Skip to content

Commit

Permalink
Add Log overloads for logging exceptions without giving a block (#1…
Browse files Browse the repository at this point in the history
…5257)

Per the discussion on #15221, this change provides non-yielding
overloads to the `Log.{{severity}}` methods for logging exceptions
without giving an associated message producing block.
  • Loading branch information
lachlan authored Dec 14, 2024
1 parent 8f12767 commit c878d22
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
20 changes: 20 additions & 0 deletions spec/std/log/log_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ describe Log do
backend.entries.all? { |e| e.exception == ex }.should be_true
end

it "can log exceptions without specifying a block" do
backend = Log::MemoryBackend.new
log = Log.new("a", backend, :warn)
ex = Exception.new

log.trace(exception: ex)
log.debug(exception: ex)
log.info(exception: ex)
log.notice(exception: ex)
log.warn(exception: ex)
log.error(exception: ex)
log.fatal(exception: ex)

backend.entries.map { |e| {e.source, e.severity, e.message, e.data, e.exception} }.should eq([
{"a", s(:warn), "", Log::Metadata.empty, ex},
{"a", s(:error), "", Log::Metadata.empty, ex},
{"a", s(:fatal), "", Log::Metadata.empty, ex},
])
end

it "contains the current context" do
Log.context.set a: 1

Expand Down
9 changes: 9 additions & 0 deletions src/log/log.cr
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ class Log
{% for method in %w(trace debug info notice warn error fatal) %}
{% severity = method.id.camelcase %}

# Logs the given *exception* if the logger's current severity is lower than
# or equal to `Severity::{{severity}}`.
def {{method.id}}(*, exception : Exception) : Nil
severity = Severity::{{severity}}
if level <= severity && (backend = @backend)
backend.dispatch Emitter.new(@source, severity, exception).emit("")
end
end

# Logs a message if the logger's current severity is lower than or equal to
# `Severity::{{ severity }}`.
#
Expand Down
5 changes: 5 additions & 0 deletions src/log/main.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ class Log
private Top = Log.for("")

{% for method in %i(trace debug info notice warn error fatal) %}
# See `Log#{{method.id}}`.
def self.{{method.id}}(*, exception : Exception) : Nil
Top.{{method.id}}(exception: exception)
end

# See `Log#{{method.id}}`.
def self.{{method.id}}(*, exception : Exception? = nil)
Top.{{method.id}}(exception: exception) do |dsl|
Expand Down

0 comments on commit c878d22

Please sign in to comment.