如何在Windows Service中初始化Serilog? [英] How to initialize Serilog in Windows Service?

查看:107
本文介绍了如何在Windows Service中初始化Serilog?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我希望能够在Windows服务中使用 Serilog ,但我不知道应该在何处对其进行初始化:

I have the following issue.I want to be able to use Serilog inside a windows service and i do not know where it should be initilized:

目前,我在 Main 中对其进行了初始化:

Currently i initialize it in my 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();
}

服务

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

因此,为了在运行服务集合的 Main 中同时使用 Serilog ,应该在目标服务内部使用它吗?

So in order to use Serilog both in the Main that runs the collection of services and inside the target service how is it supposed to be done?

推荐答案

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

A common practice is to do what you're doing - i.e. Initialize logging at the very beginning and store the logger in Log.Logger - and then, within your service, get a hold of a context logger, Log.ForContext<T>. E.g.

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.");
        }
    }
}

这使得访问Serilog记录器非常简单,并具有为您提供

This makes it very simple to get access to Serilog's logger, and has the added benefit of giving you contextual information about where the log messages are coming from, which is useful.

您可能有兴趣阅读以下内容:

You might be interested in reading this: Context and correlation – structured logging concepts in .NET (5)

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

Also, don't forget to call Log.CloseAndFlush() before your service stops, to make sure any buffered messages are written to the sink(s).

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(); // <<<<<<<<<<<<<<<<<<<
        }
    }
}

您可以在文档中详细了解以下内容:记录仪的生命周期

You can read more about this in the documentation: Lifecycle of Loggers

这篇关于如何在Windows Service中初始化Serilog?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