1 回答
TA贡献1848条经验 获得超2个赞
您基本上必须检查配置是否已经指定了控制台记录器。存储接收器的字段是私有的。所以你必须使用类似的东西来对配置做出反应。当您想要覆盖记录器上的某些属性时,您还需要使用反射来访问这些字段。下面的代码适用于我的简单测试应用程序。
public static class Extensions
{
public static IWebHostBuilder UseLogging(this IWebHostBuilder webHostBuilder) =>
webHostBuilder.UseSerilog((context, loggerConfiguration) =>
{
var logLevel = context.Configuration.GetValue<string>("Serilog:MinimumLevel");
if (!Enum.TryParse<LogEventLevel>(logLevel, true, out var level))
{
level = LogEventLevel.Information;
}
loggerConfiguration.Enrich
.FromLogContext()
.MinimumLevel.Is(level);
loggerConfiguration
.ReadFrom.Configuration(context.Configuration);
// Get the field that holds the sinks.
var sinks = loggerConfiguration.GetType()
.GetField("_logEventSinks", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(loggerConfiguration) as List<ILogEventSink>;
// Get the sink type for reusage.
var sinkType = typeof(AnsiConsoleTheme).Assembly.GetType("Serilog.Sinks.SystemConsole.ConsoleSink");
// Find the first sink of the right type.
var sink = sinks?.FirstOrDefault(s => sinkType == s.GetType());
// Check if a sink was found.
if (sink == null)
{
// No sink found add a new one.
loggerConfiguration
.WriteTo.Console(
theme: AnsiConsoleTheme.Code,
outputTemplate:
"[{Timestamp:yy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}");
}
else
{
// Otherwise change the theme.
sinkType.GetField("_theme", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(sink, AnsiConsoleTheme.Code);
}
});
}
- 1 回答
- 0 关注
- 210 浏览
添加回答
举报
