Skip to content

Commit 7d48e61

Browse files
authored
Merge pull request #18 from Arkoniak/upgrade_03
Upgrade 03
2 parents b77e08b + b06504a commit 7d48e61

File tree

4 files changed

+81
-25
lines changed

4 files changed

+81
-25
lines changed

Project.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
name = "MiniLoggers"
22
uuid = "93f3dd0f-005d-4452-894a-a31841fa4078"
33
authors = ["Andrey Oskin"]
4-
version = "0.2.6"
4+
version = "0.3.0"
55

66
[deps]
77
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
88
Logging = "56ddb016-857b-54e1-b83d-db4d58db5568"
9+
Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a"
910

1011
[compat]
1112
julia = "1"

src/minilogger.jl

Lines changed: 51 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
struct MiniLogger{IOT1 <: IO, IOT2 <: IO, DFT <: DateFormat} <: AbstractLogger
1+
abstract type AbstractMode end
2+
struct NoTransformations <: AbstractMode end
3+
struct Squash <: AbstractMode end
4+
5+
struct MiniLogger{AM <: AbstractMode, IOT1 <: IO, IOT2 <: IO, DFT <: DateFormat} <: AbstractLogger
26
io::IOT1
37
ioerr::IOT2
48
errlevel::LogLevel
@@ -7,7 +11,7 @@ struct MiniLogger{IOT1 <: IO, IOT2 <: IO, DFT <: DateFormat} <: AbstractLogger
711
flush::Bool
812
format::Vector{Token}
913
dtformat::DFT
10-
squash_message::Bool
14+
mode::AM
1115
flush_threshold::Int
1216
lastflush::Base.RefValue{Int}
1317
end
@@ -18,6 +22,16 @@ getio(io::AbstractString, append) = open(io, append ? "a" : "w")
1822
getflushthreshold(x::Integer) = x
1923
getflushthreshold(x::TimePeriod) = Dates.value(Millisecond(x))
2024

