Serilog SQL Sink Log Server Name和ASPNETCORE_ENVIRONMENT列

问题描述 投票:0回答:1

我的应用程序在负载均衡的Web服务器环境中运行。此外,在较低的环境中,用于日志记录的SQL数据库在多个环境中共享。除了默认列之外,我想将服务器名称和环境名称记录为两个单独的列。如何在startup.cs中配置SQL Server接收器?

这些列不是接收器支持的the standard columns的一部分。

下面是当前架构,有两个额外的列......

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Logs]') AND type in (N'U'))
BEGIN
    DROP TABLE [dbo].[Logs]
END
CREATE TABLE [dbo].[Logs](
    [Id] [int] IDENTITY(1,1) NOT NULL,

    [Environment] [nvarchar](60) NULL,
    [ServerName] [nvarchar](60) NULL,

    [Message] [nvarchar](max) NULL,
    [MessageTemplate] [nvarchar](max) NULL,
    [Level] [nvarchar](128) NULL,
    [TimeStamp] [datetimeoffset](7) NOT NULL,
    [Exception] [nvarchar](max) NULL,
    [Properties] [xml] NULL,
    [LogEvent] [nvarchar](max) NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

从文档中,我看起来需要将列配置为以下内容...(出于某种原因,他们的文档似乎与Serilog.Sinks.MSSqlServer版本5.1.2不兼容)

在这里我认为我需要使用

var sqlLogTableColumnOptions = new ColumnOptions
{
    AdditionalDataColumns = new Collection<DataColumn>
    {
        new DataColumn{ ColumnName = "Environment", DataType = typeof(string), MaxLength= 60},
        new DataColumn{ ColumnName = "ServerName", DataType =  typeof(string), MaxLength = 60}
    }
};

在log4net中,我曾经将它设置如下:

private string serverName = System.Net.Dns.GetHostName();
...
log4net.ThreadContext.Properties["Server"] = serverName;
serilog
1个回答
0
投票

事实证明这个解决方案很简单,有点恍然大悟。我不确定我是否应该使用nuget package,但它只需要2行代码,以使其工作:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithProperty("ServerName", Environment.MachineName or System.Net.Dns.GetHostName()) // whatever you need to log
    .Enrich.WithProperty("Environment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production")
    ... // rest of the code in Startup.cs
© www.soinside.com 2019 - 2024. All rights reserved.