Windows服务使用log4net记录日志
该文章是系列文章 基于.NetCore和ABP框架如何让Windows服务执行Quartz定时作业 的其中一篇。
比较流行的日志组件有以下四种,Topshelf都有相应的组件提供
本篇文章主要介绍log4net的使用。
配置log4net
在使用Topshelf创建Windows服务中提到了当我们调试的时候Console会打印出如下的类似日志
Configuration Result:
[Success] Name Demo.MyJob
[Success] Description Demo.MyJob Service
[Success] ServiceName Demo.MyJob
Topshelf v4.2.0.194, .NET Framework v4.0.30319.42000
The Demo.MyJob service is now running, press Control+C to exit.
该日志是如何打印出来的呢?
访问Topshelf Github的源码,在HostFactory.cs查看Run执行逻辑,日志打印是通过调用HostLogger.Get(Type type)
方法获取了LogWriter
,LogWriter是写日志接口。查看HostLogger.cs,可以看到LogWriter的默认实现,该实现包含有三个类TraceHostLoggerConfigurator.cs 继承接口HostLoggerConfigurator
、TraceLogWriterFactory.cs 继承接口LogWriterFactory
、TraceLogWriter.cs 继承接口LogWriter
。
如果我们需要实现log4net的日志访问,则需要实现三个类Log4NetLoggerConfigurator、Log4NetLoggerConfigurator、Log4NetLogWriter。我们可以自己实现,也可以使用Topshelf提供的实现,需要引用nuget包Topshelf.Log4Net
。在Run执行逻辑添加UseLog4Net
,如下所示。
public override void PostInitialize()
{
HostFactory.Run(configure =>
{
//定义服务描述
configure.SetDescription("Demo.MyJob Service");
configure.SetDisplayName("Demo.MyJob");
configure.SetServiceName("Demo.MyJob");
configure.RunAsLocalSystem();
//使用log4net记录日志
configure.UseLog4Net("App.config");
//定义操作
configure.Service<MyJobService>(service =>
{
service.ConstructUsing(_ => new MyJobService());
service.WhenStarted(async _ => await _.StartAsync());
service.WhenStopped(async _ => await _.StopAsync());
service.WhenContinued(async _ => await _.ContinueAsync());
service.WhenPaused(async _ => await _.PauseAsync());
});
});
}
在上述代码中可知,我们需要添加自己的配置文件,对log4net进行配置。注意:需将添加的配置文件的属性配置为如果较新则复制
。因为UseLog4Net关于加载配置文件的逻辑,是加载当前应用目录下的指定名称的文件。
更多关于log4net的配置请访问:https://logging.apache.org/log4net/release/manual/configuration.html
未使用log4net打印日志时,打印出来的日志是黑底白字,我们可以通过log4net配置改变打印字体的颜色,使用ManagedColoredConsoleAppender
,也可以通过RollingFileAppender在本地机器生成log日志文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<appender name="ManagedColoredConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red" />
</mapping>
<mapping>
<level value="Info" />
<foreColor value="Green" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Blue" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{ABSOLUTE} [%thread] %-5p %c{1}:%L - %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="Fatal" />
</filter>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value=".\logs\" />
<datePattern value="'my-windows-service-'dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ManagedColoredConsoleAppender" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
</configuration>
在配置文件中使用了<file value=".\logs\" />
指定了文件生成相对路径,该相对路径应指向的是应用程序当前目录下,该目录下确实生成了日志文件,但是很不爽的是在C:\Windows\System32
路径下也生成了文件。怎么解决该问题?通过log4net属性指定目录。
修改<file type="log4net.Util.PatternString" value="%property{LogsDirectory}\logs\" />
,并需要添加一行配置代码log4net.GlobalContext.Properties["LogsDirectory"] = AppDomain.CurrentDomain.BaseDirectory;
,如下所示。问题解决。
public override void PostInitialize()
{
log4net.GlobalContext.Properties["LogsDirectory"] = AppDomain.CurrentDomain.BaseDirectory;
HostFactory.Run(configure =>
{
//定义服务描述
configure.SetDescription("Demo.MyJob Service");
configure.SetDisplayName("Demo.MyJob");
configure.SetServiceName("Demo.MyJob");
configure.RunAsLocalSystem();
//使用log4net记录日志
configure.UseLog4Net("App.config");
//定义操作
configure.Service<MyJobService>(service =>
{
service.ConstructUsing(_ => new MyJobService());
service.WhenStarted(async _ => await _.StartAsync());
service.WhenStopped(async _ => await _.StopAsync());
service.WhenContinued(async _ => await _.ContinueAsync());
service.WhenPaused(async _ => await _.PauseAsync());
});
});
}
关于Appenders的特别说明
官网上哪些平台可用的Appenders表格如下
Appender | .NET Framework 1.0 | .NET Framework 1.1 | .NET Framework 2.0 | .NET Framework 3.5 | .NET Framework 4.0 | .NET Framework 4.5 | .NET Framework 3.5 Client Profile | .NET Framework 4.0 Client Profile | .NET Standard 1.3 | .NET CF 1.0 | .NET CF 2.0 | Mono | Shared Source CLI 1.0 | CLI 1.0 Compatible |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AdoNetAppender | x | x | x | x | x | x | x | x | x | x | x | x | ||
AnsiColorTerminalAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
AspNetTraceAppender | x | x | x | x | x | x | x | x | ||||||
BufferingForwardingAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
ColoredConsoleAppender | x | x | x | x | x | x | x | x | ||||||
ConsoleAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
DebugAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
EventLogAppender | x | x | x | x | x | x | x | x | x | x | ||||
FileAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
ForwardingAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
LocalSyslogAppender | x | x | x | x | x | x | x | x | x | x | x | |||
ManagedColoredConsoleAppender | x | x | x | x | x | x | x | x | ||||||
MemoryAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
NetSendAppender | x | x | x | x | x | x | x | x | ||||||
OutputDebugStringAppender | x | x | x | x | x | x | x | x | x | x | x | |||
RemoteSyslogAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
RemotingAppender | x | x | x | x | x | x | x | x | x | x | x | |||
RollingFileAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
SmtpAppender | x | x | x | x | x | x | x | x | x | x | ||||
SmtpPickupDirAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
TelnetAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
TraceAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
UdpAppender | x | x | x | x | x | x | x | x | x | x | x | x | x | x |
由表格得知 ManagedColoredConsoleAppender 不支持 .NET Standard 1.3。
访问 Apache GitHub 镜像 Mirror of This is the Apache log4net logging project git repository
https://github.com/apache/logging-log4net/blob/master/netstandard/log4net/log4net.xproj
与官网说明不一致,官网说支持 ColoredConsoleAppender,不支持 ManagedColoredConsoleAppender,但是代码显示对于.Net Core来说,ManagedColoredConsoleAppender可用。