1.安装log4包
2.新建一个xml格式的配置文件,可以任意名字,例如起名叫log4config.xml
3.添加配置信息,主要是
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">这个节点的内容。
参考地址:
1.RollingFileAppender Class (apache.org)
2.Apache log4net – Apache log4net: Config Examples - Apache log4net
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="./logTom2/log.txt" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net"> <file value="./LogTom/log2021" /> <appendToFile value="true" /> <!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])--> <rollingStyle value="Composite" /> <RollingStyle value="Date" /> <staticLogFileName value="false" /> <datePattern value="yyyy.MM.dd'.log'" /> <!--最多产生的日志文件数,超过则只保留最新的n个。设定值value="-1"为不限文件数--> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout,log4net"> <ConversionPattern value="%d [%t] %-5p %c - %m%n" /> <Header value="
----------------------Header--------------------------
" /> <Footer value="
----------------------Footer--------------------------
" /> </layout> </appender> <!-- Setup the root category, add the appenders and set the default level --> <root> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <!--<appender-ref ref="FileAppender" />--> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
4.在startup类中依赖注入log4net
public static ILoggerRepository LogRepository { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; LogRepository = LogManager.CreateRepository("NETCoreRepository"); //仓库的名字可以在配置文件中配置,也可以直接写死 XmlConfigurator.Configure(LogRepository, new FileInfo("log4Config.xml")); //读取配置文件 }
5.在action中使用
_log.Info(userModel.firstName); _log.Error(DateTime.Now.ToString() + " error test");