1.引入Nuget包
log4net
2.添加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="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">
<file value="logfile/" /> //指定日志文件保存的目录
<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> <!-- 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>
3.在StartUp.cs中配置log4Net
//为StartUp.cs添加属性
public static ILoggerRepository repository { get; set; } public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
//log4net
repository = LogManager.CreateRepository("NETCoreRepository");
//指定配置文件
XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); }
4.在程序中中使用log4Net写日志
下面是注入到控制器中的示例
public class HomeController : Controller
{
//log4Net
private ILog log;
public UploadFilesController(IHostingEnvironment hostingEnv)
{
//log4Net
this.log = LogManager.GetLogger(Startup.repository.Name, typeof(HomeController));
}
public IActionResult Index()
{
var name = message.Name;
var age = message.Age;
log.Error("error message");
return View();
}
}