EventFilters specify arbitrarily complex logic for whether or
not a LogEvent should be processed by a Logger or Appender. They are
attached to Loggers/Appenders via their $set_filter()
or $add_filter()
methods. If any EventFilter evaluates to FALSE
for a given event, that
event is ignored - similarly to when it does not pass the objects'
threshold.
Usually you do not need to instantiate a formal EventFilter
object as you
can just use any function
that has the single argument event
instead.
If you need to implement more complex filter logic - for example a filter
that is dependent on a dataset - it might be desirable to subclass
EventFilter, as R6::R6 objects can store data and functions together.
.obj()
is a special function that can only be used within the
$filter()
methods of EventFilters. It returns the Logger
or Appender that the EventFilter is attached to.
.obj()
Since LogEvents are R6 objects with reference semantics, EventFilters can be
abused to modify events before passing them on. lgr comes with a few
preset filters that use this property: FilterInject (similar to
with_log_level()
) and FilterForceLevel (similar to with_log_value()
).
NOTE: The base class for Filters is called EventFilter
so that it
doesn't conflict with base::Filter()
. The recommended convention for
Filter subclasses is to call them FilterSomething
and leave out the
Event
prefix.
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")
#> via event$.logger: 400
#> via .obj(): 400
#> FATAL [20:04:26.747] test
lg$config(NULL)
#> <Logger> [info] test
#>
#> inherited appenders:
#> console: <AppenderConsole> [all] -> console