通过.NETCore中的记录器引用对对象进行serilog索引

rryofs0p  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(432)

用原语属性索引数据很好,但是当索引一个对象时,我希望它像其他字段一样作为序列化对象添加,但是这里发生了什么;
代码:

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: }

我知道由于对象的stringfy,它添加了这些奇怪的引号,但是如何让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>();
        }
kqqjbcuj

kqqjbcuj1#

这在serilog文档中有很好的介绍。
如果您有一个复杂的对象需要解构,则需要使用@符号。

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

请注意,serilog约定是使用pascalcase作为属性名。

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

我建议您在visualstudio中安装seriloganalyzer扩展,这有助于捕捉像这样的常见错误。阅读文档!

相关问题