|
| 1 | +using Logging |
| 2 | +using ResumableFunctions |
| 3 | +using Test |
| 4 | + |
| 5 | +mutable struct CaptureLogger <: AbstractLogger |
| 6 | + records::Vector{NamedTuple} |
| 7 | +end |
| 8 | + |
| 9 | +Logging.min_enabled_level(::CaptureLogger) = Logging.Debug |
| 10 | +Logging.shouldlog(::CaptureLogger, _level, _module, _group, _id) = true |
| 11 | +Logging.catch_exceptions(::CaptureLogger) = false |
| 12 | + |
| 13 | +function Logging.handle_message( |
| 14 | + logger::CaptureLogger, |
| 15 | + level, |
| 16 | + message, |
| 17 | + _module, |
| 18 | + group, |
| 19 | + id, |
| 20 | + file, |
| 21 | + line; |
| 22 | + kwargs..., |
| 23 | +) |
| 24 | + push!(logger.records, (; level, message, group, metadata=(; kwargs...))) |
| 25 | +end |
| 26 | + |
| 27 | +@resumable function logging_generator() |
| 28 | + round = 3 |
| 29 | + pair_id = 7 |
| 30 | + attempts = 2 |
| 31 | + @debug( |
| 32 | + "Logging from a resumable function", |
| 33 | + _group=:protocol, |
| 34 | + event=:round_started, |
| 35 | + round=round, |
| 36 | + pair_id, |
| 37 | + attempts, |
| 38 | + ) |
| 39 | + @yield round |
| 40 | +end |
| 41 | + |
| 42 | +@resumable function qualified_logging_generator() |
| 43 | + value = 4 |
| 44 | + Logging.@info( |
| 45 | + "Qualified logging macro", |
| 46 | + _group=:qualified, |
| 47 | + event=:qualified_record, |
| 48 | + value, |
| 49 | + ) |
| 50 | + @logmsg( |
| 51 | + Logging.Warn, |
| 52 | + "Logging with an explicit level", |
| 53 | + _group=:logmsg, |
| 54 | + event=:logmsg_record, |
| 55 | + value, |
| 56 | + ) |
| 57 | + @yield value |
| 58 | +end |
| 59 | + |
| 60 | +@testset "structured logging metadata" begin |
| 61 | + logger = CaptureLogger(NamedTuple[]) |
| 62 | + values = Logging.with_logger(logger) do |
| 63 | + collect(logging_generator()) |
| 64 | + end |
| 65 | + |
| 66 | + @test values == [3] |
| 67 | + @test length(logger.records) == 1 |
| 68 | + record = only(logger.records) |
| 69 | + @test record.level == Logging.Debug |
| 70 | + @test record.message == "Logging from a resumable function" |
| 71 | + @test record.group == :protocol |
| 72 | + @test record.metadata == ( |
| 73 | + event=:round_started, |
| 74 | + round=3, |
| 75 | + pair_id=7, |
| 76 | + attempts=2, |
| 77 | + ) |
| 78 | + |
| 79 | + empty!(logger.records) |
| 80 | + values = Logging.with_logger(logger) do |
| 81 | + collect(qualified_logging_generator()) |
| 82 | + end |
| 83 | + |
| 84 | + @test values == [4] |
| 85 | + @test length(logger.records) == 2 |
| 86 | + qualified_record, logmsg_record = logger.records |
| 87 | + @test qualified_record.level == Logging.Info |
| 88 | + @test qualified_record.group == :qualified |
| 89 | + @test qualified_record.metadata == (event=:qualified_record, value=4) |
| 90 | + @test logmsg_record.level == Logging.Warn |
| 91 | + @test logmsg_record.group == :logmsg |
| 92 | + @test logmsg_record.metadata == (event=:logmsg_record, value=4) |
| 93 | +end |
0 commit comments