Skip to content

Instantly share code, notes, and snippets.

@frank-kutzey
Last active June 15, 2017 15:34
Show Gist options
  • Save frank-kutzey/02d54375ae3aed6d393701ab9cbdf8c0 to your computer and use it in GitHub Desktop.
Save frank-kutzey/02d54375ae3aed6d393701ab9cbdf8c0 to your computer and use it in GitHub Desktop.
converts looker logs from plain text log to json like format - usefull for importing logs to EBK or ELK
#!/usr/bin/env python
from json import dumps
import sys
while True:
string = sys.stdin.readline()
if not string:
break
try:
level = 'UNKNOWN'
if '[DEBUG|' in string:
level = 'DEBUG'
if '[VERBOSE|' in string:
level = 'VERBOSE'
if '[INFO|' in string:
level = 'INFO'
if '[WARN|' in string:
level = 'WARN'
if '[ERROR|' in string:
level = 'ERROR'
if '[FATAL|' in string:
level = 'FATAL'
tmp_string = string[string.find('] ::') - 20:string.find('] ::')]
looker_log_type = string[string.find('] ::') - 20:string.find('] ::')][tmp_string.rfind('|') + 1:255].strip()
result = dict(
createtime=string[0:string.find('[')].strip().replace(' ', 'T').replace('T+', ' +'),
looker_log_type=looker_log_type,
level=level,
message=string[string.find('::') + 3:string.find('::') + 1000].strip()
)
print(dumps(result))
except Exception as error:
print(error)
@michael-erasmus
Copy link

michael-erasmus commented Jan 6, 2017

Thanks for this @sisu-frank-kutzey! I wanted to capture all level of logs, including some tricky INFO messages that had queries with newlines in them, causing the log file to have multiple lines per log. Here is the tweaked code to do that:

try:
    level = 'UNKNOWN'
    if '[DEBUG|' in string:
      level = 'DEBUG'
    if '[VERBOSE|' in string:
      level = 'VERBOSE'
    if '[INFO|' in string:
      level = 'INFO'
    if '[WARN|' in string:
      level = 'WARN'
    if '[ERROR|' in string:
      level = 'ERROR'
    if '[FATAL|' in string:
      level = 'FATAL'

    if '::' in string: #this is a log start line
      #print the previous result
      print(dumps(result))

      #start building the next one
      tmp_string = string[string.find('] ::') - 20:string.find('] ::')]
      looker_log_type = string[string.find('] ::') - 20:string.find('] ::')][tmp_string.rfind('|') + 1:255].strip()
      message=string[string.find('::') + 3:string.find('::') + 1000].strip()

      result = dict(
        createtime=string[0:string.find('[')].strip().replace(' ', 'T').replace('T+', ' +'),
        looker_log_type=looker_log_type,
        level=level,
        message=string[string.find('::') + 3:string.find('::') + 1000].strip()
      )
    else:
        result['message'] = result['message'] += string
  except Exception as error:
    sys.stderr.write(error)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment