-
需要从NuGet 中安装log4net,直接安装
- 新建一个log4net 的配置文件(xml文件),可以任意名字,例如起名叫log4net.config
- 把配置项填写进去
<?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="log-file.log" />
<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="Log/" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<RollingStyle value="Date" />
<staticLogFileName value="false" />
<datePattern value="yyyy.MM.dd'.log'" />
<!--<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>
- 在startup的构造函数中注入log4net
public static ILoggerRepository LogRepository { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
LogRepository = LogManager.CreateRepository("NETCoreRepository"); //仓库的名字可以在配置文件中配置,也可以直接写死
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config")); //读取配置文件
}
- 在Controller中实例化
先获取一个ILog对象实例
//type 是指你当前使用log的对象的类,例如需要在HomeController中使用,参数就为typeof(HomeController)
private readonly ILog _log = LogManager.GetLogger(Startup.LogRepository.Name, Type type);
- 在Action中使用
_log.Error(e.ToString());