Skip to content

Commit

Permalink
Add default_attributes to Logger
Browse files Browse the repository at this point in the history
This adds the ability to add default attributes to a logger object.

One usecase for this:

You create a Logger, for which you already know a specific attribute,
you can now set it on the initialize instead of having to pass it around
all the time.
  • Loading branch information
jvanbaarsen authored and unflxw committed Nov 12, 2024
1 parent 8b234ca commit 27e05af
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .changesets/add-default-attributes-to-logger.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
bump: patch
type: add
---

Add default attributes to Logger
7 changes: 4 additions & 3 deletions lib/appsignal/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,21 @@ class Logger < ::Logger
FATAL => 7
}.freeze

attr_reader :level
attr_reader :level, :default_attributes

# Create a new logger instance
#
# @param group Name of the group for this logger.
# @param level Log level to filter with
# @return [void]
def initialize(group, level: INFO, format: PLAINTEXT)
def initialize(group, level: INFO, format: PLAINTEXT, default_attributes: {})
raise TypeError, "group must be a string" unless group.is_a? String

@group = group
@level = level
@format = format
@mutex = Mutex.new
@default_attributes = default_attributes
end

# We support the various methods in the Ruby
Expand Down Expand Up @@ -157,7 +158,7 @@ def silence(_severity = ERROR, &block)
private

def add_with_attributes(severity, message, group, attributes)
Thread.current[:appsignal_logger_attributes] = attributes
Thread.current[:appsignal_logger_attributes] = default_attributes.merge!(attributes)
add(severity, message, group)
ensure
Thread.current[:appsignal_logger_attributes] = nil
Expand Down
10 changes: 10 additions & 0 deletions spec/lib/appsignal/logger_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,16 @@
end
end

describe "a logger with default attributes" do
it "adds the attributes when a message is logged" do
logger = Appsignal::Logger.new("group", :default_attributes => { :some_key => "some_value" })

expect(Appsignal::Extension).to receive(:log).with("group", 6, 0, "Some message",
Appsignal::Utils::Data.generate({ :other_key => "other_value", :some_key => "some_value" }))
logger.error("Some message", { :other_key => "other_value" })
end
end

describe "#error with exception object" do
it "logs the exception class and its message" do
error =
Expand Down

0 comments on commit 27e05af

Please sign in to comment.