Skip to content

Commit

Permalink
Fix Log to always log when an exception is provided
Browse files Browse the repository at this point in the history
Previous change crystal-lang#12000 skips logging when the given block returns
`nil`, however it inadvertently also suppresses logging exceptions.
Logging is now skipped only if both the given exception and the
block result are `nil`.
  • Loading branch information
lachlan committed Dec 9, 2024
1 parent 6df6b3d commit 7943999
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
17 changes: 16 additions & 1 deletion spec/std/log/log_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,28 @@ describe Log do
entry.exception.should be_nil
end

it "does not emit anything when a nil is emitted" do
it "does not emit when block returns nil" do
backend = Log::MemoryBackend.new
log = Log.new("a", backend, :notice)

log.notice { nil }

backend.entries.should be_empty
end

it "does emit when block returns nil but exception is provided" do
backend = Log::MemoryBackend.new
log = Log.new("a", backend, :notice)
ex = Exception.new "the attached exception"

log.notice(exception: ex) { nil }

entry = backend.entries.first
entry.source.should eq("a")
entry.severity.should eq(s(:notice))
entry.message.should eq("")
entry.data.should eq(Log::Metadata.empty)
entry.exception.should eq(ex)
end
end
end
17 changes: 10 additions & 7 deletions src/log/log.cr
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,16 @@ class Log
dsl = Emitter.new(@source, severity, exception)
result = yield dsl

case result
when Entry
backend.dispatch result
when Nil
# emit nothing
else
backend.dispatch dsl.emit(result.to_s)
unless exception.nil? && result.nil?
entry =
case result
when Entry
result
else
dsl.emit(result.to_s)
end

backend.dispatch entry
end
end
{% end %}
Expand Down

0 comments on commit 7943999

Please sign in to comment.