Debian Codegraph @

R/Logger.R

raw
1 #' Loggers
2 #'
3 #' A Logger produces a [LogEvent] that contains a log message along with
4 #' metadata (timestamp, calling function, ...) and dispatches it to one or
5 #' more [Appenders] which are responsible for the output (console, file, ...)
6 #' of the event. **lgr** comes with a single pre-configured Logger called the
7 #' `root Logger` that can be accessed via `lgr$<...>`. Instantiation of new
8 #' Loggers is done with [get_logger()]. It is advisable to instantiate a
9 #' separate Logger with a descriptive name for each package/script in which
10 #' you use \pkg{lgr}.
11 #'
12 #' @name Logger
13 #' @aliases Loggers
14 #' @include Filterable.R
15 #' @include log_levels.R
16 #' @seealso [glue](https://glue.tidyverse.org/)
17 #' @examples
18 #' # lgr::lgr is the root logger that is always available
19 #' lgr$info("Today is a good day")
20 #' lgr$fatal("This is a serious error")
21 #'
22 #' # Loggers use sprintf() for string formatting by default
23 #' lgr$info("Today is %s", Sys.Date() )
24 #'
25 #' # If no unnamed `...` are present, msg is not passed through sprintf()
26 #' lgr$fatal("100% bad") # so this works
27 #' lgr$fatal("%s%% bad", 100) # if you use unnamed arguments, you must escape %
28 #'
29 #' # You can create new loggers with get_logger()
30 #' tf <- tempfile()
31 #' lg <- get_logger("mylogger")$set_appenders(AppenderFile$new(tf))
32 #'
33 #' # The new logger passes the log message on to the appenders of its parent
34 #' # logger, which is by default the root logger. This is why the following
35 #' # writes not only the file 'tf', but also to the console.
36 #' lg$fatal("blubb")
37 #' readLines(tf)
38 #'
39 #' # This logger's print() method depicts this relationship.
40 #' child <- get_logger("lg/child")
41 #' print(child)
42 #' print(child$name)
43 #'
44 #' # use formatting strings and custom fields
45 #' tf2 <- tempfile()
46 #' lg$add_appender(AppenderFile$new(tf2, layout = LayoutJson$new()))
47 #' lg$info("Not all %s support custom fields", "appenders", type = "test")
48 #' cat(readLines(tf), sep = "\n")
49 #' cat(readLines(tf2), sep = "\n")
50 #'
51 #' # cleanup
52 #' unlink(c(tf, tf2))
53 #' lg$config(NULL) # reset logger config
54 #'
55 #' # LoggerGlue
56 #' # You can also create a new logger that uses the awesome glue library for
57 #' # string formatting instead of sprintf
58 #'
59 #' if (requireNamespace("glue")){
60 #'
61 #' lg <- get_logger_glue("glue")
62 #' lg$fatal("blah ", "fizz is set to: {fizz}", foo = "bar", fizz = "buzz")
63 #' # prevent creation of custom fields with prefixing a dot
64 #' lg$fatal("blah ", "fizz is set to: {.fizz}", foo = "bar", .fizz = "buzz")
65 #'
66 #' #' # completely reset 'glue' to an unconfigured vanilla Logger
67 #' get_logger("glue", reset = TRUE)
68 #'
69 #' }
70 #'
71 #'
72 #' # Configuring a Logger
73 #' lg <- get_logger("test")
74 #' lg$config(NULL) # resets logger to unconfigured state
75 #'
76 #' # With setters
77 #' lg$
78 #' set_threshold("error")$
79 #' set_propagate(FALSE)$
80 #' set_appenders(AppenderConsole$new(threshold = "info"))
81 #'
82 #' lg$config(NULL)
83 #'
84 #' # With a list
85 #' lg$config(list(
86 #' threshold = "error",
87 #' propagate = FALSE,
88 #' appenders = list(AppenderConsole$new(threshold = "info"))
89 #' ))
90 #'
91 #' lg$config(NULL) # resets logger to unconfigured state
92 #'
93 #' # Via YAML
94 #' cfg <- "
95 #' Logger:
96 #' threshold: error
97 #' propagate: false
98 #' appenders:
99 #' AppenderConsole:
100 #' threshold: info
101 #' "
102 #'
103 #' lg$config(cfg)
104 #' lg$config(NULL)
105 NULL
106
107
108 # Logger ------------------------------------------------------------------
109
110 #' @export
111 Logger <- R6::R6Class(
112 "Logger",
113 inherit = Filterable,
114 cloneable = FALSE,
115
116 # public --------------------------------------------------------------------
117 public = list(
118 # +- methods --------------------------------------------------------------
119
120 #' @description
121 #'
122 #' **Loggers should never be instantiated directly with `Logger$new()`** but
123 #' rather via [`get_logger("name")`][get_logger]. This way new Loggers are
124 #' registered in a global namespace which ensures uniqueness and
125 #' facilitates inheritance between Loggers. If `"name"` does not exist, a
126 #' new Logger with that name will be created, otherwise the function returns
127 #' a Reference to the existing Logger.
128 #'
129 #' `name` is potentially a `"/"` separated hierarchical value like
130 #' `foo/bar/baz`. Loggers further down the hierarchy are descendants of the
131 #' loggers above and (by default) inherit `threshold` and `Appenders` from
132 #' their ancestors.
133 #'
134 #' @note
135 #' If you are a package developer you should define a new Logger for each
136 #' package, but you do not need to configure it. The user of the package
137 #' should decide how and where to output logging, usually by configuring the
138 #' root Logger (new Appenders added/removed, Layouts modified, etc...).
139 #'
140 #' @param name,appenders,threshold,filters,exception_handler,propagate
141 #' See section Active bindings.
142 #'
143 #' @seealso [get_logger()]
144 #'
145 initialize = function(
146 name = "(unnamed logger)",
147 appenders = list(),
148 threshold = NULL,
149 filters = list(),
150 exception_handler = default_exception_handler,
151 propagate = TRUE,
152 replace_empty = "<NULL>"
153 ){
154 # fields
155 # threshold must be set *after* the logging functions have been initalized
156 if (identical(name, "(unnamed logger)")){
157 warning(
158 "When creating a new Logger, you should assign it a unique `name`. ",
159 "Please see ?Logger for more infos.", call. = FALSE
160 )
161 }
162
163 private$set_name(name)
164 private$.last_event <- LogEvent$new(self)
165
166 self$set_threshold(threshold)
167 self$set_appenders(appenders)
168 self$set_propagate(propagate)
169 self$set_filters(filters)
170 self$set_exception_handler(exception_handler)
171 self$set_replace_empty(replace_empty)
172
173 invisible(self)
174 },
175
176
177 #' @description Log an event.
178 #'
179 #' If `level` passes the Logger's `threshold` a new [LogEvent] with `level`,
180 #' `msg`, `timestamp` and `caller` is created. If the new LogEvent also
181 #' passes the Loggers [Filters][EventFilter], it is be dispatched to the
182 #' relevant [Appenders].
183 #'
184 #' @param level a `character` or `integer` scalar. See [log_levels].
185 #'
186 #' @param msg `character`. A log message. If unnamed arguments are supplied
187 #' in `...`, `msg` is passed on to [base::sprintf()] (which means `"%"` have
188 #' to be escaped), otherwise `msg` is left as-is.
189 #'
190 #' @param ... *unnamed* arguments in `...` must be `character` scalars and
191 #' are passed to [base::sprintf()]. *Named* arguments must have unique names
192 #' but can be arbitrary \R objects that are passed to [`LogEvent$new()`][LogEvent] and
193 #' will be turned into custom fields.
194 #'
195 #' @param timestamp [POSIXct]. Timestamp of the event.
196 #' @param caller a `character` scalar. The name of the calling function.
197 log = function(
198 level,
199 msg,
200 ...,
201 timestamp = Sys.time(),
202 caller = get_caller(-7)
203 ){
204 if (identical(get("threshold", envir = self), 0L)) return(invisible())
205 LOG_CALL <- sys.call(-1L) # for error reporting
206
207 tryCatch({
208 # preconditions
209 level <- standardize_log_levels(level)
210 assert(
211 identical(length(unique(level)), 1L),
212 "Can only utilize vectorized logging if log level is the same for all entries"
213 )
214
215 # Check if LogEvent should be created
216 if (
217 isTRUE(level[[1]] > get("threshold", envir = self)) ||
218 isTRUE(getOption("lgr.logging_suspended"))
219 ){
220 return(invisible(msg))
221 }
222
223 # init
224 if (inherits(msg, "condition")){
225 msg <- conditionMessage(msg)
226 } else {
227 msg <- as.character(msg)
228 }
229
230 force(caller)
231 rawMsg <- msg
232
233 if (missing(...)){
234 vals <- list(
235 logger = self,
236 level = level,
237 timestamp = timestamp,
238 caller = caller,
239 msg = msg,
240 rawMsg = rawMsg
241 )
242 } else {
243 dots <- list(...)
244
245 if (is.null(names(dots))){
246 dots <- replace_empty(dots, get("replace_empty", self))
247
248 msg <- do.call(sprintf, args = c(list(msg), dots))
249 vals <- list(
250 logger = self,
251 level = level,
252 timestamp = timestamp,
253 caller = caller,
254 msg = msg,
255 rawMsg = rawMsg
256 )
257 } else {
258 not_named <- vapply(names(dots), is_blank, TRUE, USE.NAMES = FALSE)
259 unnamed_dots <- dots[not_named]
260 unnamed_dots <- replace_empty(unnamed_dots, get("replace_empty", self))
261
262 if (any(not_named)){
263 msg <- do.call(sprintf, c(list(msg), unnamed_dots))
264 }
265
266 vals <- c(
267 list(
268 logger = self,
269 level = level,
270 timestamp = timestamp,
271 caller = caller,
272 msg = msg,
273 rawMsg = rawMsg
274 ),
275 dots[!not_named]
276 )
277 }
278 }
279
280 # This code looks really weird, but it really is just replacing all
281 # instances of [[ with get() for minimal overhead. We want event
282 # dispatch to be as quick as possible.
283 event <- do.call(get("new", envir = LogEvent), vals)
284 assign(".last_event", event, private)
285
286 if (get("filter", envir = self)(event)){
287 for (app in unlist(mget(c("appenders", "inherited_appenders"), self), recursive = FALSE)){
288 tryCatch({
289 app_thresh <- get("threshold", envir = app)
290 if (
291 (is.na(app_thresh) || get("level", envir = event) <= app_thresh) &&
292 get("filter", envir = app)(event)
293 ){
294 get("append", envir = app)(event)
295 }
296 }, error = function(e) {
297 e$call <- LOG_CALL
298 e$appender <- app
299 e$logger <- self
300 get("handle_exception", envir = self)(e)
301 }
302 )
303 }
304 }
305
306 invisible(msg)
307 },
308 error = function(e) {
309 e$logger <- self
310 e$call <- LOG_CALL
311 get("handle_exception", envir = self)(e)
312 }
313 )
314 },
315
316 #' @description Log an Event fatal priority
317 #' @param msg,...,caller see `$log()`
318 fatal = function(msg, ..., caller = get_caller(-8L)){
319 if (isTRUE(get("threshold", envir = self) < 100L))
320 return(invisible())
321
322 get("log", envir = self)(
323 msg = msg,
324 caller = caller,
325 level = 100L,
326 timestamp = Sys.time(),
327 ...
328 )
329 },
330
331
332 #' @description Log an Event error priority
333 #' @param msg,...,caller see `$log()`
334 error = function(msg, ..., caller = get_caller(-8L)){
335 if (isTRUE(get("threshold", envir = self) < 200L))
336 return(invisible())
337
338 get("log", envir = self)(
339 msg = msg,
340 caller = caller,
341 level = 200L,
342 timestamp = Sys.time(),
343 ...
344 )
345 },
346
347
348 #' @description Log an Event warn priority
349 #' @param msg,...,caller see `$log()`
350 warn = function(msg, ..., caller = get_caller(-8L)){
351 if (isTRUE(get("threshold", envir = self) < 300L))
352 return(invisible())
353
354 get("log", envir = self)(
355 msg = msg,
356 caller = caller,
357 level = 300L,
358 timestamp = Sys.time(),
359 ...
360 )
361 },
362
363
364 #' @description Log an Event info priority
365 #' @param msg,...,caller see `$log()`
366 info = function(msg, ..., caller = get_caller(-8L)){
367 if (isTRUE(get("threshold", envir = self) < 400L))
368 return(invisible())
369
370 get("log", envir = self)(
371 msg = msg,
372 caller = caller,
373 level = 400L,
374 timestamp = Sys.time(),
375 ...
376 )
377 },
378
379
380 #' @description Log an Event debug priority
381 #' @param msg,...,caller see `$log()`
382 debug = function(msg, ..., caller = get_caller(-8L)){
383 if (isTRUE(get("threshold", envir = self) < 500L))
384 return(invisible())
385
386 get("log", envir = self)(
387 msg = msg,
388 caller = caller,
389 level = 500L,
390 timestamp = Sys.time(),
391 ...
392 )
393 },
394
395
396 #' @description Log an Event trace priority
397 #' @param msg,...,caller see `$log()`
398 trace = function(msg, ..., caller = get_caller(-8L)){
399 if (isTRUE(get("threshold", envir = self) < 600L))
400 return(invisible())
401
402 get("log", envir = self)(
403 msg = msg,
404 caller = caller,
405 level = 600L,
406 timestamp = Sys.time(),
407 ...
408 )
409 },
410
411
412 #' @description
413 #' `list_log()` is a shortcut for `do.call(Logger$log, x)`.
414 #' See \url{https://github.com/s-fleck/joblog} for an R package that
415 #' leverages this feature to create custom log event types for tracking
416 #' the status of cron jobs.
417 #'
418 #' @param x a named `list` that must at least contain the named elements
419 #' `level` and `timestamp`
420 #'
421 #' @examples
422 #' lg <- get_logger("test")
423 #' lg$list_log(list(level = 400, msg = "example"))
424 list_log = function(x){
425 do.call(self$log, x)
426 },
427
428
429
430 #' @description Load a Logger configuration.
431 #'
432 #' @param cfg
433 #' * a special `list` object with any or all of the the following elements:
434 #' `appenders`, `threshold`, `filters`, `propagate`, `exception_handler`,
435 #'
436 #' * the path to a `YAML`/`JSON` config file,
437 #'
438 #' * a `character` scalar containing `YAML/JSON`,
439 #'
440 #' * `NULL` (to reset the logger config to the default/unconfigured state)
441 #'
442 #' @param file,text,list can be used as an alternative to
443 #' `cfg` that enforces that the supplied argument is of the specified
444 #' type. See [logger_config] for details.
445 config = function(
446 cfg,
447 file,
448 text,
449 list
450 ){
451 assert(
452 missing(cfg) + missing(file) + missing(text) + missing(list) >= 3,
453 "You can only specify one of `cfg`, `file`, `text` and `list`."
454 )
455
456 if (!missing(cfg)){
457 if (is.list(cfg)){
458 cfg <- parse_logger_config(cfg)
459 } else {
460 cfg <- as_logger_config(cfg)
461 }
462
463 } else if (!missing(file)){
464 assert(
465 is_scalar_character(file) && !grepl("\n", file) && file.exists(file),
466 "`file` is not a valid path to a readable file"
467 )
468 cfg <- as_logger_config(file)
469
470 } else if (!missing(text)){
471 assert(
472 is_scalar_character(text) && grepl("\n", text),
473 "`text` must be a character scalar containing valid YAML"
474 )
475 cfg <- as_logger_config(text)
476
477 } else if (!missing(list)){
478 cfg <- parse_logger_config(list)
479
480 } else {
481 cfg <- as_logger_config()
482 }
483
484 if (is_logger_config(cfg)){
485 cfg <- parse_logger_config(cfg)
486 }
487
488 assert(is_parsed_logger_config(cfg))
489 self$set_threshold(cfg$threshold)
490 self$set_appenders(cfg$appenders)
491 self$set_propagate(cfg$propagate)
492 self$set_filters(cfg$filters)
493 self$set_exception_handler(cfg$exception_handler)
494
495 self
496 },
497
498
499 #' @description Add an Appender to the Logger
500 #'
501 #' @param appender a single [Appender]
502 #' @param name a `character` scalar. Optional but recommended.
503 #'
504 #' @examples
505 #' lg <- get_logger("test")
506 #' lg$add_appender(AppenderConsole$new(), name = "myconsole")
507 #' lg$appenders[[1]]
508 #' lg$appenders$myconsole
509 #' lg$remove_appender("myconsole")
510 #' lg$config(NULL) # reset config
511 add_appender = function(
512 appender,
513 name = NULL
514 ){
515 assert(inherits(appender, "Appender"))
516 private$.appenders[[length(private$.appenders) + 1L]] <- appender
517
518 if (!is.null(name))
519 names(private$.appenders)[length(private$.appenders)] <- name
520
521 invisible(self)
522 },
523
524
525 #' @param pos `integer` index or `character` name of the Appender(s) to
526 #' remove
527 #'
528 #' @description remove an appender
529 remove_appender = function(
530 pos
531 ){
532 if (is.numeric(pos)){
533 assert(
534 all(pos %in% seq_along(private$.appenders)),
535 "'pos' is out of range of the length of appenders (1:",
536 length(private$.appenders), ")"
537 )
538
539 pos <- as.integer(pos)
540 } else if (is.character(pos)) {
541 assert(
542 all(pos %in% names(private$.appenders)),
543 "'pos' is not names of appenders (",
544 paste(names(private$.appenders), collapse = ", "),
545 ")"
546 )
547 }
548
549 for (nm in pos){
550 private$.appenders[[nm]] <- NULL
551 }
552
553 invisible(self)
554 },
555
556
557 #' @description
558 #' To prevent errors in the logging logic from crashing the whole script,
559 #' Loggers pass errors they encounter to an exception handler. The default
560 #' behaviour is to demote errors to [warnings]. See also
561 #' `set_exception_handler()`.
562 #'
563 #' @param expr expression to be evaluated.
564 handle_exception = function(expr){
565 private$.exception_handler(expr)
566 },
567
568
569 # .. setters --------------------------------------------------------------
570
571 #' @description Set the exception handler of a logger
572 #'
573 #' @param fun a `function` with the single argument `e` (an error [condition])
574 #'
575 #' @examples
576 #' lgr$info(stop("this produces a warning instead of an error"))
577 set_exception_handler = function(fun){
578 assert(is.function(fun))
579 private$.exception_handler <- fun
580 invisible(self)
581 },
582
583
584 #' @description Should a Logger propagate events to the Appenders of its ancestors?
585 #' @param x `TRUE` or `FALSE`. Should [LogEvents] be passed on to the appenders
586 #' of the ancestral Loggers?
587 set_propagate = function(x){
588 assert(is_scalar_bool(x))
589 private$.propagate <- x
590 invisible(self)
591 },
592
593
594 #' @description Set the minimum log level of events that a Logger should process
595 #'
596 #' @param level `character` or `integer` scalar. The minimum
597 #' [log level][log_levels] that triggers this Logger
598 set_threshold = function(level){
599 if (!is.null(level))
600 level <- standardize_threshold(level)
601
602 private[[".threshold"]] <- level
603 invisible(self)
604 },
605
606
607 #' @description Set the Logger's Appenders
608 #'
609 #' @param x single [Appender] or a `list` thereof. Appenders control the
610 #' output of a Logger. Be aware that a Logger also inherits the Appenders
611 #' of its ancestors (see `vignette("lgr", package = "lgr")` for more info
612 #' about Logger inheritance).
613 set_appenders = function(x){
614 x <- standardize_appenders_list(x)
615 private[[".appenders"]] <- list()
616
617 for (i in seq_along(x))
618 self$add_appender(x[[i]], name = names(x)[[i]])
619
620 invisible(self)
621 },
622
623 #' @description Set the replacement for empty values (`NULL` or empty
624 #' vectors)
625 #'
626 #' @param x should be a `character` vector, but other types of values are
627 #' supported. use wisely.
628 set_replace_empty = function(x){
629 private[[".replace_empty"]] <- x
630
631 invisible(self)
632 },
633
634
635 #' @description Spawn a child Logger.
636 #' This is very similar to using [get_logger()], but
637 #' can be useful in some cases where Loggers are created programmatically
638 #'
639 #' @param name `character` vector. Name of the child logger
640 #' `get_logger("foo/bar")$spawn("baz")` is equivalent
641 #' to `get_logger("foo/bar/baz")`
642 spawn = function(name){
643 get_logger(c(private[[".name"]], name))
644 }
645 ),
646
647
648 # .. active bindings ---------------------------------------------------------
649 active = list(
650
651 #' @field name A `character` scalar. The unique name of each logger,
652 #' which also includes the names of its ancestors (separated by `/`).
653 name = function(){
654 paste(get(".name", envir = private), collapse = "/")
655 },
656
657
658 #' @field threshold `integer` scalar. The threshold of the `Logger`, or if it
659 #' `NULL` the threshold it inherits from its closest ancestor with a
660 #' non-`NULL` threshold
661 threshold = function() {
662 res <- get(".threshold", envir = private)
663 if (is.null(res)){
664 get("threshold", envir = get("parent", envir = self))
665 } else {
666 res
667 }
668 },
669
670
671 #' @field propagate A `TRUE` or `FALSE`. Should a Logger propagate events
672 #' to the Appenders of its ancestors?
673 propagate = function(){
674 get(".propagate", envir = private)
675 },
676
677
678 #' @field ancestry A named `logical` vector of containing the propagate value
679 #' of each Logger upper the inheritance tree. The names are the names of
680 #' the appenders. `ancestry` is an S3 class with a custom
681 #' `format()`/`print()` method, so if you want to use the plain logical
682 #' vector use `unclass(lg$ancestry)`
683 ancestry = function(){
684 nm <- get(".name", envir = private)
685 res <- logical(length(nm))
686
687 for (i in seq_along(nm)){
688 res[[i]] <- get("propagate", envir = get_logger(nm[1:i]))
689 }
690
691 structure(
692 setNames(res, nm),
693 class = c("ancestry", class(res))
694 )
695 },
696
697
698 #' @field parent a `Logger`. The direct ancestor of the `Logger`.
699 parent = function() {
700 nm <- get(".name", envir = private)
701
702 if (identical(nm, "root")){
703 return(NULL)
704 } else {
705 get_logger(nm[-length(nm)])
706 }
707 },
708
709
710 #' @field last_event The last LogEvent produced by the current Logger
711 last_event = function() {
712 get(".last_event", envir = private)
713 },
714
715
716 #' @field appenders a `list` of all [Appenders] of the Logger
717 appenders = function() {
718 get(".appenders", envir = private)
719 },
720
721
722 #' @field inherited_appenders A `list` of all appenders that the Logger
723 #' inherits from its ancestors
724 inherited_appenders = function(){
725 if (get(".propagate", envir = private)){
726 p <- get("parent", envir = self)
727 if (is.null(p))
728 return(NULL)
729
730 unlist(
731 unname(mget(c("appenders", "inherited_appenders"), envir = p)),
732 recursive = FALSE
733 )
734 } else {
735 NULL
736 }
737 },
738
739 replace_empty = function() {
740 get(".replace_empty", envir = private)
741 },
742
743 #' @field exception_handler a `function`. See `$set_exception_handler` and
744 #' `$handle_exception`
745 exception_handler = function() {
746 get(".exception_handler", envir = private)
747 }
748 ),
749
750
751 # .. private -----------------------------------------------------------------
752 private = list(
753 set_name = function(x){
754 assert(is_scalar_character(x))
755 private$.name <- unlist(strsplit(x, "/"))
756 invisible(self)
757 },
758
759 #' @description
760 #' Ensure all Appenders attached to a Logger are destroyed before the
761 #' Logger, so that the Appender's finalize method can access the logger if
762 #' it wants to
763 finalize = function(){
764
765 for (i in rev(seq_along(self$appenders))){
766 self$remove_appender(i)
767 gc()
768 }
769
770 invisible()
771 },
772
773 .propagate = NULL,
774 .exception_handler = NULL,
775 .name = NULL,
776 .appenders = NULL,
777 .threshold = NULL,
778 .last_event = NULL,
779 .replace_empty = NULL
780 )
781 )
782
783
784
785
786 # LoggerGlue --------------------------------------------------------------
787
788 #' LoggerGlue
789 #'
790 #' `LoggerGlue` uses [glue::glue()] instead of [base::sprintf()] to construct
791 #' log messages. **glue** is a very well designed package for
792 #' string interpolation. It makes composing log messages
793 #' more flexible and comfortable at the price of an additional dependency and
794 #' slightly less performance than `sprintf()`.
795 #'
796 #' `glue()` lets you define temporary named variables inside the call.
797 #' As with the normal Logger, these named arguments get turned into custom
798 #' fields; however, you can suppress this behaviour by making named argument
799 #' start with a `"."`. Please refer to `vignette("lgr", package = "lgr")` for
800 #' examples.
801 #'
802 #' @export
803 LoggerGlue <- R6::R6Class(
804 "LoggerGlue",
805 inherit = Logger,
806 cloneable = FALSE,
807
808 public = list(
809
810 initialize = function(
811 name = "(unnamed logger)",
812 appenders = list(),
813 threshold = NULL,
814 filters = list(),
815 exception_handler = default_exception_handler,
816 propagate = TRUE,
817 replace_empty = "<NULL>",
818 transformer = NULL
819 ){
820 # fields
821 # threshold must be set *after* the logging functions have been initalized
822 if (identical(name, "(unnamed logger)")){
823 warning(
824 "When creating a new Logger, you should assign it a unique `name`. ",
825 "Please see ?Logger for more infos.", call. = FALSE
826 )
827 }
828
829 private$set_name(name)
830 private$.last_event <- LogEvent$new(self)
831
832 self$set_threshold(threshold)
833 self$set_appenders(appenders)
834 self$set_propagate(propagate)
835 self$set_filters(filters)
836 self$set_exception_handler(exception_handler)
837 self$set_replace_empty(replace_empty)
838 self$set_transformer(transformer)
839
840 invisible(self)
841 },
842
843 # .. methods --------------------------------------------------------------
844 fatal = function(..., caller = get_caller(-8L), .envir = parent.frame()){
845 if (isTRUE(get("threshold", envir = self) < 100L))
846 return(invisible())
847
848 force(.envir)
849 get("log", envir = self)(
850 ...,
851 caller = caller,
852 level = 100L,
853 timestamp = Sys.time(),
854 .envir = .envir
855 )
856 },
857
858 error = function(..., caller = get_caller(-8L), .envir = parent.frame()){
859 if (isTRUE(get("threshold", envir = self) < 200L))
860 return(invisible())
861
862 get("log", envir = self)(
863 ...,
864 caller = caller,
865 level = 200L,
866 timestamp = Sys.time(),
867 .envir = .envir
868 )
869 },
870
871 warn = function(..., caller = get_caller(-8L), .envir = parent.frame()){
872 if (isTRUE(get("threshold", envir = self) < 300L))
873 return(invisible())
874
875 get("log", envir = self)(
876 ...,
877 caller = caller,
878 level = 300L,
879 timestamp = Sys.time(),
880 .envir = .envir
881 )
882 },
883
884 info = function(..., caller = get_caller(-8L), .envir = parent.frame()){
885 if (isTRUE(get("threshold", envir = self) < 400L))
886 return(invisible())
887
888 get("log", envir = self)(
889 ...,
890 caller = caller,
891 level = 400L,
892 timestamp = Sys.time(),
893 .envir = .envir
894 )
895 },
896
897 debug = function(..., caller = get_caller(-8L), .envir = parent.frame()){
898 if (isTRUE(get("threshold", envir = self) < 500L))
899 return(invisible())
900
901 force(.envir)
902 get("log", envir = self)(
903 ...,
904 caller = caller,
905 level = 500L,
906 timestamp = Sys.time(),
907 .envir = .envir
908 )
909 },
910
911 trace = function(..., caller = get_caller(-8L), .envir = parent.frame()){
912 if (isTRUE(get("threshold", envir = self) < 600L))
913 return(invisible())
914
915 force(.envir)
916 get("log", envir = self)(
917 ...,
918 caller = caller,
919 level = 600L,
920 timestamp = Sys.time(),
921 .envir = .envir
922 )
923 },
924
925 log = function(
926 level,
927 ...,
928 timestamp = Sys.time(),
929 caller = get_caller(-7),
930 .envir = parent.frame()
931 ){
932 if (identical(get("threshold", envir = self), 0L))
933 return(invisible())
934
935 LOG_CALL <- sys.call(-1L) # for error reporting
936
937 force(.envir)
938 tryCatch({
939 # preconditions
940 level <- standardize_log_levels(level)
941 assert(
942 identical(length(unique(level)), 1L),
943 "Can only utilize vectorized logging if log level is the same for all entries"
944 )
945
946 assert(
947 !missing(...),
948 "No log message or structured logging fields supplied"
949 )
950
951 dots <- list(...)
952
953 if ("msg" %in% names(dots)){
954 warning(
955 "LoggerGlue does not support a `$msg` argument. Please use unnamed ",
956 "text strings for construction your message like in `glue::glue()`.",
957 call. = FALSE
958 )
959 names(dots)[names(dots) == "msg"] <- ""
960 }
961
962 # construct msg
963 dots_msg <- dots # because we need the original dots later again
964
965 sel <- names(dots_msg) == ""
966 if (!length(sel)){
967 sel <- seq_along(dots_msg)
968 }
969
970 dots_msg[sel] <- lapply(dots_msg[sel], function(e){
971 if (inherits(e, "condition")){
972 conditionMessage(e)
973 } else {
974 as.character(e)
975 }
976 })
977
978 dots_msg <- replace_empty(dots_msg, get("replace_empty", self))
979 rawMsg <- dots[[1]]
980
981 glue_args <- list(.envir = .envir)
982
983 transformer <- get("transformer", self)
984
985 if (!is.null(transformer)){
986 glue_args[[".transformer"]] <- transformer
987 }
988
989 msg <- do.call(glue::glue, args = c(dots_msg, glue_args))
990
991 # Check if LogEvent should be created
992 if (
993 isTRUE(level[[1]] > get("threshold", envir = self)) ||
994 isTRUE(getOption("lgr.logging_suspended"))
995 ){
996 return(invisible(msg))
997 }
998
999 force(caller)
1000
1001 # Create list that contains all values equired for the log event
1002 custom_fields <- !(grepl("^\\.", names(dots)) | is_blank(names(dots)))
1003
1004 vals <- c(
1005 list(
1006 logger = self,
1007 level = level,
1008 timestamp = timestamp,
1009 caller = caller,
1010 msg = msg,
1011 rawMsg = rawMsg
1012 ),
1013 dots[custom_fields]
1014 )
1015
1016
1017 # This code looks really weird, but it really is just replacing all
1018 # instances of [[ with get() for minimal overhead. We want event
1019 # dispatch to be as quick as possible.
1020 event <- do.call(get("new", envir = LogEvent), vals)
1021 assign(".last_event", event, private)
1022
1023 if (get("filter", envir = self)(event)){
1024 for (app in unlist(mget(c("appenders", "inherited_appenders"), self), recursive = FALSE)){
1025 tryCatch({
1026 app_thresh <- get("threshold", envir = app)
1027 if (
1028 (is.na(app_thresh) || get("level", envir = event) <= app_thresh) &&
1029 get("filter", envir = app)(event)
1030 ){
1031 get("append", envir = app)(event)
1032 }
1033 }, error = function(e) {
1034 e$call <- LOG_CALL
1035 e$appender <- app
1036 e$logger <- self
1037 get("handle_exception", envir = self)(e)
1038 }
1039 )
1040 }
1041 }
1042 invisible(msg)
1043 },
1044 error = function(e){
1045 e$call <- LOG_CALL
1046 e$logger <- self
1047 get("handle_exception", envir = self)(e)
1048 }
1049 )
1050 },
1051
1052
1053 list_log = function(x){
1054 # TODO: Workaround until we have a better implementation of list_log
1055 names(x)[names(x) == "msg"] <- ""
1056 do.call(self$log, x)
1057 },
1058
1059
1060 spawn = function(name){
1061 get_logger_glue(c(private[[".name"]], name))
1062 },
1063
1064 # .. setters -----------------------------------------------------------------
1065
1066 #' @description Set the transformer for glue string interpolation
1067 #'
1068 #' @param x single [function] taking two arguments. See [glue::glue()].
1069 set_transformer = function(x){
1070 private[[".transformer"]] <- x
1071
1072 invisible(self)
1073 }
1074 ),
1075
1076 # .. active bindings ---------------------------------------------------
1077 active = list(
1078 transformer = function() {
1079 get(".transformer", envir = private)
1080 }
1081 ),
1082
1083
1084 # . private ------------------------------------
1085 private = list(
1086 .transformer = NULL
1087 )
1088 )
1089
1090
1091
1092
1093 # LoggerRoot --------------------------------------------------------------
1094
1095 #' Special logger subclass for the root logger. Currently exactly like a
1096 #' normal Logger, but prevents the threshold to be set to `NULL`
1097 #' @noRd
1098 LoggerRoot <- R6::R6Class(
1099 "LoggerRoot",
1100 inherit = Logger,
1101 cloneable = FALSE,
1102 public <- list(
1103 config = function(
1104 cfg,
1105 file,
1106 text
1107 ){
1108 if (is.null(cfg)){
1109 cfg <- logger_config()
1110 cfg$threshold <- getOption("lgr.default_threshold", 400L)
1111 }
1112
1113 super$config(
1114 cfg,
1115 file,
1116 text
1117 )
1118 },
1119
1120 set_threshold = function(level){
1121 if (is.null(level)){
1122 warning("Cannot set `threshold` to `NULL` for the root Logger")
1123 level <- NA_integer_
1124 }
1125 level <- standardize_threshold(level)
1126 private[[".threshold"]] <- level
1127 invisible(self)
1128 }
1129 )
1130 )
1131
1132
1133
1134
1135 # utils -------------------------------------------------------------------
1136
1137 is_Logger <- function(x){
1138 inherits(x, "Logger")
1139 }
1140
1141
1142
1143
1144 # print.Logger ------------------------------------------------------------
1145
1146 #' Print a Logger Object
1147 #'
1148 #' The `print()` method for Loggers displays the most important aspects of
1149 #' the Logger.
1150 #'
1151 #'
1152 #' @param x any \R Object
1153 #' @param color `TRUE` or `FALSE`: Output with color? Requires the Package
1154 #' **crayon**
1155 #' @param ... ignored
1156 #'
1157 #' @return
1158 #' `print()` returns `x` (invisibly), `format()` returns a `character` vector.
1159 #' @export
1160 #'
1161 #' @examples
1162 #' # print most important details of logger
1163 #' print(lgr)
1164
1165 print.Logger <- function(
1166 x,
1167 color = requireNamespace("crayon", quietly = TRUE),
1168 ...
1169 ){
1170 assert(is_scalar_bool(color))
1171 cat(format(x, color = color), sep = "\n")
1172 invisible(x)
1173 }
1174
1175
1176
1177
1178 #' @export
1179 #' @rdname print.Logger
1180 format.Logger = function(
1181 x,
1182 color = FALSE,
1183 ...
1184 ){
1185 assert(is_scalar_bool(color))
1186 assert(is_scalar_bool(color))
1187 if (!color) style_subtle <- identity
1188
1189 thr <- fmt_threshold(x$threshold, type = "character")
1190
1191 if (is_threshold_inherited(x)){
1192 thr <- style_subtle(thr)
1193 }
1194
1195
1196 header <- paste(
1197 paste0("<", class(x)[[1]], "> [", thr, "]"),
1198 format(x$ancestry, color = color)
1199 )
1200
1201 appenders <- appender_summary(x$appenders)
1202 inherited_appenders <- appender_summary(x$inherited_appenders)
1203
1204 ind <- " "
1205 res <- header
1206
1207 if (!is.null(appenders)){
1208 res <-c(
1209 res, "",
1210 "appenders:", paste0(ind, appenders)
1211 )
1212 }
1213
1214 if (!is.null(inherited_appenders)){
1215 res <- c(
1216 res, "",
1217 "inherited appenders:", paste0(ind, inherited_appenders)
1218 )
1219 }
1220
1221 res
1222 }
1223
1224
1225
1226 appender_summary <- function(x){
1227 dd <- lapply(x, srs_appender)
1228
1229 if (!length(x)){
1230 return(NULL)
1231 }
1232
1233 if (is.null(names(x))){
1234 names(x) <- ""
1235 }
1236
1237
1238 dd <- do.call(rbind, dd)
1239
1240 if (is.null(dd)) return(NULL)
1241
1242 dd$name <- ifelse(
1243 is.na(names(x)) | is_blank(names(x)),
1244 paste0("[[", seq_len(length(x)), "]]"),
1245 names(x)
1246 )
1247
1248 dd$destination <- ifelse(
1249 !is_blank(dd$destination),
1250 paste("->", dd$destination),
1251 ""
1252 )
1253
1254 with(
1255 dd,
1256 paste0(
1257 pad_right(name), ": ",
1258 pad_right(class), " [",
1259 pad_left(fmt_threshold(threshold, type = "character")), "] ",
1260 destination
1261 )
1262 )
1263 }
1264
1265
1266
1267 # single-row-summary
1268 srs_appender <- function(x){
1269 data.frame(
1270 class = fmt_class(class(x)[[1]]),
1271 threshold = x$threshold,
1272 destination = x$destination
1273 )
1274 }
1275
1276
1277
1278
1279 #' @description
1280 #' You can also print just the `ancestry` of a Logger which can be accessed with
1281 #' with `logger$ancestry()`. This returns a named `character` vector whose
1282 #' names correspond to the names of the Loggers `logger` inherits from. The
1283 #' `TRUE`/`FALSE` status of its elements correspond to the `propagate` values of
1284 #' these Loggers.
1285 #'
1286 #' @rdname print.Logger
1287 #' @export
1288 #'
1289 #' @examples
1290 #' # print only the ancestry of a logger
1291 #' lg <- get_logger("AegonV/Aerys/Rheagar/Aegon")
1292 #' get_logger("AegonV/Aerys/Rheagar")$set_propagate(FALSE)
1293 #'
1294 #' print(lg$ancestry)
1295 #' unclass(lg$ancestry)
1296
1297 print.ancestry <- function(
1298 x,
1299 color = requireNamespace("crayon", quietly = TRUE),
1300 ...
1301 ){
1302 assert(is_scalar_bool(color))
1303 cat(format(x, color = color), "\n")
1304 invisible(x)
1305 }
1306
1307
1308
1309
1310 #' @export
1311 #' @rdname print.Logger
1312 format.ancestry <- function(
1313 x,
1314 color = FALSE,
1315 ...
1316 ){
1317 assert(is_scalar_bool(color))
1318 sps <- rep("/", length(x))
1319 nms <- names(x)
1320
1321 style <- identity
1322
1323 if (color){
1324 for (i in rev(seq_along(x))){
1325 nms[[i]] <- style(nms[[i]])
1326 sps[[i]] <- style(sps[[i]])
1327 if (!x[[i]]){
1328 style <- style_subtle
1329 }
1330 }
1331 }
1332
1333 sps[length(sps)] <- ""
1334
1335 paste0(nms, sps, collapse = "")
1336 }
1337
1338
1339
1340
1341 is_threshold_inherited <- function(x){
1342 is.null(x[[".__enclos_env__"]][["private"]][[".threshold"]])
1343 }
1344