索引格式每天至每周更改

时间:2019-06-20 10:22:24

标签: c# elasticsearch nlog

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

我在NLog配置文件中创建索引。     public String getDriverClass() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC) { return "sun.jdbc.odbc.JdbcOdbcDriver"; } else { return "com.mysql.cj.jdbc.Driver"; } }

我的NLog配置部分:

index = "logstash-${date:format=yyyy.MM.dd}"

我在某些论坛(https://github.com/logstash-plugins/logstash-output-elasticsearch/issues/541#issuecomment-270923437)中发现,每周更改一次,应该使用xxxx.ww之类的格式。 我试图像这样更改配置文件:       <target xsi:type="ElasticSearch" index = "logstash-${date:format=yyyy.MM.dd}" uri="http://localhost:9200" includeAllProperties ="true"> </target>

很遗憾,这是给我结果index = "logstash-${date:format=xxxx.ww}",我希望得到的结果logstash-xxxx.ww

那么我该如何每天更改为每周一次?

1 个答案:

答案 0 :(得分:3)

${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}"