Debian Codegraph @

R/LogEvent.R

raw
1 # LogEvent ----------------------------------------------------------------
2
3 #' LogEvents - The atomic unit of logging
4 #'
5 #' @description
6 #' A `LogEvent` is a single unit of data that should be logged. `LogEvents` are
7 #' usually created by a [Logger], and then processed by one more [Appenders].
8 #' They do not need to be instantiated manually except for testing and
9 #' experimentation; however, if you plan on writing your own Appenders or
10 #' Layouts you need to understand LogEvents.
11 #'
12 #' @seealso [as.data.frame.LogEvent()]
13 #' @family docs relevant for extending lgr
14 #' @aliases LogEvents
15 #' @examples
16 #' lg <- get_logger("test")
17 #' lg$error("foo bar")
18 #'
19 #' # The last LogEvent produced by a Logger is stored in its `last_event` field
20 #' lg$last_event # formatted console output
21 #' lg$last_event$values # values stored in the event
22 #'
23 #' # Also contains the Logger that created it as .logger
24 #' lg$last_event$logger
25 #' # equivalent to
26 #' lg$last_event$.logger$name
27 #'
28 #' # This is really a reference to the complete Logger, so the following is
29 #' # possible (though nonsensical)
30 #' lg$last_event$.logger$last_event$msg
31 #' identical(lg, lg$last_event$.logger)
32 #' lg$config(NULL) # reset logger config
33 #' @export
34 LogEvent <- R6::R6Class(
35 "LogEvent",
36 lock_objects = FALSE,
37 public = list(
38
39 #' @description
40 #' The arguments to `LogEvent$new()` directly translate to the fields stored
41 #' in the `LogEvent`. Usually these values will be scalars, but (except for
42 #' `"logger"`) they can also be vectors if they are all of the same length (or
43 #' scalars that will be recycled). In this case the event will be treated by
44 #' the [Appenders] and [Layouts] as if several separate events.
45 #'
46 #' @param ... All named arguments in `...` will be added to the LogEvent
47 #' as **custom fields**. You can store arbitrary \R objects in LogEvents
48 #' this way, but not all Appenders will support them. See [AppenderJson] for
49 #' @param logger,level,timestamp,caller,msg see **Public fields**.
50 initialize = function(
51 logger,
52 level = 400,
53 timestamp = Sys.time(),
54 caller = NA,
55 msg = NA,
56 rawMsg = msg,
57 ...
58 ){
59 assert(inherits(logger, "Logger"), "Logger must be a <Logger> object, not a ", class_fmt(logger))
60
61 # assign has less overhead than [[ and event creation needs to be as fast
62 # as possible
63 assign(".logger", logger, self)
64 assign("level", level, self)
65 assign("timestamp", timestamp, self)
66 assign("caller", caller, self)
67 assign("msg", msg, self)
68 assign("rawMsg", rawMsg, self)
69
70 # custom values
71 if (!missing(...)){
72 dots <- list(...)
73 assert(identical(length(names(dots)), length(dots)))
74 # the rev() ensures that the values get added int eh same order as
75 # the user entered them
76 for (nm in rev(names(dots))){
77 assign(nm, dots[[nm]], self)
78 }
79 }
80 },
81
82 #' @field level `integer`. The [log_level] / priority of the LogEvent. Use the
83 #' active binding `level_name` to get the `character` representation
84 #' instead.
85 level = NULL,
86
87 #' @field timestamp [`POSIXct`][base::POSIXct]. The time when then the
88 #' LogEvent was created.
89 timestamp = NULL,
90
91 #' @field caller `character`. The name of the calling function.
92 caller = NULL,
93
94 #' @field msg `character`. The log message.
95 msg = NULL,
96
97 #' @field .logger [Logger]. A reference to the Logger that created the
98 #' event (equivalent to `get_logger(event$logger)`).
99 .logger = NULL,
100
101 #' @field rawMsg `character`. The raw log message without string
102 #' interpolation.
103 rawMsg = NULL
104 ),
105
106 active = list(
107
108 #' @field values `list`. All values stored in the `LogEvent`, including
109 #' all *custom fields*, but not including `event$.logger`.
110 values = function(){
111 fixed_vals <- c("level", "timestamp", "logger", "caller", "msg", "rawMsg")
112 custom_vals <- setdiff(
113 names(get(".__enclos_env__", self)[["self"]]),
114 c(".__enclos_env__", "level_name", "initialize", "clone", "values", ".logger")
115 )
116 valnames <- union(fixed_vals, custom_vals) # to enforce order of fixed_vals
117 mget(valnames, envir = self)
118 },
119
120 #' @field level_name `character`. The [log_level] / priority of the LogEvent labelled
121 #' according to `getOption("lgr.log_levels")`
122 level_name = function(){
123 label_levels(get("level", envir = self))
124 },
125
126 #' @field logger `character` scalar. The name of the Logger that
127 #' created this event, equivalent to `event$.logger$name`)
128 logger = function(){
129 get("name", envir = get(".logger", envir = self))
130 }
131 )
132 )
133
134
135
136
137 # coercion ---------------------------------------------------
138
139 #' Coerce objects to LogEvent
140 #'
141 #' Smartly coerce \R objects that look like LogEvents to LogEvents. Mainly
142 #' useful for developing Appenders.
143 #'
144 #' **Note**: `as_LogEvent.data.frame()` only supports single-row `data.frames`
145 #'
146 #' @param x any supported \R object
147 #' @param ... currently ignored
148 #'
149 #' @return a [LogEvent]
150 #' @family docs relevant for extending lgr
151 #' @export
152 as_LogEvent <- function(x, ...){
153 UseMethod("as_LogEvent")
154 }
155
156
157
158
159 #' @rdname as_LogEvent
160 #' @export
161 as_LogEvent.list <- function(x, ...){
162
163 if (is.null(x[["logger"]])){
164 x[["logger"]] <- get_logger()
165 } else if (is.character(x[["logger"]])){
166 x[["logger"]] <- get_logger(x[["logger"]])
167 }
168
169 # smartly rename timestamp fields from ElasticSearch/Logstash
170 if (!"timestamp" %in% names(x) && "@timestamp" %in% names(x)){
171 names(x)[names(x) == "@timestamp"] <- "timestamp"
172 }
173
174 x[["level"]] <- standardize_log_level(x[["level"]])
175
176 do.call(LogEvent$new, x)
177 }
178
179
180
181
182 #' @rdname as_LogEvent
183 #' @export
184 as_LogEvent.data.frame <- function(
185 x,
186 ...
187 ){
188 assert(
189 identical(nrow(x), 1L),
190 "`as_LogEvent()` only supports single-row data.frames. Try `as_event_list()` instead"
191 )
192
193 as_LogEvent(unclass(x))
194 }
195
196
197
198
199 #' Coerce LogEvents to Data Frames
200 #'
201 #' Coerce LogEvents to `data.frames`, [`data.tables`][data.table::data.table],
202 #' or [`tibbles`][tibble::tibble].
203 #'
204 #' @inheritParams base::as.data.frame
205 #' @param stringsAsFactors `logical` scalar: should `character` vectors be
206 #' converted to factors? Defaults to `FALSE` (as opposed to
207 #' [base::as.data.frame()]) and is only included for compatibility.
208 #' @param ... passed on to `data.frame()`
209 #' @param optional currently ignored and only included for compatibility.
210 #' @param box_if a `function` that returns `TRUE` or `FALSE` to determine
211 #' which values are to be boxed (i.e. placed as single elements in a list
212 #' column). See example
213 #' @param cols_expand `character` vector. Columns to *not* box (even if
214 #' `box_if()` returns `TRUE`). Vectors in these columns will result in multiple
215 #' rows in the result (rather than a single list-column row). This defaults to
216 #' `"msg"` for vectorized logging over the log message.
217 #' @export
218 #' @seealso [data.table::data.table], [tibble::tibble]
219 #'
220 #' @examples
221 #' lg <- get_logger("test")
222 #' lg$info("lorem ipsum")
223 #' as.data.frame(lg$last_event)
224 #'
225 #' lg$info("LogEvents can store any custom log values", df = iris)
226 #' as.data.frame(lg$last_event)
227 #' head(as.data.frame(lg$last_event)$df[[1]])
228 #'
229 #' # how boxing works
230 #'
231 #' # by default non-scalars are boxed
232 #' lg$info("letters", letters = letters)
233 #' as.data.frame(lg$last_event)
234 #'
235 #' # this behaviour can be modified by supplying a custom boxing function
236 #' as.data.frame(lg$last_event, box_if = function(.) FALSE)
237 #' as.data.frame(lg$last_event, cols_expand = "letters")
238 #'
239 #' # The `msg` argument of a log event is always vectorized
240 #' lg$info(c("a vectorized", "log message"))
241 #' as.data.frame(lg$last_event)
242 #'
243 #' lg$config(NULL)
244 as.data.frame.LogEvent <- function(
245 x,
246 row.names = NULL,
247 optional = FALSE,
248 stringsAsFactors = FALSE,
249 ...,
250 box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
251 cols_expand = NULL
252 ){
253 assert(is.null(cols_expand) || is.character(cols_expand))
254 boxer <- function(.) I(list(.))
255 values <- do_box_if(x$values, box_if, except = cols_expand, boxer = boxer)
256 msg_len <- length(x[["msg"]])
257 cols_expand <- c("msg", cols_expand)
258 # as.data.frame requires manual recycling
259
260 if (msg_len > 1){
261 for (i in seq_along(values)){
262 if (identical(length(values[[i]]), 1L))
263 values[[i]] <- rep(values[[i]], msg_len)
264 }
265 values <- do_box_if(values, box_if, except = cols_expand, boxer = I)
266 }
267
268 do.call(
269 data.frame,
270 c(values,
271 stringsAsFactors = stringsAsFactors,
272 row.names = row.names,
273 ...
274 )
275 )
276 }
277
278
279
280 #' @rdname as.data.frame.LogEvent
281 as.data.table.LogEvent <- function(
282 x,
283 ...,
284 box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
285 cols_expand = "msg"
286 ){
287 values <- do_box_if(x$values, box_if, cols_expand)
288 data.table::as.data.table(values)
289 }
290
291
292
293
294 #' @rdname as.data.frame.LogEvent
295 as_tibble.LogEvent <- function(
296 x,
297 ...,
298 box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
299 cols_expand = "msg"
300 ){
301 values <- do_box_if(x$values, box_if, cols_expand)
302 tibble::as_tibble(values)
303 }
304
305
306
307
308 # printing ---------------------------------------------------
309
310 #' Print or Format Logging Data
311 #'
312 #' @param x a [LogEvent]
313 #' @param timestamp_fmt see [format.POSIXct()]
314 #' @param fmt A `character` scalar that may contain any of the tokens listed
315 #' bellow in the section Format Tokens.
316 #' @param colors A `list` of `functions` that will be used to color the
317 #' log levels (likely from [crayon::crayon]).
318 #' @inheritParams standardize_threshold
319 #' @param pad_levels `right`, `left` or `NULL`. Whether or not to pad the log
320 #' level names to the same width on the left or right side, or not at all.
321 #' @param excluded_fields a `character` vector of fields to exclude from `%j` and
322 #' `%f`
323 #' @param ... ignored
324 #'
325 #' @section Format Tokens:
326 #' \describe{
327 #' \item{`%t`}{The timestamp of the message, formatted according to
328 #' `timestamp_fmt`)}
329 #' \item{`%l`}{the log level, lowercase `character` representation}
330 #' \item{`%L`}{the log level, uppercase `character` representation}
331 #' \item{`%k`}{the log level, first letter of lowercase `character` representation}
332 #' \item{`%K`}{the log level, first letter of uppercase `character` representation}
333 #' \item{`%n`}{the log level, `integer` representation}
334 #' \item{`%g`}{the name of the logger}
335 #' \item{`%p`}{the PID (process ID). Useful when logging code that uses
336 #' multiple threads.}
337 #' \item{`%c`}{the calling function}
338 #' \item{`%m`}{the log message}
339 #' \item{`%r`}{the raw log message (without string interpolation)}
340 #' \item{`%f`}{all custom fields of `x` in a pseudo-JSON like format that is
341 #' optimized for human readability and console output}
342 #' \item{`%j`}{all custom fields of `x` in proper JSON. This requires that you
343 #' have **jsonlite** installed and does not support colors as opposed to
344 #' `%f`
345 #' }
346 #' }
347 #'
348 #' @return `x` for `print()` and a `character` scalar for `format()`
349 #' @export
350 #'
351 #' @examples
352 #' # standard fields can be printed using special tokens
353 #' x <- LogEvent$new(
354 #' level = 300, msg = "a test event", caller = "testfun()", logger = lgr
355 #' )
356 #' print(x)
357 #' print(x, fmt = c("%t (%p) %c: %n - %m"))
358 #' print(x, colors = NULL)
359 #'
360 #' # custom values
361 #' y <- LogEvent$new(
362 #' level = 300, msg = "a gps track", logger = lgr,
363 #' waypoints = 10, location = "Austria"
364 #' )
365 #'
366 #' # default output with %f
367 #' print(y)
368 #'
369 #' # proper JSON output with %j
370 #' if (requireNamespace("jsonlite")){
371 #' print(y, fmt = "%L [%t] %m %j")
372 #' }
373 #'
374 print.LogEvent <- function(
375 x,
376 fmt = "%L [%t] %m %f",
377 timestamp_fmt = "%Y-%m-%d %H:%M:%S",
378 colors = getOption("lgr.colors"),
379 log_levels = getOption("lgr.log_levels"),
380 pad_levels = "right",
381 excluded_fields = NULL,
382 ...
383 ){
384 cat(format(
385 x,
386 fmt = fmt,
387 timestamp_fmt = timestamp_fmt,
388 colors = colors,
389 log_levels = log_levels,
390 pad_levels = pad_levels,
391 excluded_fields = excluded_fields
392 ), sep = "\n")
393 invisible(x)
394 }
395
396
397
398
399 #' @rdname print.LogEvent
400 #' @export
401 format.LogEvent <- function(
402 x,
403 fmt = "%L [%t] %m %f",
404 timestamp_fmt = "%Y-%m-%d %H:%M:%S",
405 colors = NULL,
406 log_levels = getOption("lgr.log_levels"),
407 pad_levels = "right",
408 excluded_fields = NULL,
409 ...
410 ){
411 stopifnot(
412 is_scalar_character(fmt),
413 is_scalar_character(timestamp_fmt),
414 is_scalar_character(pad_levels) || is.null(pad_levels)
415 )
416
417 # init
418 lvls <- label_levels(x$level, log_levels = log_levels)
419 lvls[is.na(lvls)] <- x$level[is.na(lvls)]
420
421 if (!is.null(pad_levels)){
422 nchar_max <- max(nchar(names(log_levels)))
423 diff <- nchar_max - nchar(lvls)
424 pad <- vapply(diff, function(i) paste(rep.int(" ", i), collapse = ""), character(1))
425
426 if (pad_levels == "right"){
427 lvls <- paste0(lvls, pad)
428 } else {
429 lvls <- paste0(pad, lvls)
430 }
431
432 } else {
433 lvls <- x$level
434 }
435
436 # tokenize
437 tokens <- tokenize_format(
438 fmt,
439 valid_tokens = paste0(
440 "%",
441 c("t", "p", "c", "m", "r", "l", "L", "n", "f", "j", "k", "K", "g"))
442 )
443
444 # format
445 len <- length(tokens)
446 res <- vector("list", length(tokens))
447
448 for(i in seq_len(len)){
449 res[[i]] <- switch(
450 tokens[[i]],
451 "%n" = colorize_levels(x$level, colors),
452 "%l" = colorize_levels(lvls, colors),
453 "%L" = colorize_levels(toupper(lvls), colors),
454 "%k" = colorize_levels(lvls, colors, transform = function(.) strtrim(., 1)),
455 "%K" = colorize_levels(lvls, colors, transform = function(.) toupper(strtrim(., 1))),
456 "%t" = format(get("timestamp", envir = x), format = timestamp_fmt),
457 "%m" = get("msg", envir = x),
458 "%r" = get("rawMsg", envir = x),
459 "%c" = get("caller", envir = x),
460 "%g" = get("logger", envir = x),
461 "%p" = Sys.getpid(),
462 "%f" = format_custom_fields(get_custom_fields(x, excluded_fields), color = length(colors)),
463 "%j" = format_custom_fields_json(get_custom_fields(x, excluded_fields)),
464 tokens[[i]]
465 )
466 }
467
468 sub("[ \t\r]*$", "", do.call(paste0, res))
469 }
470
471
472
473 format_custom_fields_json <- function(x){
474 if (length(x)){
475 jsonlite::toJSON(x, auto_unbox = TRUE)
476 } else {
477 ""
478 }
479 }
480
481
482
483 #' Convert a LogEvent to a character string
484 #'
485 #' @param x a [LogEvent]
486 #' @param ... ignored
487 #'
488 #' @return a `character` scalar
489 #' @export
490 #'
491 #' @examples
492 #' toString(LogEvent$new(logger = lgr::lgr))
493 toString.LogEvent <- function(x, ...){
494 paste(
495 paste0("$", names(x$values), ": ", vapply(x$values, function(.) string_repr(.), character(1L))),
496 collapse = ", "
497 )
498 }
499
500
501
502
503 # utils -------------------------------------------------------------------
504
505 do_box_if <- function(x, predicate, except, boxer = list){
506 sel <-
507 vapply(x, predicate, TRUE, USE.NAMES = FALSE)
508
509 if (length(except)){
510 sel[(names(x) %in% except)] <- FALSE
511 }
512
513 for (i in seq_along(x))
514 if (sel[[i]])
515 x[[i]] <- boxer(x[[i]])
516
517 x
518 }
519
520
521
522
523 get_custom_fields <- function(x, excluded_fields = NULL){
524 x$values[!names(x$values) %in% c(DEFAULT_FIELDS, excluded_fields)]
525 }
526
527
528
529
530 format_custom_fields <- function(
531 x,
532 color = TRUE
533 ){
534 if (!length(x)) return("")
535
536 max_len <- floor(max(512 / length(x) - sum(nchar(names(x))), 16))
537
538 braces <- c("{", "}")
539 brackets <- c("[", "]")
540 colon <- ": "
541 comma <- ", "
542 dots <- ".."
543
544 if (!color){
545 style_subtle <- identity
546 style_accent <- identity
547 } else {
548 braces <- style_subtle(braces)
549 colon <- style_subtle(colon)
550 comma <- style_subtle(comma)
551 }
552
553 res <- lapply(
554 x,
555 string_repr,
556 width = max_len
557 )
558
559 paste0(
560 braces[[1L]],
561 paste(
562 style_accent(names(res)), colon, res,
563 sep = "",
564 collapse = comma
565 ),
566 braces[[2L]]
567 )
568 }
569
570
571
572
573 tokenize_format <- function(
574 x,
575 valid_tokens = NULL
576 ){
577 pos <- unlist(gregexpr("%.", x))
578
579 if (identical(pos, -1L))
580 return(x)
581
582 pos <- sort(unique(c(1L, pos, pos + 2L, nchar(x) + 1L)))
583 res <- vector("character", length(x))
584
585 for(i in seq_len(length(pos) - 1L)) {
586 res[[i]] <- substr(x, pos[[i]], pos[[i + 1L]] - 1L)
587 }
588
589 if (!is.null(valid_tokens)){
590 placeholders <- grep("%", res, value = TRUE, fixed = TRUE)
591 assert(
592 all(placeholders %in% valid_tokens),
593 "'format' contains unrecognised format specifications: ",
594 paste(sort(setdiff(placeholders, valid_tokens)), collapse = ", ")
595 )
596 }
597
598 res
599 }
600
601
602
603
604 # globals --------------------------------------------------------
605
606 DEFAULT_FIELDS <- c("level", "timestamp", "logger", "caller", "msg", "rawMsg")