Windows 使用 SeriLog 的服务没有日志保存到 MS SQL 服务器

Windows Service Using SeriLog No Logs Saved To MS SQL Server

我创建了一个 .net 框架 windows 服务应用程序,它应该使用 serilog 和 MS SQL 服务器来记录消息和任何潜在的错误。我的问题是没有任何内容被记录到 MS SQL 服务器,所以我不确定是什么问题。

举个例子(我删除了我的敏感代码)——我在 publice Service1() 方法中对 SeriLog 进行了初始化,然后我想要一个进程每 5 分钟 运行,所以在 OnStart() 我有定时器设置,我使用这个代码

public Service1()
{
    InitializeComponent();

    var log = new LoggerConfiguration()
        .WriteTo.MSSqlServer(
            connectionString: "data source=ZZZZZZZZ;Initial Catalog=ZZ;Persist Security Info=False;User Id=ZZ; Password=ZZZ;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;",
            sinkOptions: new SinkOptions
            {
                TableName = "SeriLog",
                SchemaName = "dbo",
                AutoCreateSqlTable = false
            })
        .CreateLogger();
}

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 300000;
    timer.Enabled = true;
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    GetData().GetAwaiter().GetResult();
}
private static async Task GetData()
{
    Log.Information("Started Grabbing Data");
}

现在有没有人看到任何可以阻止日志记录发生的东西?

编辑
我在控制台应用程序中使用了这个确切的代码,它正在写入 SQL 服务器,但是当我发布我的 Windows 服务应用程序并将其 运行ning 作为服务时,没有日志曾经记录过。

解决 Serilog 问题时,您应该做的第一件事是启用 SelfLog, to see if there are any exceptions being thrown. For instance, if the sink is not able to connect to SQL Server, or if there's something wrong with the table, you'll get an error message in the SelfLog

Serilog.Sinks.MSSqlServer 是一个“定期批处理接收器”,因此日志不会立即写入数据库。您可能需要调整 configuration options related to batching of messages. Also remember to flush your logs when the service stops otherwise you might lose messages. See Lifecycle of Loggers.

您可以采取许多步骤来解决 SQL 服务器接收器无法正常工作的原因。下面这个答案中描述了常见的:

您正在初始化 var log,但正在通过静态 Log class 登录。要启用静态 Log class,您需要初始化 Log.Logger.