23

When I use log4net for logging in .NET4.0 I use the following code

LogManager declaration:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

And when used in code:

log.Info("My info text");

This outputs the following to the log-file:

2013-10-01 14:41:11,010 [3] INFO  MyNamespace.MyClass [(null)] - My info text

I am wondering what the [(null)] means and how I can remove/change it?

This is my config-file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <log4net>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="log-file.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>
UncleBlue
  • 265
  • 1
  • 2
  • 7
  • Just a little simplification. Instead of `LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);` just do `LogManager.GetLogger(typeof(MyClassName));` – user2359695 Oct 20 '14 at 20:26

2 Answers2

28

Fix

To stop it appearing in the log remove [%property{NDC}] from the config file.

This happens because log4net automatically populates a context of information that might be useful for logging - in some cases this might result in a null value.


log4net NDC

This post explains how to use NDC: When to use 'nested diagnostic context' (NDC)?

In short log4net calls the static method log4net.NDC.Push to set the context of the the code.

You could for example set the NDC manually by running the following:

log4net.NDC.Push("context")

From that point forward outputting a log message will supply %property{NDC} as the string context.


UPDATE:

NDC.Push has been deprecated. Alternatively, you can use ThreadContext.Stacks["NDC"].Push("context")

janniks
  • 2,942
  • 4
  • 23
  • 36
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
20

if you just want the (null) to disappear you can also set log4net.Util.SystemInfo.NullText to some other value like "" or string.Empty, it will use that instead.

janniks
  • 2,942
  • 4
  • 23
  • 36
Cees Kaas
  • 241
  • 2
  • 6