我创建了一个 .Net 类库(4.6.2)并创建了由其他接口(interface)(如控制台应用程序)调用的 serilog 实现。现在,当我使用文件接收器类型时,日志被写入文件,但使用 MSSQL 接收器,它不会这样做。
使用 autoCreateTable 选项提供的列选项创建日志表
ILogger logger = new LoggerConfiguration()
.WriteTo.MSSqlServer(connectionString,
tableName,
autoCreateSqlTable: autoCreateSqlTable,
restrictedToMinimumLevel: LogEventLevel.Verbose,
columnOptions: GetSQLSinkColumnOptions(),
batchPostingLimit: batchPostingLimit)
.CreateLogger();
我还启用了 serilog 的自我记录,但没有显示异常。没有找到任何有用的解决方案。
然而,日志表正在生成。我已经检查了用户的权限,并且也具有正确的权限。
下面是代码的快照。
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();
}
}
最佳答案
以下是一些可以帮助您排除故障的想法:
您是否正在使用 Verbose
进行测试?或 Debug
仅限事件?这可能是原因。您没有为 Serilog 指定全局最低级别(您只为作为过滤器的接收器指定了最低级别)和 default minimum is Information
, 这意味着 Verbose
和 Debug
正在被忽略... 指定全局 MinimumLevel
对于 Serilog:
ILogger logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.MSSqlServer(connectionString,
tableName,
autoCreateSqlTable: autoCreateSqlTable,
restrictedToMinimumLevel: LogEventLevel.Verbose,
columnOptions: GetSQLSinkColumnOptions(),
batchPostingLimit: batchPostingLimit)
.CreateLogger();
你在处理你的记录器吗?
Serilog.Sinks.MSSqlServer
是一个“定期批处理接收器”,因此您需要确保在最后处理记录器以强制它将日志刷新到数据库。见 Lifecycle of Loggers .((IDisposable) logger).Dispose();
即使您使用的是
1
对于 batchPostingLimit
, it waits 5
seconds by default before sending the logs to the database .如果您的应用在此之前关闭并且您没有处置记录器,则消息将丢失。为了排除故障,请使用
AuditTo
而不是 WriteTo
(并删除不适用于审计的 batchPostingLimit
)。 WriteTo
是安全的,并且会吃任何异常(exception),而 AuditTo
会让异常冒出来。ILogger logger = new LoggerConfiguration()
.AuditTo.MSSqlServer(
connectionString,
tableName,
restrictedToMinimumLevel: LogEventLevel.Verbose,
autoCreateSqlTable: true)
.CreateLogger();
当然,一旦你找出问题所在,请返回
WriteTo
.
关于c# - Serilog MSSQL Sink 不会将日志写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953060/