gpt4 book ai didi

c# - 索引格式每天更改为每周

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:34 27 4
gpt4 key购买 nike

我目前正在将我的日志从 Nlog 发送到 ElasticSearch。我每天都在创建索引,并将日志发送到该索引。我想创建 Index Weekly,所以我想更改配置文件。

我在 NLog 配置文件中创建索引。 index = "logstash-${date:format=yyyy.MM.dd}"

我的 NLog 配置部分:

  <target xsi:type="ElasticSearch" 
index = "logstash-${date:format=yyyy.MM.dd}"
uri="http://localhost:9200"
includeAllProperties ="true">
</target>

我发现在一些论坛 ( https://github.com/logstash-plugins/logstash-output-elasticsearch/issues/541#issuecomment-270923437 ) 每周更改我应该使用像 xxxx.ww。我试图像这样更改配置文件: index = "logstash-${date:format=xxxx.ww}"

不幸的是,这是给我的结果 logstash-xxxx.ww,我期望结果 logstash-2019.25

那么如何将每日更改为每周?

最佳答案

${date} 接受与 DateTime.ToString 相同的格式。不幸的是,.NET 没有 ww 或 weeknumber 格式(参见 Custom date and time format strings - .NET | Microsoft Docs)

论坛上的链接谈论的是 Joda Time,它是一个用于 Java 而不是 .NET 的库。

您可以使用 NLog 中的自定义布局渲染器解决此问题。在 .NET 中获取周数有点棘手,这是从 Get the correct week number of a given date 得到的:

// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

创建一个渲染 2019.25 等的布局渲染器(参见 NLog docs - How to write a custom layout renderer)

using NLog.LayoutRenderers;
using NLog;
...

// register ${myDateTime}. Register a soon as possible (e.g main(), app_start etc)
LayoutRenderer.Register("myDateTime", logEventInfo =>
logEventInfo.TimeStamp.Year +"." + GetIso8601WeekOfYear(logEventInfo.TimeStamp));

现在这应该可以工作了:

index = "logstash-${myDateTime}"

关于c# - 索引格式每天更改为每周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683912/

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