如何在 Windows 服务中初始化 Serilog?

Ber*_*ian 1 .net windows-services initialization serilog

我有以下问题。我希望能够Serilog在 Windows 服务中使用,但我不知道它应该在哪里初始化:

目前我在我的初始化它Main

using Serilog;

public static void RunService() {
    Log.Logger = new LoggerConfiguration()
      .WriteTo.RollingFile([some path])
      .CreateLogger();

    MyService daemon = new MyService();
    Log.Information("Service initialized")

    ServiceBase[] services;
    services = new ServiceBase[] {
        service
    };
    Log.Information("Before running the service");
    ServiceBase.Run(services);
}

static void Main(string[] args) {
   RunService();
}
Run Code Online (Sandbox Code Playgroud)

服务

public class MyService:ServiceBase{
   protected override void OnSessionChange(SessionChangeDescription changeDescription) {
    Log.Information("session changed");
   } 
   protected override void OnStart(string[] args) {
     Log.Information("Started service");
   }
}
Run Code Online (Sandbox Code Playgroud)

因此,为了SerilogMain运行服务集合的服务和目标服务中使用它应该如何完成?

Cai*_*ete 5

一个常见的做法是做你正在做的事情 - 即在最开始初始化日志记录并将记录器存储在Log.Logger- 然后,在你的服务中,获取上下文记录器,Log.ForContext<T>. 例如

using System.ServiceProcess;
using Serilog;

namespace WindowsServiceHost
{
    public partial class MyService : ServiceBase
    {
        private readonly ILogger _log = Log.ForContext<MyService>();

        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _log.Information("Service starting...");
            // ...

            _log.Information("Service started.");
        }

        protected override void OnStop()
        {
            _log.Information("Service stopping...");
            // ...

            _log.Information("Service stopped.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这使得访问 Serilog 的记录器变得非常简单,并且具有为您提供上下文信息的额外好处有关日志消息来自何处的,这很有用。

您可能有兴趣阅读以下内容:上下文和相关性 – .NET 中的结构化日志概念 (5)


另外,不要忘记Log.CloseAndFlush()在服务停止之前调用,以确保任何缓冲的消息都写入接收器。

static class Program
{
    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.File(@"C:\SomePath\MyApp.log")
            .CreateLogger();

        try
        {
            var servicesToRun = new ServiceBase[]
            {
                new MyService(),
            };

            ServiceBase.Run(servicesToRun);
        }
        catch(Exception ex)
        {
            Log.Fatal(ex, ex.Message);
            throw;
        }
        finally
        {
            Log.CloseAndFlush(); // <<<<<<<<<<<<<<<<<<<
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中阅读有关此内容的更多信息:记录器的生命周期