This is simple usage of log4net
By name we can know log4net is a logging tool for .net application, from log4j, it’s generic version on java platform is well known by developers.
There are some simple steps to active a log by log4net in our .net code, what I record here is just a most simple case, and more parameters and layout define for log can be easily found from apache web.
Setp1 of course you need add log4net dll to your application.
Step2 create a config file and name is as “log4net.config”, like follow:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net-net-1.2"/>
</configSections>
<log4net>
<logger name="EPS.Logging">
<level value="ALL"/>
<appender-ref ref="LogFileAppender" />
</logger>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value=".//temp//" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyyMMdd".txt"" />
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] "/>
<param name="Footer" value="[Footer] "/>
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
</log4net>
</configuration>
Setp3 need let your application notice this config by add one line in AssemblyInfo.cs if you are running winform app or console app.
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
If it’s a web or web service project you need add one more line at Global.ascx.cs like follow:
protected void Application_Start(object sender, EventArgs e)
{log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));}
To let the config file be loaded when application is started.
Step4 as we config the log name as “EPS.Logging”, we can use it in our code like follow:
class Program
{
static void Main(string[] args)
{
log4net.LogManager.GetLogger("EPS.Logging").Debug("begin log");
log4net.LogManager.GetLogger("EPS.Logging").Fatal("end");
}
}
The result is we can find the log file in temp folder like follow:
[Header]
2010-01-14 14:36:44,896 [10] DEBUG EPS.Logging [(null)] - begin log
2010-01-14 14:36:44,911 [10] FATAL EPS.Logging [(null)] - end
[Footer]
That’s all