Skip to content

Commit d46eef0

Browse files
feat(logging): add logging.jl for custom logging utilities
1 parent 5df577f commit d46eef0

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

src/logging.jl

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using Logging
2+
using Logging: AbstractLogger, LogLevel, Info, global_logger
3+
using LoggingExtras: TeeLogger, FileLogger
4+
using Dates
5+
using Printf
6+
7+
struct TimestampLogger <: AbstractLogger
8+
logger::AbstractLogger
9+
end
10+
11+
Logging.min_enabled_level(logger::TimestampLogger) = Logging.min_enabled_level(logger.logger)
12+
Logging.shouldlog(logger::TimestampLogger, level, _module, group, id) =
13+
Logging.shouldlog(logger.logger, level, _module, group, id)
14+
15+
function Logging.handle_message(logger::TimestampLogger, level, message, _module, group, id,
16+
filepath, line; kwargs...)
17+
timestamp = Dates.format(now(), "yyyy-mm-dd HH:MM:SS")
18+
new_message = "[$timestamp] $message"
19+
Logging.handle_message(logger.logger, level, new_message, _module, group, id,
20+
filepath, line; kwargs...)
21+
end
22+
23+
function setup_logging!(verbosity::Int, logfile::Union{String,Nothing}=nothing)
24+
level = verbosity >= 2 ? Logging.Debug :
25+
verbosity == 1 ? Logging.Info : Logging.Warn
26+
27+
# Create console logger
28+
console_logger = ConsoleLogger(stderr, level)
29+
30+
if isnothing(logfile)
31+
# Log to console only
32+
global_logger(TimestampLogger(console_logger))
33+
else
34+
# Try to set up file logging with fallback to console-only
35+
try
36+
file_logger = FileLogger(logfile, level)
37+
combined_logger = TeeLogger(console_logger, file_logger)
38+
global_logger(TimestampLogger(combined_logger))
39+
catch e
40+
@warn "Failed to set up file logging to $(_display_path(logfile)): $e"
41+
42+
global_logger(TimestampLogger(console_logger))
43+
end
44+
end
45+
end
46+
47+
function __init__()
48+
# Set a default logging level when the package is loaded at runtime.
49+
setup_logging!(0)
50+
end

0 commit comments

Comments
 (0)