Serilog MSSQL Sink不会将日志写入数据库

我创建了一个.Net类库(4.6.2)并创建了serilog实现,它由其他接口(如控制台应用程序)调用。 现在,当我使用文件接收器类型时,日志将被写入文件但是使用MSSQL接收器,它没有这样做。 使用autoCreateTable选项提供的列选项创建日志表

ILogger logger = new LoggerConfiguration() .WriteTo.MSSqlServer(connectionString, tableName, autoCreateSqlTable: autoCreateSqlTable, restrictedToMinimumLevel: LogEventLevel.Verbose, columnOptions: GetSQLSinkColumnOptions(), batchPostingLimit: batchPostingLimit) .CreateLogger(); 

我还启用了serilog的自我记录,但没有显示exception。 找不到任何有用的解决方案。

但是生成了日志表。 我已检查用户的权限,并且还具有正确的权限。

下面是代码的快照。

 public static class GenericLogger { private static ILogger _usageLogger; private static ILogger _errorLogger; static GenericLogger() { var logTypes = LogConfigurationHelper.GetLogTypes(); if (logTypes != null && logTypes.Count > 0) { foreach (var logType in logTypes) { ConfigureLogger(logType.Id); // Intitalizes logs based on //configuration. } } Serilog.Debugging.SelfLog.Enable(msg => { Debug.Print(msg); Debugger.Break(); }); } ///The write log function /// public static void WriteError(LogDetail infoToLog) { if (infoToLog.Exception != null) { infoToLog.Message = GetMessageFromException(infoToLog.Exception); } _errorLogger.Write(LogEventLevel.Information, "{Timestamp}{Product}{Layer}{Location}{Message}" + "{Hostname}{UserId}{UserName}{Exception}{ElapsedMilliseconds}" + "{CorrelationId}{CustomException}{AdditionalInfo}", infoToLog.TimeStamp, infoToLog.Product, infoToLog.Layer, infoToLog.Location, infoToLog.Message, infoToLog.Hostname, infoToLog.UserId, infoToLog.UserName, infoToLog.Exception?.ToCustomString(), infoToLog.ElapsedMilliseconds, infoToLog.CorrelationId, infoToLog.CustomException, infoToLog.AdditionalInfo); // To add ((IDisposable) _errrorLog).Dispose(); } } 

以下是一些可以帮助您排除故障的想法:


您是仅使用VerboseDebug事件进行测试吗? 这可能是原因。 您没有为Serilog指定全局最小级别(您只指定了接收器的最小级别,它充当filter), 默认最小值是Information ,这意味着将忽略VerboseDebug …指定MinimumLevel的全局MinimumLevel:

 ILogger logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.MSSqlServer(connectionString, tableName, autoCreateSqlTable: autoCreateSqlTable, restrictedToMinimumLevel: LogEventLevel.Verbose, columnOptions: GetSQLSinkColumnOptions(), batchPostingLimit: batchPostingLimit) .CreateLogger(); 

你正在处理你的记录器吗? Serilog.Sinks.MSSqlServer是一个“定期批处理接收器”,因此您需要确保在最后处置记录器以强制它将日志刷新到数据库。 请参阅记录器的生命周期 。

 ((IDisposable) logger).Dispose(); 

即使您使用1作为batchPostingLimit , 它在将日志发送到数据库之前默认等待5秒 。 如果您的应用在此期间之前关闭并且您没有丢弃记录器,则消息将丢失。


为了排除故障,请使用AuditTo而不是WriteTo (并删除不适用于审计的batchPostingLimit )。 WriteTo是安全的,会吃任何exception,而AuditTo会让exception冒出来。

 ILogger logger = new LoggerConfiguration() .AuditTo.MSSqlServer( connectionString, tableName, restrictedToMinimumLevel: LogEventLevel.Verbose, autoCreateSqlTable: true) .CreateLogger(); 

当然,一旦弄清楚出了什么问题,请回到WriteTo