Skip to content

Commit 26801b9

Browse files
committed
add closure example
1 parent 9e0052d commit 26801b9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,44 @@ The filter function for early filter logging only has access to the
148148
The most notable use of it is to filter based on modules,
149149
see the HTTP example below.
150150

151+
Another example is using them to stop messages every being repeated within a given time period.
152+
153+
```
154+
using Dates, Logging, LoggingExtras
155+
156+
julia> function make_throttled_logger(period)
157+
history = Dict{Symbol, DateTime}()
158+
# We are going to use a closure
159+
EarlyFilteredLogger(global_logger()) do log
160+
if !haskey(history, log.id) || (period < now() - history[log.id])
161+
# then we will log it, and update record of when we did
162+
history[log.id] = now()
163+
return true
164+
else
165+
return false
166+
end
167+
end
168+
end
169+
make_throttled_logger (generic function with 1 method)
170+
171+
julia> throttled_logger = make_throttled_logger(Second(3));
172+
173+
julia> with_logger(throttled_logger) do
174+
for ii in 1:10
175+
sleep(1)
176+
@info "It happen" ii
177+
end
178+
end
179+
┌ Info: It happen
180+
└ ii = 1
181+
┌ Info: It happen
182+
└ ii = 4
183+
┌ Info: It happen
184+
└ ii = 7
185+
┌ Info: It happen
186+
└ ii = 10
187+
```
188+
151189
## `MinLevelLogger`
152190
This is basically a special case of the early filtered logger,
153191
that just checks if the level of the message is above the level specified when it was created.

0 commit comments

Comments
 (0)