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)
- Exception trigger:
100 / b. Since variableb=0, aDivideByZeroExceptionwill be thrown. - Catch exception:
catch (Exception ex)catches all exceptions derived fromException. - 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
Exceptioninstance, itautomatically outputs the full stack trace (StackTrace), including source location and call chain.
- First argument: custom log message (here we pass the short exception description
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
Previous: Standalone configuration file