Logging with Context InformationOnce you start using logging prevalently in your code, eventually you will want to add custom information into your log messages. This is especially helpful in a large distributed system that has centralized logging to a database or a Web service. You are going to want to know the IP address of the computer, possibly the user logged on at the time of the error, and other specific context information. Log4Net allows for adding context information in your log message with two different classes. Both classes are thread-safe and have their advantages and disadvantages. MDCThe Mapped Diagnostic Context (MDC) is implemented as a Dictionary value-key pair lookup. One of the nice features of the MDC is that you have a greater control over the message output than you do with the NDC. Later in this chapter, Listing 8.12 on p. 215 shows using MDC with WMI. You can see in the config file that you can put mapped information anywhere in the conversion pattern string. However, this does come with a price, which is that the Dictionary key used in the code (i.e., clock) has to match exactly in the config file's conversion pattern string (i.e., %X{clock} ). NDCThe Nested Diagnostic Context (NDC) is similar to the MDC, except that it is Stack-based rather than Dictionary-based. Listing 8.10 shows the use of the NDC. Listing 8.10. Nested Diagnostic Contextusing(log4net.NDC.Push(System.Environment.UserName.ToString())) { if(_logger.IsDebugEnabled) { _logger.Debug("This is just a test of using NDC."); } } The config file Pattern Layout looks like this:<layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" /> </layout> The disadvantage is that in the config file, the %x outputs all the information built up in the NDC. The bright side is that you do not have to worry about matching up strings in your code with strings in your configuration file. Another advantage to the NDC is that you can wrap the code in a C# using statement, which will automatically call the NDC's disposal code and clean up resources for you. |