Serilog SQL Sink日志服务器名称和ASPNETCORE_ENVIRONMENT作为列

时间:2019-04-09 07:25:07

标签: serilog

我的应用程序正在负载平衡的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;

1 个答案:

答案 0 :(得分:0)

事实证明,解决方案非常简单,它突然出现在我身上。我不确定是否应该为此使用nuget package,但仅花了两行代码即可使其正常工作:

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