gpt4 book ai didi

.net - 如何使用字段将 Serilog 数据发送到 Elasticsearch

转载 作者:行者123 更新时间:2023-11-29 02:49:34 25 4
gpt4 key购买 nike

我是 ES 和 Serilog 的新手,但我的搜索还没有产生这个答案。我试图弄清楚如何使用 Serilog 以这种方式将数据发送到 Elasticsearch,如果数据包含字段(例如,如果它是具有公共(public)属性的对象),则数据在 ES 中显示为这些属性领域。到目前为止,我已经尽可能地使用 RenderedCompactJsonFormatter 和匿名类型来实现这个主要(见下文),但仍然会生成命名字段,其中字段中的数据是除此之外的所有内容匿名类型声明的"new"部分:

            var log = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200/test_srpostimes"))
{
InlineFields = true,
IndexDecider = (@event,offset) => "test_elapsedtimes",
CustomFormatter = new RenderedCompactJsonFormatter()
})
.WriteTo.Console()
.CreateLogger();
var elapsedTime = new {Time = 64};
var timeStamp = new {Timestamp = DateTime.Now};
var transID = new {TransID = "551674"};

log.Information("{timeStamp} {transID} {elapsedTime}", timeStamp, transID, elapsedTime);

这会产生:

@t:
2016-07-11T18:45:35.0349343Z
@m:
"{ Timestamp = 7/11/2016 2:45:35 PM }" "{ TransID = 551674 }" "{ Time = 64 }"
@i:
b3ee2c05
timeStamp:
{ Timestamp = 7/11/2016 2:45:35 PM }
transID:
{ TransID = 551674 }
elapsedTime:
{ Time = 64 }
_id:
AVXbR11WjgSgCs5HSlYY
_type:
logevent
_index:
test_srpostimes
_score:
1

是否有更好的方法可以使用 ES(和 Kibana)中的字段搜索/可视化我们的数据?

最佳答案

我想通了。我更改了构造以使用 ElasticsearchJsonFormatter。由于记录器似乎能够从消息中解析字段名称,因此我切换到一个对象并改为传入属性:

        var log = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200/test_srpostimes"))
{
IndexDecider = (@event,offset) => "test_elapsedtimes",
CustomFormatter = new ElasticsearchJsonFormatter()
})
.WriteTo.Console()
.CreateLogger();

var elapsedTimeMessage = new ElapsedTimeMessage(DateTime.Now.Millisecond);

log.Information("{EventTime} {EventId} {ElapsedTime}", elapsedTimeMessage.EventTime, elapsedTimeMessage.EventId, elapsedTimeMessage.ElapsedTime);

这在 ES 中产生了更具可读性的输出:

  "_source": {
"@timestamp": "2016-07-12T09:03:21.5804873-04:00",
"level": "Information",
"messageTemplate": "{EventTime} {EventId} {ElapsedTime}",
"fields": {
"EventTime": "2016-07-12T09:03:21.5754873-04:00",
"EventId": "575",
"ElapsedTime": 575
}
}

关于.net - 如何使用字段将 Serilog 数据发送到 Elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com