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 關注
- 145 瀏覽
添加回答
舉報