简体   繁体   English

Serilog 是记录类型而不是 object 内容

[英]Serilog is logging type rather than object content

I'm new to Serilog - trying it out to see if it will help.我是 Serilog 的新手 - 试试看是否有帮助。 I'm using Serilog v2 and Serilog.Sinks.MsSqlServer v5我正在使用 Serilog v2 和 Serilog.Sinks.MsSqlServer v5

I have the following console app code:我有以下控制台应用程序代码:

static void Main(string[] args)
    {
        var logger = CreateLogger();

        var employee = new Person()
        {
            Name = "Rob",
            Age = 45
        };

        logger.Debug("Employee details {Employee}", employee);

        Console.ReadKey();

    }

private static ILogger CreateLogger()
    {

        string levelString = SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
                            "LCC.Common", "Serilog.MinimumLevel");

        SerilogLevel level = (SerilogLevel)Enum.Parse(typeof(SerilogLevel), levelString);

        string conString = SSOSettingsFileManager.SSOSettingsFileReader.ReadString(
                            "LCC.Common", "Serilog.ConnectionString");

        var levelSwitch = new LoggingLevelSwitch();
        levelSwitch.MinimumLevel = (Serilog.Events.LogEventLevel)level;

        return new LoggerConfiguration()
            .MinimumLevel.ControlledBy(levelSwitch)
            .WriteTo.MSSqlServer(connectionString: conString, tableName: "Logs", autoCreateSqlTable: true)
            .CreateLogger();
    }

I would have expected the details of Person to be logged ie Name Rob and Age 45. However, I find the following logged to the Properties column on my Sql Server Sink:我本来希望记录人员的详细信息,即姓名 Rob 和年龄 45。但是,我发现以下内容记录到我的 Sql 服务器接收器的属性列中:

<properties><property key='Employee'>ConsoleApplication1.Person</property></properties>

Where did I go wrong?我在哪里 go 错了?

here is Serilog documentation 这是Serilog文档

For this task, Serilog provides the @ destructuring operator. 对于此任务,Serilog提供了@解构运算符。

var sensorInput = new { Latitude = 25, Longitude = 134 };
Log.Information("Processing {@SensorInput}", sensorInput);

as you can see to do destructuring you have to set @ before key name. 如您所见,要进行销毁,您必须在键名之前设置@。 This is missed in your sample code 您的示例代码中错过了

logger.Debug("Employee details {Employee}", employee);

The logging framework is going to call ToString on the object passed to it. 日志记录框架将在传递给它的对象上调用ToString。 If you want the details logged, one option would be to override the ToString method to serialize the object (assumes reference to Newtonsoft.JSON library): 如果要记录详细信息,一种选择是重写ToString方法以序列化对象(假设引用了Newtonsoft.JSON库):

// in Person.cs
public override string ToString()
{
    return JsonConvert.SerializeObject(this);
}

@oleksa's answer worked for me and helped me realize what I needed to do in my case of trying to log some info from a controller using the Log.ForContext(...) approach. @oleksa 的回答对我有用,并帮助我意识到在尝试使用Log.ForContext(...)方法从 controller 记录一些信息的情况下我需要做什么。 Here are a couple examples:这里有几个例子:

Option 1:选项1:

I prefer this approach since it keeps the view cleaner in the log aggregator (Seq in my case).我更喜欢这种方法,因为它使日志聚合器中的视图更清晰(在我的例子中是 Seq)。

// Inside controller GET method

Employee employee = await myService.GetData();

// Need to set the `destructureObjects` flag to `true`
Log.ForContext<Employee>(Serilog.Events.LogEventLevel.Information, "Employee", employee, true)
   .Information("Employee Information");

Option 2:选项 2:

// Inside controller GET method

Employee employee = await myService.GetData();

Log.Information("Employee Information {@Employee}", employee);

.NET 6 & Serilog 5.0 .NET 6 & Serilog 5.0

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

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