Skip to content

Commit

Permalink
Add optional pretty printing
Browse files Browse the repository at this point in the history
  • Loading branch information
santry committed Jan 17, 2023
1 parent 79dc954 commit 6c334c9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
20 changes: 19 additions & 1 deletion lib/json_tagged_logger/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -36,7 +42,7 @@ def call(severity, _time, _progname, message)
end
end

log.compact.to_json + "\n"
format_for_output(log)
end

private
Expand Down Expand Up @@ -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
15 changes: 15 additions & 0 deletions test/test_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 6c334c9

Please sign in to comment.