25+
getmode(mode) = mode
26+
getmode(mode::AbstractString) = getmode(Symbol(mode))
27+
function getmode(mode::Symbol)
28+
if mode == :notransformations
29+
return NoTransformations()
30+
elseif mode == :squash
31+
return Squash()
32+
end
33+
end
34+
2135
function Base.close(logger::MiniLogger)
2236
if logger.io != stdout && logger.io != stderr && isopen(logger.io)
2337
close(logger.io)
@@ -40,12 +54,14 @@ Supported keyword arguments include:
4054
* `errlevel` (default `Error`): determines which output IO to use for log messages. If you want for all messages to go to `io`, set this parameter to `MiniLoggers.AboveMaxLevel`. If you want for all messages to go to `ioerr`, set this parameter to `MiniLoggers.BelowMinLevel`.
4155
* `minlevel` (default: `Info`): messages below this level are ignored. For example with default setting `@debug "foo"` is ignored.
4256
* `append` (default: `false`): defines whether to append to output stream or to truncate file initially. Used only if `io` or `ioerr` is a file path.
43-
* `squash_message` (default: `true`): if `squash_message` is set to `true`, then message is squashed to a single line, i.e. all `\\n` are changed to ` ` and `\\r` are removed.
57+
* `message_mode` (default: `:squash`): choose how message is transformed before being printed out. Following modes are supported:
58+
* `:notransformations`: message printed out as is, without any extra transformations
59+
* `:squash`: message is squashed to a single line, i.e. all `\\n` are changed to ` ` and `\\r` are removed.
4460
* `flush` (default: `true`): whether to `flush` IO stream for each log message. Flush behaviour also affected by `flush_threshold` argument.
4561
* `flush_threshold::Union{Integer, TimePeriod}` (default: 0): if this argument is nonzero and `flush` is `true`, then `io` is flushed only once per `flush_threshold` milliseconds. I.e. if time between two consecutive log messages is less then `flush_threshold`, then second message is not flushed and will have to wait for the next log event.
4662
* `dtformat` (default: "yyyy-mm-dd HH:MM:SS"): if `datetime` parameter is used in `format` argument, this dateformat is applied for output timestamps.
47-
* `format` (default: "{[{datetime}]:func} {message}"): format for output log message. It accepts following keywords, which should be provided in curly brackets:
48-
* `datetime`: timestamp of the log message
63+
* `format` (default: "[{timestamp:func}] {level:func}: {message}"): format for output log message. It accepts following keywords, which should be provided in curly brackets:
64+
* `timestamp`: timestamp of the log message
4965
* `level`: name of log level (Debug, Info, etc)
5066
* `filepath`: filepath of the file, which produced log message
5167
* `basename`: basename of the filepath of the file, which produced log message
@@ -61,11 +77,21 @@ Colour information is applied recursively without override, so `{{line} {module:
6177
6278
If part of the format is not a recognised keyword, then it is just used as is, for example `{foo:red}` means that output log message contain word "foo" printed in red.
6379
"""
64-
function MiniLogger(; io = stdout, ioerr = stderr, errlevel = Error, minlevel = Info, append = false, message_limits = Dict{Any, Int}(), flush = true, format = "{[{datetime}]:func} {message}", dtformat = dateformat"yyyy-mm-dd HH:MM:SS", squash_message = true, flush_threshold = 0)
80+
function MiniLogger(; io = stdout, ioerr = stderr, errlevel = Error, minlevel = Info, append = false, message_limits = Dict{Any, Int}(), flush = true, format = "[{timestamp:func}] {level:func}: {message}", dtformat = dateformat"yyyy-mm-dd HH:MM:SS", flush_threshold = 0, message_mode = Squash())
6581
tio = getio(io, append)
6682
tioerr = io == ioerr ? tio : getio(ioerr, append)
6783
lastflush = Dates.value(Dates.now())
68-
MiniLogger(tio, tioerr, errlevel, minlevel, message_limits, flush, tokenize(format), dtformat, squash_message, getflushthreshold(flush_threshold), Ref(lastflush))
84+
MiniLogger(tio,
85+
tioerr,
86+
errlevel,
87+
minlevel,
88+
message_limits,
89+
flush,
90+
tokenize(format),
91+
dtformat,
92+
getmode(message_mode),
93+
getflushthreshold(flush_threshold),
94+
Ref(lastflush))
6995
end
7096

7197
shouldlog(logger::MiniLogger, level, _module, group, id) =
@@ -84,20 +110,24 @@ end
84110
showvalue(io, ex::Exception) = Base.showerror(io, ex)
85111
showvalue(io, ex::AbstractVector{Union{Ptr{Nothing}, Base.InterpreterIP}}) = Base.show_backtrace(io, ex)
86112

87-
function showmessage(io, msg, squash)
88-
if squash
89-
msglines = split(chomp(string(msg)), '\n')
90-
print(io, replace(msglines[1], "\r" => ""))
91-
for i in 2:length(msglines)
92-
print(io, " ", replace(msglines[i], "\r" => ""))
93-
end
94-
else
95-
print(io, msg)
113+
# Here we are fighting with multiple dispatch.
114+
# If message is `Exception` or `Tuple{Exception, Any}` or anything else
115+
# then we want to ignore third argument.
116+
# But if it is any other sort of message we want to dispatch result
117+
# on the type of message transformation
118+
function _showmessage(io, msg, ::Squash)
119+
msglines = split(chomp(string(msg)), '\n')
120+
print(io, replace(msglines[1], "\r" => ""))
121+
for i in 2:length(msglines)
122+
print(io, " ", replace(msglines[i], "\r" => ""))
96123
end
97124
end
98-
showmessage(io, e::Tuple{Exception,Any}, squash) = showvalue(io, e)
99-
showmessage(io, ex::Exception, squash) = showvalue(io, e)
100-
showmessage(io, ex::AbstractVector{Union{Ptr{Nothing}, Base.InterpreterIP}}, squash) = Base.show_backtrace(io, ex)
125+
_showmessage(io, msg, ::NoTransformations) = print(io, msg)
126+
127+
showmessage(io, msg, mode) = _showmessage(io, msg, mode)
128+
showmessage(io, e::Tuple{Exception,Any}, _) = showvalue(io, e)
129+
showmessage(io, ex::Exception, _) = showvalue(io, ex)
130+
showmessage(io, ex::AbstractVector{Union{Ptr{Nothing}, Base.InterpreterIP}}, _) = Base.show_backtrace(io, ex)
101131

102132
tsnow(dtf) = Dates.format(Dates.now(), dtf)
103133

@@ -149,10 +179,10 @@ function handle_message(logger::MiniLogger, level, message, _module, group, id,
149179
for token in logger.format
150180
c = extractcolor(token, level, _module, group, id, filepath, line)
151181
val = token.val
152-
if val == "datetime"
182+
if val == "timestamp"
153183
printwcolor(iob, tsnow(logger.dtformat), c)
154184
elseif val == "message"
155-
showmessage(iob, message, logger.squash_message)
185+
showmessage(iob, message, logger.mode)
156186

157187
iscomma = false
158188
for (key, val) in kwargs

test/test02_loggerformat.jl

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ conts(s, sub) = match(Regex(sub), s) !== nothing
88
@testset "basic format" begin
99
io = IOBuffer()
1010
logger = MiniLogger(io = io, minlevel = MiniLoggers.Debug,
11-
format = "{datetime}:{level}:{module}:{basename}:{filepath}:{line}:{group}:{module}:{id}:{message}")
11+
format = "{timestamp}:{level}:{module}:{basename}:{filepath}:{line}:{group}:{module}:{id}:{message}")
1212
with_logger(logger) do
1313
@info "foo"
1414
s = String(take!(io))
15-
@test !conts(s, "datetime")
15+
@test !conts(s, "timestamp")
1616
@test !conts(s, "level")
1717
@test !conts(s, "module")
1818
@test !conts(s, "basename")
@@ -36,7 +36,7 @@ end
3636
@test s == "foo bar\n"
3737
end
3838

39-
logger = MiniLogger(io = io, format = "{message}", squash_message = false)
39+
logger = MiniLogger(io = io, format = "{message}", message_mode = :notransformations)
4040
with_logger(logger) do
4141
@info "foo\nbar"
4242

@@ -92,6 +92,22 @@ end
9292

9393
s = String(take!(io))
9494
@test conts(s, "^foo exception = ERROR\n *Stacktrace")
95+
96+
try
97+
error("ERROR")
98+
catch err
99+
@error err
100+
end
101+
s = String(take!(io))
102+
@test s == "ERROR\n"
103+
104+
try
105+
error("ERROR")
106+
catch err
107+
@error catch_backtrace()
108+
end
109+
s = String(take!(io))
110+
@test conts(s, "^\n *Stacktrace")
95111
end
96112
end
97113

test/test03_misc.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ module MiscTest
22

33
using ReTest
44
using MiniLoggers
5+
using MiniLoggers: getmode, NoTransformations, Squash
6+
57
using Dates
68

79
@testset "flush" begin
@@ -97,4 +99,11 @@ end
9799
end
98100
end
99101

102+
@testset "modes" begin
103+
@test getmode("notransformations") isa NoTransformations
104+
@test getmode("squash") isa Squash
105+
@test getmode(:notransformations) isa NoTransformations
106+
@test getmode(:squash) isa Squash
107+
end
108+
100109
end # module

0 commit comments

Comments
 (0)