Three types of logging context available in Log4Net.
- Log4Net.GlobalContext :- This context shared across all application threads and domains.If two threads set the same property on GlobalContext, One Value will override the other.
- Log4Net.ThreadContext :- This context scope limited to calling thread. Here two threads can set same property to different values without overriding to each other.
- Log4Net.ThreadLogicalContext :- This context behaves similarly to the ThreadContext. if you're working with a custom thread pool algorithm or hosting the CLR, you may find some use for this one.
Open Visual Studio, create a new console project, and add a reference to the log4net assembly. Add the following code to your program.cs file:
namespace Log4Net_Context{ class Program { private static log4net.ILog Log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); static void Main( string[] args ) { log4net.Config.XmlConfigurator.Configure(); log4net.ThreadContext.Properties[ "myContext" ] = "Logging from Main"; Log.Info( "this is an info message" ); Console.ReadLine(); } }}
Add the parameter definition for the custom column:<configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger (%property{myContext})
[%level]- %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
</configuration>
Run your application and check the log file, you we find the addition data property.
Nice explanation! Thank you, I was looking for it.
ReplyDelete