Class: LogStash::Filters::Date

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

Overview

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

For example, syslog events usually have timestamps like this:

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

Constants inherited from Base

Base::RESERVED

Constants included from Config::Mixin

Config::Mixin::CONFIGSORT

Instance Attribute Summary

Attributes included from Config::Mixin

#config, #original_params

Attributes inherited from Plugin

#logger, #params

Instance Method Summary collapse

Methods inherited from Base

#execute, #threadsafe?

Methods included from Config::Mixin

#config_init, included

Methods inherited from Plugin

#eql?, #finished, #finished?, #hash, #inspect, lookup, #reload, #running?, #shutdown, #teardown, #terminating?, #to_s

Constructor Details

#initialize(config = {}) ⇒ Date

Returns a new instance of Date.



113
114
115
116
117
# File 'lib/logstash/filters/date.rb', line 113

def initialize(config = {})
  super

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

Instance Method Details

#filter(event) ⇒ Object



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
235
236
237
238
239
240
241
242
243
# File 'lib/logstash/filters/date.rb', line 196

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|
          parser = parserconfig[:parser]
          begin
            epochmillis = parser.call(value)
            success = true
            break # success
          rescue StandardError, JavaException => e
            last_exception = e
          end
        end # fieldparsers.each

        raise last_exception unless success

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

        @logger.debug? && @logger.debug("Date parsing done", :value => value, :timestamp => event[@target])
      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

  filter_matched(event) if !event.cancelled?
  return event
end

#registerObject



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/logstash/filters/date.rb', line 130

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
  # TODO(sissel): Need a way of capturing regexp configs better.
  locale = parseLocale(@config["locale"][0]) if @config["locale"] != nil and @config["locale"][0] != nil
  setupMatcher(@config["match"].shift, locale, @config["match"] )
end

#setupMatcher(field, locale, value) ⇒ Object



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
182
183
184
185
186
187
188
189
190
191
# File 'lib/logstash/filters/date.rb', line 142

def setupMatcher(field, locale, value)
  value.each do |format|
    case format
      when "ISO8601"
        joda_parser = org.joda.time.format.ISODateTimeFormat.dateTimeParser
        if @timezone
          joda_parser = joda_parser.withZone(org.joda.time.DateTimeZone.forID(@timezone))
        else
          joda_parser = joda_parser.withOffsetParsed
        end
        parser = lambda { |date| joda_parser.parseMillis(date) }
      when "UNIX" # unix epoch
        joda_instant = org.joda.time.Instant.java_class.constructor(Java::long).method(:new_instance)
        #parser = lambda { |date| joda_instant.call((date.to_f * 1000).to_i).to_java.toDateTime }
        parser = lambda { |date| (date.to_f * 1000).to_i }
      when "UNIX_MS" # unix epoch in ms
        joda_instant = org.joda.time.Instant.java_class.constructor(Java::long).method(:new_instance)
        parser = lambda do |date| 
          #return joda_instant.call(date.to_i).to_java.toDateTime
          return date.to_i
        end
      when "TAI64N" # TAI64 with nanoseconds, -10000 accounts for leap seconds
        joda_instant = org.joda.time.Instant.java_class.constructor(Java::long).method(:new_instance)
        parser = lambda do |date| 
          # Skip leading "@" if it is present (common in tai64n times)
          date = date[1..-1] if date[0, 1] == "@"
          #return joda_instant.call((date[1..15].hex * 1000 - 10000)+(date[16..23].hex/1000000)).to_java.toDateTime 
          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
        parser = lambda { |date| joda_parser.parseMillis(date) }
    end

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