EventFilter: Event Filters

Description Modifying LogEvents with Filters Accessing Appenders and Loggers from Filters Note Examples

Description

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.

Modifying LogEvents with Filters

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()

Accessing Appenders and Loggers from Filters

You can use the special function .obj() to access the calling Logger/Appender from within a filter

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.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# using filters to modify log events
analyse <- function(){
  lgr$add_filter(FilterForceLevel$new("info"), "force")
  lgr$add_filter(FilterInject$new(type = "analysis"), "inject")
  on.exit(lgr$remove_filter(c("force", "inject")))
  lgr$debug("a debug message")
  lgr$error("an error")
}
analyse()
lgr$error("an error")


# using .obj()
l <- Logger$new("foo", threshold = "debug")
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
}
l$add_filter(f)
l$fatal("test")

s-fleck/yog documentation built on Jan. 17, 2019, 5:56 a.m.