Log exception information

The previous chapters covered logging user‑defined content. In fact, Log4net can also log exceptions along with their full stack traces, making troubleshooting much easier for developers.

try
{
    int b = 0;
    int a = 100 / b;
}
catch (Exception ex)
{
    log.Error(ex.Message, ex);
}Code language: PHP (php)
  1. Exception trigger: 100 / b. Since variable b=0, a DivideByZeroException will be thrown.
  2. Catch exception: catch (Exception ex) catches all exceptions derived from Exception.
  3. Key logging pattern: log.Error(ex.Message, ex);
    • First argument: custom log message (here we pass the short exception description ex.Message)
    • The second argument must be the exception object ex
    • When log4net detects the second argument is an Exception instance, itautomatically outputs the full stack trace (StackTrace), including source location and call chain.
Incorrect usage (stack trace will not be printed)
//  Only passing string, stack trace is lost!
log.Error(ex.ToString());
log.Error(ex.Message);Code language: JavaScript (javascript)

This only outputs exception text. Some log formats will not expand the call stack automatically, which makes debugging difficult.

Recommended standard pattern
//  Recommended: add business context then pass the exception object
log.Error("Error occurred while performing division calculation", ex);Code language: JavaScript (javascript)

Log exception information

Leave a Reply

Your email address will not be published. Required fields are marked *