Others have posted some good links on getting the Logging Application Block (LAB) working so I won't duplicate that here.
In terms of formatting your exception you have 3 choices that I can think of:
- Use the default
Exception.ToString()
implementation (it's not bad)
- Write a Custom Formatter that integrates into the LAB.
- Write a helper function that performs the formatting and passes the string into the Write method.
If option 1 doesn't meet your needs then I would recommend going with option 3 (since option 2 is overkill).
A simple example would be something like:
catch (Exception exception)
{
Logger.Write(LogHelper.CreateExceptionString(exception));
}
...
public static string CreateExceptionString(Exception e)
{
StringBuilder sb = new StringBuilder();
CreateExceptionString(sb, e, string.Empty);
return sb.ToString();
}
private static void CreateExceptionString(StringBuilder sb, Exception e, string indent)
{
if (indent == null)
{
indent = string.Empty;
}
else if (indent.Length > 0)
{
sb.AppendFormat("{0}Inner ", indent);
}
sb.AppendFormat("Exception Found:\n{0}Type: {1}", indent, e.GetType().FullName);
sb.AppendFormat("\n{0}Message: {1}", indent, e.Message);
sb.AppendFormat("\n{0}Source: {1}", indent, e.Source);
sb.AppendFormat("\n{0}Stacktrace: {1}", indent, e.StackTrace);
if (e.InnerException != null)
{
sb.Append("\n");
CreateExceptionString(sb, e.InnerException, indent + " ");
}
}