
Last chance! 50% off unlimited learning
Sale ends in
Filters can be used for the $set_filter()
and $add_filter()
methods of
Appenders and Loggers. You normally do not need to construct a formal
EventFilter
object, you can just use any function
that has the single
argument event
or any object that has a filter
method.
Since LogEvents are R6 objects with reference semantics, Filters can also be abused to modify log events before passing them on. lgr comes with a few preset filters that use this property:
FilterInject$new(..., .list)
...
and .list
can take any number
of named R6 objects that will be injected as custom fields into all
LogEvents processed by the Appender/Logger that this filter is attached
to. See also with_log_value()
FilterForceLevel$new(level)
Sets the level of all LogEvents
processed by the Appender/Logger that this filter is attached to to
level
. See also with_log_value()
You can use the special function .obj()
to access the calling
Logger/Appender from within a filter
# NOT RUN {
# using filters to modify log events
lg <- get_logger("test")
analyse <- function(){
lg$add_filter(FilterForceLevel$new("info"), "force")
lg$add_filter(FilterInject$new(type = "analysis"), "inject")
on.exit(lg$remove_filter(c("force", "inject")))
lg$debug("a debug message")
lg$error("an error")
}
analyse()
lg$error("an error")
lg$config(NULL) # reset config
# using .obj()
lg <- get_logger("test")
f <- function(event) {
cat("via event$.logger:", event$.logger$threshold, "\n") # works for loggers only
cat("via .obj(): ",.obj()$threshold, "\n") # works for loggers and appenders
TRUE
}
lg$add_filter(f)
lg$fatal("test")
lg$config(NULL)
# }
Run the code above in your browser using DataLab