【问题标题】:index format change daily to weekly索引格式每天更改为每周
【发布时间】:2019-11-03 03:39:19
【问题描述】:

我目前正在将我的日志从 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

那么我怎样才能将每天更改为每周?

【问题讨论】:

    标签: c# elasticsearch nlog


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2017-09-26
      • 2015-03-08
      • 2018-11-12
      • 2022-06-23
      相关资源
      最近更新 更多