Class: Fluent::TimeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/fluent/time.rb

Defined Under Namespace

Classes: TimeParseError

Instance Method Summary collapse

Constructor Details

#initialize(format = nil, localtime = true, timezone = nil) ⇒ TimeParser

Returns a new instance of TimeParser.



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
# File 'lib/fluent/time.rb', line 186

def initialize(format = nil, localtime = true, timezone = nil)
  if format.nil? && (timezone || !localtime)
    raise Fluent::ConfigError, "specifying timezone requires time format"
  end

  @cache1_key = nil
  @cache1_time = nil
  @cache2_key = nil
  @cache2_time = nil

  format_with_timezone = format && (format.include?("%z") || format.include?("%Z"))

  # unixtime_in_expected_tz = unixtime_in_localtime + offset_diff
  offset_diff = case
                when format_with_timezone then nil
                when timezone  then Time.now.localtime.utc_offset - Time.zone_offset(timezone)
                when localtime then 0
                else Time.now.localtime.utc_offset # utc
                end

  strptime = format && (Strptime.new(format) rescue nil)

  @parse = case
           when format_with_timezone && strptime then ->(v){ Fluent::EventTime.from_time(strptime.exec(v)) }
           when format_with_timezone             then ->(v){ Fluent::EventTime.from_time(Time.strptime(v, format)) }
           when format == '%iso8601'             then ->(v){ Fluent::EventTime.from_time(Time.iso8601(v)) }
           when strptime then ->(v){ t = strptime.exec(v);         Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
           when format   then ->(v){ t = Time.strptime(v, format); Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
           else ->(v){ Fluent::EventTime.parse(v) }
           end
end

Instance Method Details

#parse(value) ⇒ Object Also known as: call

TODO: new cache mechanism using format string



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/fluent/time.rb', line 219

def parse(value)
  unless value.is_a?(String)
    raise TimeParseError, "value must be string: #{value}"
  end

  if @cache1_key == value
    return @cache1_time
  elsif @cache2_key == value
    return @cache2_time
  else
    begin
      time = @parse.call(value)
    rescue => e
      raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
    end
    @cache1_key = @cache2_key
    @cache1_time = @cache2_time
    @cache2_key = value
    @cache2_time = time
    return time
  end
end