0

I am using the below code and every time I run the code, I do see the break point hitting in LogErrorToDatabase method. However sometimes I see the log entry for the ErrorGuid in the database and sometimes I do not see any log entries. The ErrorGuid gets returned to the client side but missing DB entry.

public async Task<ActionResult<IEnumerable<Location>>> Get()
        {
            try { 
                Log.Information("Inside Locations Get");
                int a = int.Parse("?"); //Uncomment to test error handling
                return await Repo.Get<Location>().ToListAsync();
            }
            catch (Exception ex)
            {
                //Log error
                var id = Guid.NewGuid();
                await LogErrorToDatabase(ex, id);
                return BadRequest(new ErrorDetail()
                {
                    ErrorGuid = id
                });

            }
        }

        public async Task LogErrorToDatabase(Exception ex, Guid id)
        {
            await Task.Run(() => Log.ForContext("ErrorGuid", id)
                    .Error(ex, "Error occured with getting the Location List"));
        }

I have no clue on this randomness. Any help will be appreciated.

mehtav
  • 51
  • 1
  • 3
  • Does this answer your question? [Serilog MSSQL Sink doesn't write logs to database](https://stackoverflow.com/questions/52953060/serilog-mssql-sink-doesnt-write-logs-to-database) – C. Augusto Proiete Apr 22 '20 at 17:25

2 Answers2

1

There are several steps you can take troubleshoot why messages are not being written to the Serilog Sink. You can see a number of them on another answer here in SO:

Serilog MSSQL Sink doesn't write logs to database


Update: String or binary data would be truncated is a common SQL Server exception that happens when you're trying to store a value that is larger than the table field can store. For example, if you have an nvarchar(4) field and try to store abcde (5 characters) you'll get the same kind of exception.

You either have to increase the size of the fields in the database you're using to store information, or you have to limit the number of characters you're logging in your C# code.

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • I now have another problem. If my web api call logged the error once in DB and I try to call the same API again on a different page, it is not logging the error in the database the second time. Any clue? – mehtav Apr 26 '20 at 21:21
0

Thanks Calo. Your response was helpful. I turned the Audit on by switching from WriteTo to AuditTo, set "period": 1 and added Log.CloseAndFlush(); and get the below error logged to my SQL database. Help will be appreciated.

System.AggregateException: Failed to emit a log event. (String or binary data would be truncated.
The statement has been terminated.)
 ---> System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Serilog.Sinks.MSSqlServer.MSSqlServerAuditSink.Emit(LogEvent logEvent)
   at Serilog.Core.Sinks.AggregateSink.Emit(LogEvent logEvent)
ClientConnectionId:c0e1f1a4-b655-4be1-b655-c8954f44d299
Error Number:8152,State:2,Class:16
   --- End of inner exception stack trace ---
   at Serilog.Core.Sinks.AggregateSink.Emit(LogEvent logEvent)
   at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
   at Serilog.Core.Logger.Serilog.Core.ILogEventSink.Emit(LogEvent logEvent)
   at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
   at Serilog.Core.Logger.Serilog.Core.ILogEventSink.Emit(LogEvent logEvent)
   at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
   at Serilog.Core.Logger.Write(LogEventLevel level, Exception exception, String messageTemplate, Object[] propertyValues)
   at Serilog.Core.Logger.Write(LogEventLevel level, String messageTemplate, Object[] propertyValues)
   at Serilog.Core.Logger.Write[T0,T1,T2](LogEventLevel level, String messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
   at Serilog.Core.Logger.Error[T0,T1,T2](String messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
   at MCF.API.ExtensionHelpers.ExceptionMiddleware.InvokeAsync(HttpContext httpContext) in 
mehtav
  • 51
  • 1
  • 3
  • 1
    best to edit this into your _question_ and delete it.... - if you do want to @ someone, you can add a comment on their response. Also, dont type `Thanks`, we press the up diamond over the vote counter if an answer is helpful. – Ruben Bartelink Apr 23 '20 at 00:21