log4net
log4net 是一个可以帮助程序员把日志信息输出到各种 不同目标的 .NET 类库。Fireasy 提供了 log4net 对 日志管理器 的实现。
修改配置文件如下:
- .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="fireasy">
<section name="loggings" type="Fireasy.Common.Logging.Configuration.LoggingConfigurationSectionHandler, Fireasy.Common"/>
</sectionGroup>
</configSections>
<fireasy>
<loggings managed="Fireasy.Log4net.LogFactory, Fireasy.Log4net">
<!--<logging name="log4net" type="Fireasy.Log4net.LogFactory,Fireasy.Log4net" />-->
</loggings>
</fireasy>
</configuration>
- .Net Core 下的 appsettings.json 文件
{
"fireasy": {
"loggings": {
"settings": {
"nlog": {
"type": "Fireasy.Log4net.LogFactory, Fireasy.Log4net"
}
}
}
}
}
在 .Net Core 应用中可以使用扩展方法 AddLog4netLogger 切换到 log4net 日志组件。如下所示:
namespace demo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddFireasy().AddLog4netLogger(s =>
{
s.XmlFile = "mynlog.confg";
});
}
}
}
log4net 默认使用 log4net.config 配置文件,你可以由以上的参数设置自定义配置文件。以下是 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="logfile/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>