Windows服務使用log4net記錄日誌

該文章是系列文章 基於.NetCore和ABP框架如何讓Windows服務執行Quartz定時做業 的其中一篇。html

比較流行的日誌組件有如下四種,Topshelf都有相應的組件提供git

本篇文章主要介紹log4net的使用。github

配置log4net

使用Topshelf建立Windows服務中提到了當咱們調試的時候Console會打印出以下的相似日誌apache

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 繼承接口HostLoggerConfiguratorTraceLogWriterFactory.cs 繼承接口LogWriterFactoryTraceLogWriter.cs 繼承接口LogWriter
若是咱們須要實現log4net的日誌訪問,則須要實現三個類Log4NetLoggerConfigurator、Log4NetLoggerConfigurator、Log4NetLogWriter。咱們能夠本身實現,也能夠使用Topshelf提供的實現,須要引用nuget包Topshelf.Log4Net。在Run執行邏輯添加UseLog4Net,以下所示。windows

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.htmlapp

未使用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;,以下所示。問題解決。async

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表格以下ide

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可用。字體

相關文章
相關標籤/搜索