使用Serilog进行MVC日志记录而不是序列化对象

时间:2017-12-05 16:45:50

标签: c# logging asp.net-core-mvc azure-application-insights serilog

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

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

在我们的启动:配置方法......

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()中删除@,我们继续在日志中打印出类型。在这种情况下,它是“字符串”。

1 个答案:

答案 0 :(得分:0)

在此页面的帮助下计算出来: 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跟踪日志记录。