Debian Codegraph @

R/Filter.R

raw
1 # EventFilter -------------------------------------------------------------
2
3 #' Event Filters
4 #'
5 #' @description EventFilters specify arbitrarily complex logic for whether or
6 #' not a LogEvent should be processed by a [Logger] or [Appender]. They are
7 #' attached to Loggers/Appenders via their `$set_filter()` or `$add_filter()`
8 #' methods. If any EventFilter evaluates to `FALSE` for a given event, that
9 #' event is ignored - similarly to when it does not pass the objects'
10 #' threshold.
11 #'
12 #' Usually you do not need to instantiate a formal `EventFilter` object as you
13 #' can just use any `function` that has the single argument `event` instead.
14 #' If you need to implement more complex filter logic - for example a filter
15 #' that is dependent on a dataset - it might be desirable to subclass
16 #' EventFilter, as [R6::R6] objects can store data and functions together.
17 #'
18 #'
19 #' @section Modifying LogEvents with EventFilters:
20 #'
21 #' Since LogEvents are R6 objects with reference semantics, EventFilters can be
22 #' abused to modify events before passing them on. lgr comes with a few
23 #' preset filters that use this property: [FilterInject] (similar to
24 #' [with_log_level()]) and [FilterForceLevel] (similar to [with_log_value()]).
25 #'
26 #' **NOTE:** The base class for Filters is called `EventFilter` so that it
27 #' doesn't conflict with [base::Filter()]. The recommended convention for
28 #' Filter subclasses is to call them `FilterSomething` and leave out the
29 #' `Event` prefix.
30 #'
31 #' @aliases Filter
32 #' @seealso [is_filter()]
33 #' @export
34 EventFilter <- R6::R6Class(
35 "EventFilter",
36 public = list(
37
38 #' @description Initialize a new EventFilter
39 #' @param fun a `function` with a single argument `event` that must return
40 #' either `TRUE` or `FALSE`. Any non-`FALSE` will be interpreted as
41 #' `TRUE` (= no filtering takes place) and a warning will be thrown.
42 initialize = function(fun = function(event) TRUE){
43 self$filter <- fun
44 },
45
46 #' @description filter The `filter` method of an event must return either
47 #' `TRUE` or `FALSE`. If it returns `TRUE`, [Filterable]s such as
48 #' [Appenders] or [Loggers] will continue processing the event, if `FALSE`
49 #' the event will be discarded.
50 filter = NULL
51 )
52 )
53
54
55
56
57 # FilterInject ------------------------------------------------------------
58
59 #' Inject values into all events processed by a Logger/Appender
60 #'
61 #' @description Inject arbitrary values into all [LogEvents][LogEvent] processed
62 #' by a Logger/Appender. It is recommended to use filters that modify LogEvents
63 #' only with Loggers, but they will also work with Appenders.
64 #'
65 #' @export
66 #' @examples
67 #' lg <- get_logger("test")
68 #'
69 #' analyse <- function(){
70 #' lg$add_filter(FilterInject$new(type = "analysis"), "inject")
71 #' on.exit(lg$remove_filter("inject"))
72 #' lg$error("an error with forced custom 'type'-field")
73 #' }
74 #'
75 #' analyse()
76 #' lg$error("an normal error")
77 #' lg$config(NULL) # reset config
78 FilterInject <- R6::R6Class(
79 "FilterInject",
80 inherit = EventFilter,
81 public = list(
82
83 #' @description Initialize a new FilterInject
84 #' @param ...,.list any number of named \R objects that will be injected as
85 #' custom fields into all [LogEvents][LogEvent] processed by the
86 #' Appender/Logger that this filter is attached to. See also
87 #' [with_log_value()].
88 initialize = function(..., .list = list()){
89 vals <- list(...)
90 assert(!is.null(names(vals)) && is_equal_length(names(vals)), vals)
91 if (length(.list) > 0){
92 assert(!is.null(names(.list)) && is_equal_length(names(.list)), .list)
93 }
94 vals <- c(vals, .list)
95 assert(all_are_distinct(names(vals)))
96 self[["values"]] <- vals
97
98 self$filter <- function(event){
99 vals <- get("values", envir = self)
100 for (i in seq_along(vals)){
101 event[[names(vals)[[i]] ]] <- vals[[i]]
102 }
103 TRUE
104 }
105 },
106
107 #' @field values a named `list` of values to be injected into each
108 #' [LogEvent] processed by this filter
109 values = NULL
110 )
111 )
112
113
114
115
116 # FilterForceLevel --------------------------------------------------------
117
118 #' Override the log level of all events processed by a Logger/Appender
119 #'
120 #' @description Overrides the log level of the Appender/Logger that this filter
121 #' is attached to to with `level`. See also [with_log_level()]. It is
122 #' recommended to use filters that modify LogEvents only with Loggers, but
123 #' they will also work with Appenders.
124 #'
125 #' @export
126 #' @examples
127 #' lg <- get_logger("test")
128 #'
129 #' analyse <- function(){
130 #' lg$add_filter(FilterForceLevel$new("info"), "force")
131 #' on.exit(lg$remove_filter("force"))
132 #' lg$error("an error with forced log level INFO")
133 #' }
134 #'
135 #' analyse()
136 #' lg$error("an normal error")
137 #' lg$config(NULL) # reset config
138 FilterForceLevel <- R6::R6Class(
139 "FilterForceLevel",
140 inherit = EventFilter,
141 public = list(
142
143 #' @description Initialize a new FilterForceLevel
144 #' @param level an `integer` or `character` [log level][log_level]
145 initialize = function(level){
146 self[["level"]] <- standardize_log_level(level)
147
148 self[["filter"]] <- function(event){
149 event[["level"]] <- get("level", self)
150 TRUE
151 }
152 },
153
154 #' @field level an `integer` [log level][log_level] used to override the log
155 #' levels of each [LogEvent] processed by this filter.
156 level = NULL
157 )
158 )
159
160
161
162
163 # utils -------------------------------------------------------------------
164
165 #' @description `.obj()` is a special function that can only be used within the
166 #' `$filter()` methods of [EventFilters][EventFilter]. It returns the [Logger]
167 #' or [Appender] that the EventFilter is attached to.
168 #'
169 #' @rdname EventFilter
170 #' @export
171 #' @examples
172 #' lg <- get_logger("test")
173 #' f <- function(event) {
174 #' cat("via event$.logger:", event$.logger$threshold, "\n") # works for loggers only
175 #' cat("via .obj(): ",.obj()$threshold, "\n") # works for loggers and appenders
176 #' TRUE
177 #' }
178 #' lg$add_filter(f)
179 #' lg$fatal("test")
180 #' lg$config(NULL)
181 .obj <- function(){
182 get("self", parent.env(parent.frame(2)))
183 }
184
185
186
187
188 #' Check if an R Object is a Filter
189 #'
190 #' @description Returns `TRUE` for any \R object that can be used as a Filter
191 #' for [Loggers] or, [Appenders]:
192 #' * a `function` with the single argument `event`;
193 #' * an [EventFilter] [R6::R6] object; or
194 #' * any object with a `$filter(event)` method.
195 #'
196 #' **Note:** A Filter **must** return a scalar `TRUE` or `FALSE`, but this
197 #' property cannot be checked by [is_filter()].
198 #'
199 #' @param x any \R Object
200 #' @seealso [EventFilter], [Filterable]
201 #' @return `TRUE` or `FALSE`
202 #'
203 #' @export
204 is_filter <- function(
205 x
206 ){
207 if (is.function(x)){
208 identical(names(formals(x)), "event")
209 } else {
210 # the extra is.function is to prevent infinite recursions
211 "filter" %in% names(x) &&
212 is.function(x[["filter"]]) &&
213 identical(names(formals(x[["filter"]])), c("event"))
214 }
215 }
216
217
218
219
220 standardize_filters_list <- function(x){
221 if (is.null(x))
222 return(list())
223
224 if (is_filter(x))
225 return(list(x))
226
227 assert(
228 is.list(x),
229 "'filters' must be a list Filters or a single Filter (see ?is_filter)"
230 )
231
232 for (f in x)
233 assert_filter(f)
234
235 x
236 }
237
238
239
240
241 assert_filter <- function(x){
242 if (is_filter(x))
243 TRUE
244 else
245 stop(ObjectIsNoFilterError(paste0(
246 "`", deparse(substitute(x)), "` ",
247 "is not a function with the single argument `event` or an EventFilter, ",
248 "but ", string_repr(x), ". See ?is_filter."
249 )
250 ))
251 }
252
253
254
255
256 ObjectIsNoFilterError <- function(message = "Object is not an EventFilter. See ?is_filter."){
257 error(message, "ObjectIsNoFilterError")
258 }