Windows效劳运用log4net纪录日记

2019年7月2日11:05:04Windows效劳运用log4net纪录日记已关闭评论 381

该文章是系列文章 基于.NetCore和ABP框架怎样让Windows效劳实行Quartz准时功课 的个中一篇。

对照盛行的日记组件有以下四种,Topshelf都有响应的组件供应

  • log4net
  • NLog
  • serilog
  • Elmah

本篇文章重要引见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
Windows效劳运用log4net纪录日记
与官网申明不一致,官网说支撑 ColoredConsoleAppender,不支撑 ManagedColoredConsoleAppender,然则代码显现关于.Net Core来讲,ManagedColoredConsoleAppender可用。

avatar