Search code examples
asp.net.netxmlconfigurationserilog

How to use only custom columns in Serilog.Sinks.MSSQLServer in XML?


We are moving our logging from log4net to Serilog. We were logging from log4net into our remote MSSQL server. We need to keep that table and the columns intact because other teams are using it, but we need to send our Serilog logs into it. Looking into https://github.com/serilog/serilog-sinks-mssqlserver I could not see how we can link our old columns to the log data. I can add columns within the Columns tag and remove all the standard columns, but I don't know how to log the serilog data into those columns.

So here is our current log table:

CREATE TABLE [dbo].[EventLog]
(
    [EventID] [INT] IDENTITY(1,1) NOT NULL,
    [Date] [DATETIME] NOT NULL,
    [Type] [VARCHAR](10) NOT NULL,
    [Logger] [VARCHAR](255) NOT NULL,
    [Thread] [VARCHAR](255) NOT NULL,
    [Message] [VARCHAR](MAX) NOT NULL,
    [MoResponse] [VARCHAR](MAX) NULL,
    [StackTrace] [VARCHAR](MAX) NULL,
    [MoStatus] [VARCHAR](255) NULL,
    [MoTransactionID] [VARCHAR](255) NULL,

    CONSTRAINT [PK_EventLog] 
        PRIMARY KEY CLUSTERED ([EventID] 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

I prefer not to have to create a new log table. I just don't know how to map the data serilog pops out to these columns (particularly in Web.config xml). Thanks in advance.


Solution

  • The mapping is done via the names of the properties that are available, either through the message template, or properties that were added via enrichers.

    Log.Logger("{EventID} some message", eventId);
    

    The above would map the property EventID to a field called EventID in the database.

    i.e. Every log message would need to have properties with the exact same name as the fields in the table (case-sensitive):

    • EventID
    • Date
    • Type
    • Logger
    • Thread
    • Message
    • MoResponse
    • StackTrace
    • MoStatus
    • MoTransactionID

    You'll likely want to use a set of enrichers to define most of these properties automatically. It might be easier to just write your own enricher that takes care of adding the properties that can be automatically included, calling other enrichers as needed.

    I'd recommend reading carefully the documentation for Custom Property Columns to see how they're configured, in code, and via configuration files.


    ps: It might be easier to write your own custom sink, borrowing the essential parts of Serilog.Sinks.MSSqlServer that you need.