欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# log4net

程序员文章站 2022-03-25 18:57:33
1.install-package log4net 2.add new config file, its name is log4net.config

1.install-package log4net

2.add new config file, its name is log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="all" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<appender name="console" type="log4net.appender.coloredconsoleappender">
<mapping>
<level value="error" />
<forecolor value="red, highintensity" />
</mapping>
<mapping>
<level value="info"/>
<forecolor value="green,highintensity"/>
</mapping>
<mapping>
<level value="debug"/>
<forecolor value="yellow,highintensity"/>
</mapping>
<mapping>
<level value="warn"/>
<forecolor value="purple,highintensity"/>
</mapping>
<mapping>
<level value="fatal"/>
<forecolor value="cyan,highintensity"/>
</mapping>
<layout type="log4net.layout.patternlayout">
<conversionpattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.appender.rollingfileappender">
<file value="myapp.log" />
<appendtofile value="true" />
<rollingstyle value="size" />
<maxsizerollbackups value="5" />
<maximumfilesize value="10mb" />
<staticlogfilename value="true" />
<layout type="log4net.layout.patternlayout">
<conversionpattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>

3.right click the log4net.config and set copy to output directory as 'copy always'

4.open assemblyinfo.cs and append to the end

[assembly:log4net.config.xmlconfigurator(configfile ="log4net.config")]

5. 

 private static readonly log4net.ilog logger = log4net.logmanager.getlogger(system.reflection.methodbase.getcurrentmethod().declaringtype);
        static void main(string[] args)
        {
            log4netdemo();
            console.readline();
        }

        static void log4netdemo()
        {           
            logger.info($"{datetime.now.tostring("yyyymmddhhmmssffff")}");            
            logger.error($"{datetime.now.tostring("yyyymmddhhmmssffff")}");
            logger.debug($"{datetime.now.tostring("yyyymmddhhmmssffff")}");
            logger.fatal($"{datetime.now.tostring("yyyymmddhhmmssffff")}");
            logger.warn($"{datetime.now.tostring("yyyymmddhhmmssffff")}");             
        }

C# log4net