简体   繁体   中英

Log4Net Logging Exceptions

I know I can log exceptions to the database using Log4Net, but I want to break up what it stores for an exception into different columns.

Does anyone know if this is available, if anyone has done this or is it just easier to log exceptions to the database manually?

Cheers Anthony

UPDATE:

If it helps maybe use the following:

  • Does anyone know if this is available?
    • These are the sort of details I am after:
      • ExceptionType
      • ExceptionMessage
      • ExceptionSource
      • ExceptionTargetSite
      • ExceptionStackTrace
  • If anyone has done this?
  • Is it just easier to log exceptions to the database manually?

Maybe the change in format will help.

If you don't want to use something like ELMAH , a dodgy way might be catching all exceptions by overriding Page.ProcessRequest (dodgy because it is marked for infrastructure use only)

public override void ProcessRequest(HttpContext context)
{
    try
    {
        base.ProcessRequest(context);
    }
    catch (Exception e)
    {
        log.ErrorFormat(e.Message); // Log exception message, or
        log.ErrorFormat(e.ToString()); // Log stack trace
        throw;
    }
}

As requested, you can use the approach outlined here: Log4Net available database fields for adoappender - seems there are a few more ie method_name? to use custom properties in the log4net ThreadContext to possibly save this extra information about the exceptions in something like the following:

public void LogDetailedException (LogLevel level, string message, Exception exception)
{
    log4net.ThreadContext.Properties["exceptionType"] = exception.GetType().AssemblyQualifiedName;
    // appropriate logging statement
    log4net.ThreadContent.Properties.Remove("exceptionType"); // clear it, so it's not used in future calls
}

And then in your pattern:

<conversionPattern value="%property{exceptionType}" />

It's worth testing/researching to see if this is thread-safe (the name would imply that it is, but it can't hurt to check). You'll also want to make sure subsequent logs don't include this data in their messages (ie, make sure it's cleared).

(marked was wiki as this isn't specifically my answer, just a gathering of various info and discussion in the comments on Mitch's answer).

ELMAH is a great pick. A less known library is CuttingEdge.Logging . Just as ELMAH, it allows logging the exception type, message and stack trace to a table in the database.

使用AdoNetAppender类 ,或者使用不满足您需求的类,编写您自己的自定义Appender

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM