Skip to content

Commit

Permalink
Log entry metadata when it's not empty (#45)
Browse files Browse the repository at this point in the history
* Log entry metadata when it's not empty

* Convert metadata to hash
  • Loading branch information
cyangle authored Dec 13, 2021
1 parent c29fc11 commit 5e60a84
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
9 changes: 9 additions & 0 deletions spec/json_log_formatter_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ describe Dexter::JSONLogFormatter do
)
end

it "formats the entry metadata as json" do
io = IO::Memory.new
entry = build_entry({my_data: "is great!"}, source: "json-test", severity: :debug, data: Log::Metadata.build({metadata: "is great!", more_data: "more!"}))
format(entry, io)
io.to_s.chomp.should eq(
{severity: "Debug", source: "json-test", timestamp: timestamp, data: {metadata: "is great!", more_data: "more!"}, my_data: "is great!"}.to_json
)
end

it "formats complex types" do
io = IO::Memory.new
entry = build_entry({args: [1], params: {foo: "bar"}, other: {arr: [1]}}, source: "json-test", severity: :debug)
Expand Down
18 changes: 13 additions & 5 deletions src/dexter/json_log_formatter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,23 @@ module Dexter
end

private def default_data
data = {
"severity" => entry.severity.to_s,
"source" => entry.source,
"timestamp" => entry.timestamp,
}
data = Hash(String, String | Time | Hash(String, String)).new
data["severity"] = entry.severity.to_s
data["source"] = entry.source
data["timestamp"] = entry.timestamp
data["data"] = metadata unless entry.data.empty?
data["message"] = entry.message unless entry.message.empty?
data
end

private def metadata
Hash(String, String).new.tap do |hash|
entry.data.each do |key, value|
hash[key.to_s] = value.to_s
end
end
end

private def exception_data
entry.exception.try do |ex|
{"error" => {"class" => ex.class.name, "message" => ex.message, "backtrace" => ex.backtrace?}}
Expand Down

0 comments on commit 5e60a84

Please sign in to comment.