I configured Serilog in a dotNet app to capture an extra column of data but nothing shows up in log. I'm passing 'elapsedTime' as an extra parameter to _logger.Information(), but nothing shows up in the log table for ElapsedMilliseconds. Any ideas what I missed?
Program.cs
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.WriteTo.Console()
.WriteTo.MSSqlServer(
connectionString: Config.CONN_STRING_PROD,
tableName: "APP_SERILOG",
restrictedToMinimumLevel: LogEventLevel.Information,
columnOptions: GetSqlColumnOptions()
)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
private static ColumnOptions GetSqlColumnOptions()
{
var options = new ColumnOptions();
options.AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn
{
ColumnName = "ElapsedMilliseconds",
AllowNull = true,
DataType = SqlDbType.Int
}
};
return options;
}
ReportLoggingExtensions.cs
public static class ReportLoggingExtensions
{
public static Serilog.ILogger _logger { get; } = Log.Logger;
public static void LogSqlResponceInformation(string sqlCmd, int recordCount, TimeSpan elapsedTime)
{
Dictionary<string, string> logMessage = new Dictionary<string, string>
{
{ "Sql Responce - ", sqlCmd },
{ "Result record count", recordCount.ToString() },
{ "Execution Time", elapsedTime.ToString() }
};
_logger.Information(JsonConvert.SerializeObject(logMessage), elapsedTime);
}
}
Log Table:
select top 1 *
from APP_SERILOG
order by Id desc
Id Message Level TimeStamp Exception LogEvent ElapsedMilliseconds
1059381 {"Sql Responce - ":"RiderActivity","Result record count":"0","Execution Time":"00:00:00.1455455"} 2023-06-27 16:28:44.557 NULL NULL NULL
Trying variations: ForContext is suppose to help when attempting to log information to extra columns, but still no success.
_logger
.ForContext("ElapsedMilliseconds", elapsedTime)
.ForContext("LogId", 1)
.Information(JsonConvert.SerializeObject(logMessage));
Also tried:
using (LogContext.PushProperty("ElapsedMilliseconds", elapsedTime))
using (LogContext.PushProperty("LogId", 1))
{
_log.Information(JsonConvert.SerializeObject(logMessage));
}
The following turned out to be useful works.
Generic ILogger, or through Serilog, add logged property
Startup:
using Serilog;
using Serilog.Context;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
. . .
Log.Logger = new LoggerConfiguration()
.Enrich.WithMachineName()
. . .
.CreateLogger();
Runtime:
GlobalLogContext.PushProperty("LogId", userId);
GlobalLogContext.PushProperty("ElapsedMilliseconds", totalSeconds);
_log.Information(JsonConvert.SerializeObject(logMessage));