ablaze
ablaze

Reputation: 722

Serilog SQL Sink Log Server Name and ASPNETCORE_ENVIRONMENT as columns

My application is running on a load balanced web server environment. Also, in lower environments, the SQL database for logging is shared across multiple environments. I would like to record server name and environment name as two separate columns in addition to the default columns. How do I configure the SQL server sink in the startup.cs?

These columns are not the part of the standard columns supported by the sink.

Below is current schema, with two extra 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

From the documentation, it looks like I need to configure the column something as following ... (For some reason, their documentation does not seem to up to date with Serilog.Sinks.MSSqlServer version 5.1.2)

Here what I think I need to use

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}
    }
};

In log4net, I used to set it as following:

private string serverName = System.Net.Dns.GetHostName();
...
log4net.ThreadContext.Properties["Server"] = serverName;

Upvotes: 1

Views: 1317

Answers (1)

ablaze
ablaze

Reputation: 722

The solution turned out to be quite straightforward and it kinda dawned upon me. I am not sure if I should use a nuget package for this but it took just 2 more lines of code, to get it working:

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

Upvotes: 2

Related Questions