1.首先需要同nuget安装log4net和Microsoft.Extensions.Logging.Log4Net.AspNetCore,安装完成之后如下:
2.在netcore项目的program中添加log4net组件
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) //netcore配置log4net .ConfigureLogging((context, loggingbuilder) => { loggingbuilder.AddFilter("System", LogLevel.Warning); loggingbuilder.AddFilter("Microsoft", LogLevel.Warning); loggingbuilder.AddLog4Net();//添加log4net记录日志 }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
3.以上配置表示默认读取根目录log4net.config文件,所以需要在网站根目录创建一个配置文件,名称:log4net.config
<?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="DebugAppender" type="log4net.Appender.DebugAppender" > <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <!--指定日记记录方式,以滚动文件的方式(文件记录)--> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <file value="log4net/Info/" /> <!--是否是向文件中追加日志--> <appendToFile value="true" /> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--每个文件最大1M--> <param name="maximumFileSize" value="1MB" /> <!--日志根据日期滚动--> <param name="RollingStyle" value="Date" /> <!--日志文件名格式为:logs_20080831.log--> <param name="DatePattern" value=""logs_"yyyyMMdd".log"" /> <!--日志文件名是否是固定不变的--> <param name="StaticLogFileName" value="false" /> <!--布局--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <!--读取debug=>info级别的日志--> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="INFO" /> </filter> </appender> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <file value="log4net/Error/" /> <!--是否是向文件中追加日志--> <appendToFile value="true" /> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--每个文件最大1M--> <param name="maximumFileSize" value="1MB" /> <!--日志根据日期滚动--> <param name="RollingStyle" value="Date" /> <!--日志文件名格式为:logs_20080831.log--> <param name="DatePattern" value=""logs_"yyyyMMdd".log"" /> <!--日志文件名是否是固定不变的--> <param name="StaticLogFileName" value="false" /> <!--布局--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <!--读取错误日志--> <param name="LevelMin" value="ERROR" /> </filter> </appender> <root> <!--读取所有级别日志--> <level value="ALL"/> <appender-ref ref="DebugAppender" /> <appender-ref ref="InfoAppender" /> <appender-ref ref="ErrorAppender" /> </root> </log4net>
这个配置文件表示的是创建两个文件加,Info存储一般日志,Error文件夹存储错误日志
使用方法: