【发布时间】:2016-04-14 13:59:36
【问题描述】:
我正在将 Serilog 添加到我们的日志记录基础架构中,但对以下内容感到困惑:
public class OzCpWriteEntryExInput : OzCpAppServiceInputBase
{
private readonly ILogger _Logger;
/// <summary>
/// Class constructor
/// </summary>
public OzCpWriteEntryExInput(ILogger aLogger)
{
//Save params supplied
_Logger = aLogger;
//Create resources required
Entry = new OzCpLogEntryContextInput();
}
public OzCpLogEntryContextInput Entry { get; set; }
public ILogger Logger => _Logger;
}
public class OzCpLoggingService : OzCruisingPlatformAppServiceBase, IOzCpLoggingService
{
private const string MESSAGE_TEMPLATE =
"{LogVersion} {DateTimeUtc:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{LevelRange}] [{ApplicationHostName}] [{ApplicationName}] [{ApplicationVersion}] [{Location}] {Message}{NewLine}{Exception}{NewLine}{StackTrace}{NewLine}{UserDataKind}{@UserData}";
public OzCpBuildLoggerOutput BuildLogger(OzCpBuildLoggerInput aParams)
{
OzCpBuildLoggerOutput result = new OzCpBuildLoggerOutput();
//#TODO (DE) Convert logger hard coded values into settings
bool logToUdp = true;
//By default logging will include all events
LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
.Enrich.WithProperty("LogVersion", "01.00")
.MinimumLevel.Verbose();
if (logToUdp)
{
loggerConfiguration.WriteTo.Udp(IPAddress.Loopback, 11000, 0, LogEventLevel.Verbose, MESSAGE_TEMPLATE);
}
//Finally we can build the logger
result.Logger = loggerConfiguration.CreateLogger();
return result;
}
/// <summary>
/// Writes an entry to the supplied logger and associated log sinks.
/// </summary>
/// <param name="aParams">Parameters defining the entry to be written.</param>
/// <returns>Returns whether the entry was written to the logger.</returns>
public OzCpWriteEntryExOutput WriteEntryEx(OzCpWriteEntryExInput aParams)
{
OzCpWriteEntryExOutput result = new OzCpWriteEntryExOutput();
//These variable values are only the ones out of the entry as the logger "enriches" the other values based on
//what has been passed in when it was configured
object[] messageTemplateVariableValues =
{
"***", //Log Version is actually an enriched property!!!!
aParams.Entry.DateTimeUtc,
aParams.Entry.LevelRange,
aParams.Entry.Location,
aParams.Entry.StackTrace,
aParams.Entry.UserDataKind,
aParams.Entry.UserData
};
switch (aParams.Entry.EntryKind)
{
case OzCpLoggingEntryKindEnum.Verbose:
aParams.Logger.Verbose(aParams.Entry.Exception, MESSAGE_TEMPLATE, messageTemplateVariableValues);
break;
}
return result;
}
}
WriteLogEx() 的调用者最终可以提供自己的 Serilog.ILogger。我不会解释为什么会这样的原因,只是假设这是一个要求。
作为示例,我包括 BuildLogger(),它设置 ILogger 以使用自定义消息模板和一些通过丰富配置构建器的附加属性写入 UDP。
一切都非常简单。但是,现在当我使用 ILogger.Verbose() 写入 ILogger 时,我需要为消息模板中的令牌传递参数。
但这似乎是基于 ordinal 的,所以第一个进入 {LogVersion} 应该是通过扩充器完成的之前为记录器设置的配置。
如果我不使用 LogVersion,格式化的消息模板会减一,如果我包含它,那么我自然会得到:
*** 2016-04-14 14:53:57.677 +10:00 [信息]...
而不是我想要的是:
01.00 2016-04-14 14:53:57.677 +10:00 [信息]...
那么如何从 ILogger 中调用日志记录方法并通过名称而不是位置传递令牌值?
【问题讨论】: