问题
I am currently sending my Log from Nlog to ElasticSearch. I am creating Index daily, and send Logs to that index. I want to create Index Weekly, so I want to change config file.
I do index creation in NLog configuration file.
index = "logstash-${date:format=yyyy.MM.dd}"
My NLog Configuration part :
<target xsi:type="ElasticSearch"
index = "logstash-${date:format=yyyy.MM.dd}"
uri="http://localhost:9200"
includeAllProperties ="true">
</target>
I found in some forums (https://github.com/logstash-plugins/logstash-output-elasticsearch/issues/541#issuecomment-270923437) changing weekly I should use like xxxx.ww.
I tried to change config file like this :
index = "logstash-${date:format=xxxx.ww}"
Unfortunately this is give me result logstash-xxxx.ww
, I expected result logstash-2019.25
So how can I change daily to weekly?
回答1:
${date}
accepts the same formats as DateTime.ToString
. Unfortunately there is no ww or weeknumber format with .NET (see Custom date and time format strings - .NET | Microsoft Docs)
The link on the forum is talking about Joda Time, which is a library for Java and not .NET.
You could solve this with a custom layout renderer in NLog. Getting the week number in .NET is a bit tricky, got this from 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);
}
Creating a layout renderer which renders 2019.25 etc (see 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));
and now this should work:
index = "logstash-${myDateTime}"
来源:https://stackoverflow.com/questions/56683912/index-format-change-daily-to-weekly