C#中使用log4net框架做日誌輸出
阿新 • • 發佈:2018-05-11
repos com cep man utf info epo fin code
一、用法
1、引入包:https://www.nuget.org/packages/log4net/
2、Main函數
using System; using System.IO; using log4net; using log4net.Config; namespace Log4NetDemo { class Program { static void Main(string[] args) { var repository = LogManager.CreateRepository("NETCoreRepository"); XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); var log = LogManager.GetLogger("NETCoreRepository", typeof(Program)); log.Info("this is a info."); log.Error("this is an error:", new Exception("this is error.")); log.Fatal("this is a fatal."); log.Warn("this is a warn"); Console.WriteLine("finish."); } } }
3、新建一個log4net.config配置文件,並設置輸出到程序目錄下。
<?xml version="1.0" encoding="UTF-8"?> <configuration status="ON"> <log4net> <appender name="ConsoleAppender"type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd‘.log‘" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root level="ALL"> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
4、效果:
C#中使用log4net框架做日誌輸出