Module: Nais::Log::Parser

Defined in:
lib/nais/log/parser.rb,
lib/nais/log/parser/version.rb

Constant Summary collapse

VERSION =
"0.32.2"

Class Method Summary collapse

Class Method Details

.flatten_hash(hash, path = "", keep = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nais/log/parser.rb', line 12

def Parser.flatten_hash(hash, path = "", keep = nil)
  hash.each_with_object({}) do |(k, v), ret|
    if path == "" && !keep.nil? && k =~ keep
      ret[k] = v
    else
      key = (path + k.to_s).tr('.','_')
      if v.is_a? Hash
        ret.merge! Parser.flatten_hash(v, key.to_s + "_")
      else
        ret[key] = v
      end
    end
  end
end

.get_keywords(str, regex) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/nais/log/parser.rb', line 27

def Parser.get_keywords(str, regex)
  keywords = str.scan(regex)
  if keywords.any?
    keywords.uniq!
    keywords.size == 1 ? keywords.first : keywords
  end
end

.loglevel_from_dns_response(response) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/nais/log/parser.rb', line 390

def Parser.loglevel_from_dns_response(response)
  return case response
         when 'NOERROR'
           'Info'
         when 'NODATA'
           'Warning'
         when 'FORMERR'
           'Warning'
         when 'SERVFAIL'
           'Error'
         when 'NXDOMAIN'
           'Warning'
         when 'NOTIMP'
           'Warning'
         when 'REFUSED'
           'Warning'
         end
end

.loglevel_from_http_response(response) ⇒ Object



409
410
411
412
413
414
415
416
417
418
# File 'lib/nais/log/parser.rb', line 409

def Parser.loglevel_from_http_response(response)
  return case response.to_s[0,1]
         when '2','3'
           'Info'
         when '4'
           'Warning'
         when '5'
           'Error'
         end
end

.merge_json_field(record, field) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/nais/log/parser.rb', line 35

def Parser.merge_json_field(record, field)
  if record.has_key?(field)
    value = record[field].strip
    if value[0].eql?('{') && value[-1].eql?('}')
      begin
        record = JSON.parse(value).merge(record)
        record.delete(field)
      rescue JSON::ParserError=>e
      end
    end
  end
  record
end

.parse_accesslog(str) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/nais/log/parser.rb', line 229

def Parser.parse_accesslog(str)
  if !str.nil? && m = str.match(/^(\S+) +(?:(\S+) )?(\S+) \[([^\]]+)\] \"([^\"]*)\" (\S+) (\S+)(.*)/)
    r = {}
    r['remote_ip'] = m[1]
    r['ident'] = m[2] unless (m[2].nil? || m[2] == '-')
    r['user'] = m[3] unless m[3] == '-'
    r['timestamp'] = Time.strptime(m[4], "%d/%b/%Y:%H:%M:%S %Z").iso8601
    r['request'] = m[5]
    r['response_code'] = m[6] unless m[6] == '-'
    r['content_length'] = m[7] unless m[7] == '-'
    ext = m[8] unless m[8] == ''
    return r, ext
  else
    return nil
  end
end

.parse_accesslog_with_processing_time(str) ⇒ Object



246
247
248
249
250
251
252
# File 'lib/nais/log/parser.rb', line 246

def Parser.parse_accesslog_with_processing_time(str)
  r,ext = Parser.parse_accesslog(str)
  if !ext.nil? && m = ext.match(/^\s+(?:\"?-\"?|([0-9.]+)(?:[µm]?s))?$/u)
    r['processing_time'] = m[1] unless m[1].nil?
  end
  return r
end

.parse_accesslog_with_referer_useragent(str) ⇒ Object



254
255
256
257
258
259
260
261
# File 'lib/nais/log/parser.rb', line 254

def Parser.parse_accesslog_with_referer_useragent(str)
  r,ext = Parser.parse_accesslog(str)
  if !ext.nil? && m = ext.match(/^\s+\"([^\"]+)\" \"([^\"]+)\"$/)
    r['referer'] = m[1] unless m[1] == '-'
    r['user_agent'] = m[2] unless m[2] == '-'
  end
  return r
end

.parse_capnslog(str) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/nais/log/parser.rb', line 320

def Parser.parse_capnslog(str)
  if !str.nil? && m = str.match(/^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{6}) ([TDNIWEC]) \| ([^:]+):\s*(.*)/)
    r = {}
    r['timestamp'] = Time.strptime(m[1], "%Y-%m-%d %H:%M:%S.%N").utc.iso8601(9)
    r['level'] = case m[2]
                 when 'T'
                   'Trace'
                 when 'D'
                   'Debug'
                 when 'N'
                   'Notice'
                 when 'I'
                   'Info'
                 when 'W'
                   'Warning'
                 when 'E'
                   'Error'
                 when 'C'
                   'Critical'
                 end
    r['component'] = m[3]
    r['message'] = m[4]
    return r
  else
    return nil
  end
end

.parse_coredns(str) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/nais/log/parser.rb', line 170

def Parser.parse_coredns(str)
  if !str.nil? && m = str.match(/^(\S+) \[([^\]]+?)\] (.+)$/)
    r = {}
    r['timestamp'] = m[1]
    r['level'] = m[2]
    msg = m[3]
    r['message'] = msg
    if m = msg.match(/^(\S+?):(\d+) - (\d+) \"([^\"]*)\" (\S+) (\S+) (\d+) (\d+(?:\.\d+)?)s$/)
      r['remote_ip'] = m[1]
      r['remote_port'] = m[2]
      r['query_id'] = m[3]
      r['message'] = m[4]
      r['response_code'] = m[5]
      r['flags'] = m[6].split(',')
      r['content_length'] = m[7]
      r['processing_time'] = m[8]
    end
    return r
  else
    return nil
  end
end

.parse_glog(str) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/nais/log/parser.rb', line 281

def Parser.parse_glog(str)
  if !str.nil? && m = str.match(/^([IWEF])(\d{4} \d\d:\d\d:\d\d\.\d{6})\s+(\S+)\s([^:]+):(\d+)\]\s+(.*)/)
    r = {}
    r['level'] = case m[1]
                 when 'I'
                   'Info'
                 when 'W'
                   'Warning'
                 when 'E'
                   'Error'
                 when 'F'
                   'Critical'
                 end
    r['timestamp'] = Time.strptime(m[2], "%m%d %H:%M:%S.%N").utc.iso8601(9)
    r['thread'] = m[3]
    r['file'] = m[4]
    r['line'] = m[5]
    r['message'] = m[6]
    return r
  else
    return nil
  end
end

.parse_gokit(str) ⇒ Object



272
273
274
275
276
277
278
279
# File 'lib/nais/log/parser.rb', line 272

def Parser.parse_gokit(str)
  r = Logfmt.parse(str)
  if !r.nil? && r.has_key?('ts') && r.has_key?('level') && (r.has_key?('msg') || r.has_key?('err'))
    r
  else
    nil
  end
end

.parse_influxdb(str) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/nais/log/parser.rb', line 348

def Parser.parse_influxdb(str)
  if !str.nil? && m = str.match(/^\[([^\]]+)\] (.*)$/)
    r = {}
    comp = m[1]
    msg = m[2]
    if comp == 'httpd'
      ar, ext = parse_accesslog(msg)
      unless ar.nil?
        r = ar
        r['message'] = r.delete('request')
        if !ext.nil? && m = ext.match(/^ \"([^\"]+)\" \"([^\"]+)\" ([0-9a-f-]+) (\d+)$/)
          r['referer'] = m[1] unless m[1] == '-'
          r['user_agent'] = m[2]  unless m[2] == '-'
          r['request'] = m[3] unless m[3] == '-'
          r['processing_time'] = m[4] unless m[4] == '-'
        end
      end
    end
    case comp
    when 'D'
      r['level'] = 'Debug'
    when 'I'
      r['level'] = 'Info'
    when 'W'
      r['level'] = 'Warning'
    when 'E'
      r['level'] = 'Error'
    else
      r['component'] = comp
    end
    if m = msg.match(/^(\d{4}[-\/]\d\d[-\/]\d\d)[ T](\d\d:\d\d:\d\d)Z? (.*)/)
      r['timestamp'] = Time.strptime(m[1].tr('/','-')+" "+m[2]+"+00:00", "%Y-%m-%d %H:%M:%S%Z").iso8601
      r['message'] = m[3]
    elsif r['message'].nil?
      r['message'] = msg
    end
    return r
  else
    return nil
  end
end

.parse_kv(str) ⇒ Object



123
124
125
126
127
128
129
130
131
# File 'lib/nais/log/parser.rb', line 123

def Parser.parse_kv(str)
  r = {}
  if !str.nil? && match = str.scan(/\b([A-Za-z]{1,20})=(?:([^\ "][^, ]*)|\"([^\"]+)\"),?/)
    match.each{|m|
      r[m[0]] = m[1].nil? ? m[2] : m[1]
    }
  end
  return r.empty? ? nil : r
end

.parse_logrus(str) ⇒ Object



263
264
265
266
267
268
269
270
# File 'lib/nais/log/parser.rb', line 263

def Parser.parse_logrus(str)
  r = Logfmt.parse(str)
  if !r.nil? && r.has_key?('time') && r.has_key?('level') && r.has_key?('msg')
    r
  else
    nil
  end
end

.parse_redis(str) ⇒ Object



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
# File 'lib/nais/log/parser.rb', line 193

def Parser.parse_redis(str)
  if !str.nil? && m = str.match(/^(?:\[(\d+)\]|(\d+):([XCSM])) (\d{1,2} \S{3,} \d\d:\d\d:\d\d\.\d\d\d) ([-.*#]) (.+)/)
    r = {}
    if m[3].nil?
      r['thread'] = m[1]
    else
      r['thread'] = m[2]
      r['component'] = case m[3]
                       when 'X'
                         'sentinel'
                       when 'C'
                         'persistence'
                       when 'S'
                         'slave'
                       when 'M'
                         'master'
                       end
    end
    r['timestamp'] = Time.strptime(m[4]+'Z', "%d %b %H:%M:%S.%L%Z").utc.iso8601(3)
    r['level'] = case m[5]
                 when '.'
                   'Debug'
                 when '-'
                   'Info'
                 when '*'
                   'Info'
                 when '#'
                   'Error'
                 end
    r['message'] = m[6]
    return r
  else
    return nil
  end
end

.parse_simple(str) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/nais/log/parser.rb', line 305

def Parser.parse_simple(str)
  if !str.nil? && m = str.match(/^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[,.]\d{3,9})?) ([a-zA-Z]+) (?:\[([^\]]+)\] )?(\S+) (.*)/)
    r = {}
    r['timestamp'] = Time.parse(m[1]).utc.iso8601(9)
    r['level'] = m[2]
    r['thread'] = m[3] if !m[3].nil?
    r['component'] = m[4]
    r['message'] = m[5]
    return r
  else
    return nil
  end
end

.parse_uri(str) ⇒ Object



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
# File 'lib/nais/log/parser.rb', line 133

def Parser.parse_uri(str)
  r = {}
  unless str.nil?
    i = str.index('?')
    if i.nil?
      r['path'] = URI.decode(str)
    else
      if i != 0
        r['path'] = URI.decode(str[0,i])
      end
      if i+1 < str.length
        query = str[i+1, str.length]
        kv = {}
        query.scan(/([^=&]+)=([^&]+)/) do |k,v|
          k.gsub!(/\+/, ' ')
          k = URI.decode(k)
          v.gsub!(/\+/, ' ')
          v = URI.decode(v)
          if kv.has_key?(k)
            if kv[k].is_a?(Array)
              next if kv[k].include?(v)
              kv[k].push(v)
            else
              next if kv[k] == v
              kv[k] = [kv[k], v]
            end
          else
            kv[k] = v
          end
        end
        r['query_params'] = kv unless kv.empty?
      end
    end
  end
  r
end

.prefix_fields(record, prefix, regex, negate = false) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
# File 'lib/nais/log/parser.rb', line 111

def Parser.prefix_fields(record, prefix, regex, negate = false)
  r = {}
  record.each{|k,v|
    if (!negate && k =~ regex) || (negate && k !~ regex)
      r[prefix+k] = record[k]
    else
      r[k] = record[k]
    end
  }
  r
end

.remap_elasticsearch_fields(time, record) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/nais/log/parser.rb', line 49

def Parser.remap_elasticsearch_fields(time, record)
  record["received_at"] = Time.new.iso8601(9)
  unless record.has_key?("@timestamp")
    record["@timestamp"] = record.delete("timestamp") || record.delete("time") || record.delete("ts") || Time.at(time).iso8601(9)
  end
  unless record.has_key?("message")
    record["message"] = record.delete("msg") || record.delete("log")
  end
  record.delete('log')
  record
end

.remap_java_fields(record) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/nais/log/parser.rb', line 61

def Parser.remap_java_fields(record)
  record["thread"] = record.delete("thread_name") if record.has_key?("thread_name")
  record["component"] = record.delete("logger_name") if record.has_key?("logger_name")
  if record.has_key?("level")
    if record['level'].is_a?(String)
      record['level'].capitalize!
      record['level'] = 'Warning' if record['level'] == 'Warn'
    else
      record['x_level'] = record.delete('level')
    end
  end
  record.delete("level_value")
  record.delete("ndc")
  record.delete("source_host")
  if record.has_key?('exception')
    record['stack_trace'] = record['exception']['stacktrace'] if record['exception'].has_key?('stacktrace')
    record.delete('exception')
  end
  if record.has_key?('mdc')
    record['mdc'].each{|k,v|
      record[k] = record['mdc'][k]
    }
    record.delete('mdc')
  end
  record
end

.remap_log15(record) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/nais/log/parser.rb', line 89

def Parser.remap_log15(record)
  record['@timestamp'] = record.delete('t') if record.has_key?('t')
  record['message'] = record.delete('msg') if record.has_key?('msg')
  record['component'] = record.delete('logger') if record.has_key?('logger')
  if record.has_key?('lvl')
    record['level'] = case record['lvl']
                      when 'dbug'
                        'Debug'
                      when 'info'
                        'Info'
                      when 'warn'
                        'Warning'
                      when 'eror'
                        'Error'
                      when 'crit'
                        'Critical'
                      end
    record.delete('lvl')
  end
  record
end