C# log4net

    xiaoxiao2023-03-24  6

    ## log4net * 参考链接:http://www.codeproject.com/Articles/140911/log-net-Tutorial * 上面的链接里的工程里有log4net.dll

    添加步骤

    新建winform(just for example)在里面添加引用log4net.dll(上面提到的)配置App.config

    在Program.cs的namespace外添加

    [assembly: log4net.Config.XmlConfigurator(Watch = true)]

    在主窗口对应的cs文件中添加变量

    //Here is the once-per-class call to initialize the log object private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    其实这个在哪里添加都行,之后输出日志文件时,跟踪的就是调用的log变量对应的cs文件。

    配置完成

    在哪里需要输出日志文件,就在该处添加像以下的代码即可

    log.Debug("Debug logging"); log.Info("Info logging"); log.Warn("Warn logging"); log.Error("Error logging"); log.Fatal("Fatal logging");

    App.config的配置问题

    在里面可以配置日志文件的路径、文件名、是否滚动输出日志(设置为是时,当输出日志文件的大小大于设置的阈值时,会删除最早的日志文件)可以设置输出的日志文件的等级可以参考链接中的代码的配置

    我的App.config文件内容

    <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!-- This writes the log information to the console window. It only logs events that are at least at the INFO level (which would mean that DEBUG events are not captured. --> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newlineExtra Info: %property{testProperty}%newline%exception"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="INFO"/> <levelMax value="FATAL"/> </filter> </appender> <!-- This stores information in the mylogfile.txt file. It only captures log events that contain the key word test or error. --> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="./log/log.txt"/> <appendToFile value="true"/> <rollingStyle value="Size"/> <maxSizeRollBackups value="5"/> <maximumFileSize value="10MB"/> <staticLogFileName value="true"/> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="INFO"/> <levelMax value="FATAL"/> </filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline%exception"/> </layout> </appender> <root> <level value="INFO"/> <appender-ref ref="RollingFileAppender"/> </root> </log4net>

    通过代码配置log4net

    有时候希望日志文件的名称和程序运行时刻有关,同时又不能随着程序的运行时间而变化(即在每次程序运行时,只产生一个日志文件),而通过xml配置时,要么是固定的文件名,要么是随着程序的运行时间变化而产生不同的日志文件。因此考虑通过代码来设置日志的文件名。在程序启动时,需要配置一下文件名。

    具体的代码如下

    log4net.Config.BasicConfigurator.Configure(new log4net.Appender.FileAppender(new log4net.Layout.PatternLayout("%date [%thread] %level %logger line%L - %message%newline%exception"), String.Format("./log/log-{0}.log", DateTime.Now.ToString("yyyyMMdd-HHmmss")), false));
    转载请注明原文地址: https://ju.6miu.com/read-1202575.html
    最新回复(0)