繁体   English   中英

使用Serilog的MVC日志记录未序列化对象

[英]MVC logging with Serilog not serializing objects

使用AspNetCore 2.0.0和Serilogger 2.0.2的MVC Core Web服务项目。

在我们的一个控制器中,我正在使用Serilog将请求数据记录到Application Insights中。

在我们的Startup:Configure方法中...

Serilog.ILogger serilogLogger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .Enrich.FromLogContext()
            .WriteTo.ApplicationInsightsEvents( Configuration.GetValue<string>( "ApplicationInsights:InstrumentationKey" ) )
            .CreateLogger();
loggerFactory.AddSerilog( serilogLogger );

没什么特别的。 在我们的控制器中,我们有以下内容

public async Task<IActionResult> Create( [FromBody] List<Event> value )
{
   foreach( Event e in value )
   {
      _logger.LogWarning( "***** Event Create {@event}", e );
   }
}

我们在App Insights中看到以下内容:

{"AspNetCoreEnvironment":"Development","{OriginalFormat}":"***** Event Create {@event}","DeveloperMode":"true","CategoryName":"Demo.Controllers.EventController","@event":"Demo.Models.Event"}

为什么只给我类型,然后将其序列化为Json? 我尝试在Event类上重载ToString方法,并从LogWarning()中删除@,然后继续在日志中打印出类型。 在这种情况下,它是“字符串”。

在此页面的帮助下找到了答案: https : //github.com/serilog/serilog/wiki/Structured-Data

我们在安装程序中添加了Destructure.With()调用,并添加了一个类来处理数据的所有破坏。

Serilog.ILogger logger = new LoggerConfiguration()
  .ReadFrom.Configuration(Configuration)
  .WriteTo.ApplicationInsightsEvents(Configuration.GetValue<string>("ApplicationInsights:InstrumentationKey"))
  .Destructure.With<DestructureModels>()
  .CreateLogger();
loggerFactory.AddSerilog(logger);

我们的解构类如下所示:

public class DestructureModels : IDestructuringPolicy
{
    public bool TryDestructure( object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result )
    {
        // to handle custom serialization of objects in the log messages
        //
        if( value.GetType().Namespace.Contains("MyProj.Models"))
        {
            result = new ScalarValue(JsonConvert.SerializeObject(value));
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }
}

不是完美的,因为它似乎仅在设置为发送到CustomEvents时才起作用,因此不适用于AppInsights中的Traces。 上面的解构类将被调用,但是您不会在AppInsights中获得值。 缺乏有关如何/为什么使用这些东西的文档非常令人沮丧。 同样,我们需要显式地登录代码,而不是能够利用AppInsights跟踪日志记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM