Class: LogStash::Filters::Date

Inherits:
Base
  • Object
show all
Defined in:
lib/logstash/filters/date.rb

Overview

The date filter is used for parsing dates from fields, and then using that date or timestamp as the logstash timestamp for the event.

For example, syslog events usually have timestamps like this:

source,ruby

“Apr 17 09:32:01”

You would use the date format ‘MMM dd HH:mm:ss` to parse this.

The date filter is especially important for sorting events and for backfilling old data. If you don’t get the date correct in your event, then searching for them later will likely sort out of order.

In the absence of this filter, logstash will choose a timestamp based on the first time it sees the event (at input time), if the timestamp is not already set in the event. For example, with file input, the timestamp is set to the time of each read.

Constant Summary collapse

JavaException =
java.lang.Exception
UTC =
org.joda.time.DateTimeZone.forID("UTC")
DATEPATTERNS =

LOGSTASH-34

%w{ y d H m s S }

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Date

Returns a new instance of Date.



95
96
97
98
99
# File 'lib/logstash/filters/date.rb', line 95

def initialize(config = {})
  super

  @parsers = Hash.new { |h,k| h[k] = [] }
end

Instance Method Details

#filter(event) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/logstash/filters/date.rb', line 186

def filter(event)
  @logger.debug? && @logger.debug("Date filter: received event", :type => event["type"])
  return unless filter?(event)
  @parsers.each do |field, fieldparsers|
    @logger.debug? && @logger.debug("Date filter looking for field",
                                    :type => event["type"], :field => field)
    next unless event.include?(field)

    fieldvalues = event[field]
    fieldvalues = [fieldvalues] if !fieldvalues.is_a?(Array)
    fieldvalues.each do |value|
      next if value.nil?
      begin
        epochmillis = nil
        success = false
        last_exception = RuntimeError.new "Unknown"
        fieldparsers.each do |parserconfig|
          parserconfig[:parser].each do |parser|
            begin
              epochmillis = parser.call(value)
              success = true
              break # success
            rescue StandardError, JavaException => e
              last_exception = e
            end
          end # parserconfig[:parser].each
          break if success
        end # fieldparsers.each

        raise last_exception unless success

        # Convert joda DateTime to a ruby Time
        event[@target] = LogStash::Timestamp.at(epochmillis / 1000, (epochmillis % 1000) * 1000)

        @logger.debug? && @logger.debug("Date parsing done", :value => value, :timestamp => event[@target])
        filter_matched(event)
      rescue StandardError, JavaException => e
        @logger.warn("Failed parsing date from field", :field => field,
                     :value => value, :exception => e)
        # Raising here will bubble all the way up and cause an exit.
        # TODO(sissel): Maybe we shouldn't raise?
        # TODO(sissel): What do we do on a failure? Tag it like grok does?
        #raise e
      end # begin
    end # fieldvalue.each
  end # @parsers.each

  return event
end

#registerObject



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/logstash/filters/date.rb', line 102

def register
  require "java"
  if @match.length < 2
    raise LogStash::ConfigurationError, I18n.t("logstash.agent.configuration.invalid_plugin_register",
      :plugin => "filter", :type => "date",
      :error => "The match setting should contains first a field name and at least one date format, current value is #{@match}")
  end

  locale = nil
  if @locale
    if @locale.include? '_'
      @logger.warn("Date filter now use BCP47 format for locale, replacing underscore with dash")
      @locale.gsub!('_','-')
    end
    locale = java.util.Locale.forLanguageTag(@locale)
  end
  setupMatcher(@config["match"].shift, locale, @config["match"] )
end

#setupMatcher(field, locale, value) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/logstash/filters/date.rb', line 121

def setupMatcher(field, locale, value)
  value.each do |format|
    parsers = []
    case format
      when "ISO8601"
        iso_parser = org.joda.time.format.ISODateTimeFormat.dateTimeParser
        if @timezone
          iso_parser = iso_parser.withZone(org.joda.time.DateTimeZone.forID(@timezone))
        else
          iso_parser = iso_parser.withOffsetParsed
        end
        parsers << lambda { |date| iso_parser.parseMillis(date) }
        #Fall back solution of almost ISO8601 date-time
        almostISOparsers = [
          org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZ").getParser(),
          org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").getParser()
        ].to_java(org.joda.time.format.DateTimeParser)
        joda_parser = org.joda.time.format.DateTimeFormatterBuilder.new.append( nil, almostISOparsers ).toFormatter()
        if @timezone
          joda_parser = joda_parser.withZone(org.joda.time.DateTimeZone.forID(@timezone))
        else
          joda_parser = joda_parser.withOffsetParsed
        end
        parsers << lambda { |date| joda_parser.parseMillis(date) }
      when "UNIX" # unix epoch
        parsers << lambda do |date|
          raise "Invalid UNIX epoch value '#{date}'" unless /^\d+(?:\.\d+)?$/ === date || date.is_a?(Numeric)
          (date.to_f * 1000).to_i
        end
      when "UNIX_MS" # unix epoch in ms
        parsers << lambda do |date|
          raise "Invalid UNIX epoch value '#{date}'" unless /^\d+$/ === date || date.is_a?(Numeric)
          date.to_i
        end
      when "TAI64N" # TAI64 with nanoseconds, -10000 accounts for leap seconds
        parsers << lambda do |date| 
          # Skip leading "@" if it is present (common in tai64n times)
          date = date[1..-1] if date[0, 1] == "@"
          return (date[1..15].hex * 1000 - 10000)+(date[16..23].hex/1000000)
        end
      else
        joda_parser = org.joda.time.format.DateTimeFormat.forPattern(format).withDefaultYear(Time.new.year)
        if @timezone
          joda_parser = joda_parser.withZone(org.joda.time.DateTimeZone.forID(@timezone))
        else
          joda_parser = joda_parser.withOffsetParsed
        end
        if (locale != nil)
          joda_parser = joda_parser.withLocale(locale)
        end
        parsers << lambda { |date| joda_parser.parseMillis(date) }
    end

    @logger.debug("Adding type with date config", :type => @type,
                  :field => field, :format => format)
    @parsers[field] << {
      :parser => parsers,
      :format => format
    }
  end
end