0

I've been trying to configure Serilog to use the MSSqlServer sink. As long as I'm using the default error table provided by Serilog, then it works as expected. However, I'm going to be using the same table in the same database for multiple projects, so I wanted to add a "Source" column which would contain the current assembly's name automatically.

I have the following:

"Serilog": {
      "Using": [
        "Serilog.Sinks.File",
        "Serilog.Sinks.MSSqlServer"
      ],
      "MinimumLevel": "Information",
      "WriteTo": [
        {
          "Name": "File",
          "Args": {
            "path": "Logs/log-.txt",
            "rollingInterval": "Day",
            "rollOnFileSizeLimit": true,
            "retainedFileCountLimit": 7,
            "fileSizeLimitBytes": 10000000,
            "flushToDiskInterval": "00:00:10"
          }
        },
        {
          "Name": "MSSqlServer",
          "Args": {
            "connectionString": "Server=xxxxxxxx",
            "tableName": "Error_Logs",
            "autoCreateSqlTable": true,
            "columnOptions": {
              "additionalColumns": [
                {
                  "ColumnName": "Source",
                  "DataType": "nvarchar(128)",
                  "AllowNull": false
                }
              ],
              "customColumns": [
                {
                  "PropertyName": "Source",
                  "ColumnName": "Source",
                  "DataType": "nvarchar(128)"
                }
              ],
              "minimumLevel": "Error"
            }
          }
        }
      ]
    }

In my Program.cs, I have the following:

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration, "AppSettings:Serilog")
    .Enrich.FromLogContext()
    .CreateLogger();

The issue is that I am getting this:

2023-02-20T15:40:48.8728390Z Unable to write batch of 1 log events to the database due to following error: Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Source', table 'XXXX.dbo.Error_Logs'; column does not allow nulls. INSERT fails.
The statement has been terminated.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.SqlBulkCopy.RunParser(BulkCopySimpleResultSet bulkCopyHandler)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinuedOnSuccess(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsync(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource`1 source)
--- End of stack trace from previous location ---

I have tried a bunch of things such as:

Adding: .Enrich.WithProperty("Source", Assembly.GetExecutingAssembly().GetName().Name)

Adding: LogContext.PushProperty("Source", Assembly.GetExecutingAssembly().GetName().Name);

Adding: "Enrich": ["WithAssemblyName"] at the end of the appsettings.json file

Etc... But nothing has worked and all have produced this issue.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Skyhighjinks
  • 162
  • 1
  • 1
  • 10
  • [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Thom A Feb 20 '23 at 15:58
  • Does this answer your question? [Populate custom columns in Serilog MsSql sink](https://stackoverflow.com/questions/64308665/populate-custom-columns-in-serilog-mssql-sink) – quaabaam Feb 20 '23 at 17:34
  • @quaabaam Not exactly, I don't want to have to insert it every time I want to log a message or something. The idea is I'd do something like: `_Logger.LogError("This is my error");` and it'd auto populate the `[Source]` column with the current assembly without having to reference it every time, if that makes sense? – Skyhighjinks Feb 20 '23 at 18:28
  • Perhaps to debug - make the column nullable (by whatever means is easiest) and look at which events end up logged without a source. – Nicholas Blumhardt Feb 20 '23 at 22:38
  • @NicholasBlumhardt The field doesn't seem to be populating the `[Source]` column at all sadly. – Skyhighjinks Feb 21 '23 at 11:53

0 Answers0