Created
July 26, 2018 16:46
-
-
Save bobisme/285b047d0ce804ecdbc025903c1978a6 to your computer and use it in GitHub Desktop.
Simplifying the semantic logger formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'logger' | |
require 'semantic_logger' | |
class KubeFmt < SemanticLogger::Formatters::Json | |
# redefine the defaults for log_host and log_application to be false | |
def initialize( | |
time_format: :iso_8601, log_host: false, log_application: false, | |
time_key: :timestamp | |
) | |
super( | |
time_format: time_format, log_host: log_host, | |
log_application: log_application, time_key: time_key | |
) | |
end | |
def message | |
super | |
return if hash[:message] | |
# use the exception to form the message is there is none | |
return unless log.exception | |
hash[:message] = "#{log.exception.class.name}: #{log.exception.message}" | |
end | |
# redefine process_info to exclude pid and thread | |
def process_info | |
file, line = log.file_name_and_line | |
return unless file | |
hash[:file] = file | |
hash[:line] = line.to_i | |
end | |
# eliminate the useless "log_index" field | |
def level | |
hash[:level] = log.level | |
end | |
end | |
SemanticLogger.add_appender(io: STDOUT, formatter: KubeFmt.new) | |
logger = SemanticLogger['poop'] | |
logger.level = :debug | |
logger.info('poop') | |
begin | |
raise 'WTF' | |
rescue StandardError => exc | |
logger.fatal(exc) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"timestamp": "2018-07-26T16:46:06.602569Z", | |
"level": "info", | |
"name": "poop", | |
"message": "poop" | |
} | |
{ | |
"timestamp": "2018-07-26T16:46:06.602623Z", | |
"level": "fatal", | |
"file": "./app.rb", | |
"line": 49, | |
"name": "poop", | |
"message": "RuntimeError: WTF", | |
"exception": { | |
"name": "RuntimeError", | |
"message": "WTF", | |
"stack_trace": [ | |
"./app.rb:47:in `<main>'" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment