【问题标题】:serilog indexing objects via logger reference in .net core通过 .net 核心中的记录器引用的 serilog 索引对象
【发布时间】:2021-01-28 05:20:24
【问题描述】:

使用原始属性索引数据很好,但是当涉及到索引对象时,我希望它添加为与其他字段相同的序列化对象,但这里会发生什么;

代码:

ModelInput innerdata = new ModelInput()
            {
                SentimentText = "==RUDE== Dude, you are rude upload that carl picture back, or else.",
                LoggedIn = @"TRUE",
            };
            string name = "";
            string surname = "";
            _logger.LogInformation("{name} {surname} {innerdata} ", name, surname, innerdata);
            _logger.LogInformation("{name} {surname} {innerdata} ", name, surname, JsonConvert.SerializeObject(innerdata));

没有序列化;

"_source" : {
          "@timestamp" : "2020-10-13T22:58:41.8081607+03:00",
          "level" : "Information",
          "messageTemplate" : "{name} {surname} {innerdata} ",
          "message" : "\"\" \"\" \"YD_Baguni_WebML.Model.ModelInput\" ",
          "fields" : {
            "name" : "",
            "surname" : "",
            "innerdata" : "YD_Baguni_WebML.Model.ModelInput",

序列化对象时的样子;

"_source" : {
          "@timestamp" : "2020-10-13T23:00:04.5960980+03:00",
          "level" : "Information",
          "messageTemplate" : "{name} {surname} {innerdata} ",
          "message" : "\"\" \"\" \"{\\\"Sentiment\\\":null,\\\"SentimentText\\\":\\\"==RUDE== Dude, you are rude upload that carl picture back, or else.\\\",\\\"LoggedIn\\\":\\\"TRUE\\\"}\" ",
          "fields" : {
            "name" : "",
            "surname" : "",
            "innerdata" : """{"Sentiment":null,"SentimentText":"==RUDE== Dude, you are rude upload that carl picture back, or else.","LoggedIn":"TRUE"}""",

似乎没有一个是正确的,应该是这样的:

"fields" : {
            "name" : "",
            "surname" : "",
            "innerdata" : { SentimentText:"", LoggedIn: }

我知道由于对象的字符串化而添加了这些奇怪的引号,但是如何使elasticsearch正确保存这些数据?

配置;

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return new WebHostBuilder()
                .UseKestrel(opt =>
                {
                    opt.AddServerHeader = false;
                    opt.Limits.MaxRequestLineSize = 16 * 1024;
                })
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIIS()
                .UseIISIntegration()
                .UseUrls("https://localhost:44301")
                .UseSerilog((context, config) =>
                {
                    config.Enrich.FromLogContext()
                    .Enrich.WithExceptionDetails()
                    .Enrich.WithMachineName()
                    .WriteTo.Console()
                    .WriteTo.File(Path.Combine(context.HostingEnvironment.WebRootPath, "./elastic-errors.txt"), Serilog.Events.LogEventLevel.Error, rollingInterval: RollingInterval.Day)
                    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(context.Configuration["ElasticConfiguration:Uri"]))
                    {
                        IndexFormat = context.Configuration["ElasticConfiguration:IndexFormat"],
                        CustomFormatter = new ElasticsearchJsonFormatter(),
                        AutoRegisterTemplate = true,
                        NumberOfShards = 2,
                        NumberOfReplicas = 1,
                        BufferCleanPayload = (failingEvent, statuscode, exception) =>
                        {
                            dynamic e = JObject.Parse(failingEvent);
                            return JsonConvert.SerializeObject(new Dictionary<string, object>()
                            {
                                { "@timestamp", e["@timestamp"] },
                                { "level", "Error" },
                                { "message", "Error: " + e.message },
                                { "messageTemplate", e.messageTemplate },
                                { "failingStatusCode", statuscode },
                                { "failingException", exception }
                            });
                        },
                        BufferIndexDecider = (logEvent, offset) => "log-serilog-" + (new Random().Next(0, 2)),
                    }).Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
                    .ReadFrom.Configuration(context.Configuration);
                })
                .UseStartup<Startup>();
        }

【问题讨论】:

    标签: c# asp.net-core elasticsearch serilog


    【解决方案1】:

    Serilog documentation 对此进行了很好的介绍。

    如果你有一个复杂的对象想要解构,你需要使用@符号。

    _logger.LogInformation("{name} {surname} {@innerdata} ", name, surname, innerdata);
    

    请注意,Serilog 约定是使用 PascalCase 作为您的属性名称。

    _logger.LogInformation("{Name} {Surname} {@InnerData} ", name, surname, innerdata);
    

    我建议你在 Visual Studio 中安装Serilog Analyzer 扩展,它可以很好地帮助捕捉此类常见错误。并阅读文档!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多