From 6c334c9b69ca14eec105dd0306f7b5f386e1b5fe Mon Sep 17 00:00:00 2001 From: Sean Santry Date: Mon, 16 Jan 2023 23:05:13 -0500 Subject: [PATCH] Add optional pretty printing --- README.md | 2 +- lib/json_tagged_logger/formatter.rb | 20 +++++++++++++++++++- test/test_formatter.rb | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b3a84bb..329093b 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ will get you something like } ``` -[Note: I've pretty-printed the output in these examples for easier reading. The actual log output will be on a single line without extra whitespace.] +[_Note_: By default, `JsonTaggedLogger::Formatter` outputs logs as single lines without extra whitespace. Setting `JsonTaggedLogger::Formatter#pretty_print` to `true` will pretty print the logs, as I've done in these examples.] Importantly, if the controller action (or any code it calls along the way) has an explicit call to `Rails.logger.tagged("TAG").info("tagged log message")`, you'll get the same key/value tags (`request_id`, `host`, `my_param`, &c.) in the JSON document along with a `tags` key: diff --git a/lib/json_tagged_logger/formatter.rb b/lib/json_tagged_logger/formatter.rb index 4eab50a..c590352 100644 --- a/lib/json_tagged_logger/formatter.rb +++ b/lib/json_tagged_logger/formatter.rb @@ -3,6 +3,12 @@ module JsonTaggedLogger class Formatter + attr_accessor :pretty_print + + def initialize(pretty_print: false) + @pretty_pretty = pretty_print + end + def call(severity, _time, _progname, message) log = { level: severity, @@ -36,7 +42,7 @@ def call(severity, _time, _progname, message) end end - log.compact.to_json + "\n" + format_for_output(log) end private @@ -69,5 +75,17 @@ def message_without_tags(message) message end end + + def format_for_output(log_hash) + compacted_log = log_hash.compact + + output_json = if pretty_print + JSON.pretty_generate(compacted_log) + else + JSON.generate(compacted_log) + end + + output_json + "\n" + end end end diff --git a/test/test_formatter.rb b/test/test_formatter.rb index 0492de7..b2db560 100644 --- a/test/test_formatter.rb +++ b/test/test_formatter.rb @@ -140,4 +140,19 @@ def test_tags_merged_with_tags_in_json_message assert_equal "val1", results["key1"] assert_equal ["tag1", "tag2", "tag3", "tag4"], results["tags"] end + + def test_optional_pretty_printing + @logger.formatter.pretty_print = true + + @logger.info("hello world") + + expected_output = <<~JSON + { + "level": "INFO", + "msg": "hello world" + } + JSON + + assert_equal expected_output, @output.string + end end