Skip to content

Commit

Permalink
Support for user defined logging handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
essenciary committed Oct 25, 2023
1 parent 86e1aec commit aa28990
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "Genie"
uuid = "c43c736e-a2d1-11e8-161f-af95117fbd1e"
authors = ["Adrian Salceanu <[email protected]>"]
version = "5.19.1"
version = "5.20.0"

[deps]
ArgParse = "c7e460c6-2fb9-53a9-8c5b-16f535851c63"
Expand Down
61 changes: 61 additions & 0 deletions src/Logger.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@ using Genie
using Logging, LoggingExtras
import Dates

"""
Collection of custom user defined handlers that will be called when a log message is received.
# Example
```julia
julia> f(args...) = println(args...)
julia> push!(Logger.HANDLERS, f)
julia> @info "hello"
[ Info: 2023-10-25 13:36:15 hello
Info2023-10-25 13:36:15 helloMainREPL[5]Main_0f6a5e07REPL[5]1
```
"""
const HANDLERS::Vector{Function} = Function[]

function timestamp_logger(logger)
date_format = Genie.config.log_date_format

Expand All @@ -26,10 +42,55 @@ function initialize_logging(; log_name = default_log_name())
else
Logging.ConsoleLogger(stdout, Genie.config.log_level)
end
logger = LoggingExtras.TeeLogger(
logger,
GenieLogger() do lvl, msg, _mod, group, id, file, line
for handler in HANDLERS
try
handler(lvl, msg, _mod, group, id, file, line)
catch
end
end
end
)

LoggingExtras.TeeLogger(LoggingExtras.MinLevelLogger(logger, Genie.config.log_level)) |> timestamp_logger |> global_logger

nothing
end

### custom logger

"""
GenieLogger is a custom logger that allows you to pass a function that will be called with the log message, level, module, group, id, file and line.
# Example
```julia
l = Genie.Logger.GenieLogger() do lvl, msg, _mod, group, id, file, line
uppercase(msg) |> println
end
with_logger(l) do
@info "hello"
@warn "watch out"
@error "oh noh"
end
```
"""
struct GenieLogger <: Logging.AbstractLogger
action::Function
io::IO
end

GenieLogger(action::Function) = GenieLogger(action, stderr)

Logging.min_enabled_level(logger::GenieLogger) = Logging.BelowMinLevel
Logging.shouldlog(logger::GenieLogger, level, _module, group, id) = true
Logging.catch_exceptions(logger::GenieLogger) = true

function Logging.handle_message(logger::GenieLogger, lvl, msg, _mod, group, id, file, line; kwargs...)
logger.action(lvl, msg, _mod, group, id, file, line; kwargs...)
nothing
end

end

0 comments on commit aa28990

Please sign in to comment.