Debian Codegraph @

R/Appender.R

raw
1 # Appender ----------------------------------------------------------------
2
3 #' Appenders
4 #'
5 #' @description Appenders are attached to [Loggers] and manage the output of the
6 #' [LogEvents] to a destination - such as the console or a text file. An
7 #' Appender has a single [Layout] that tells it how to format the LogEvent. For
8 #' details please refer to the documentations of the specific Appenders.
9 #'
10 #' Additional Appenders that support a wide range of output destinations -
11 #' such as databases, email, push-notifications or Linux syslog - are available
12 #' from the package [lgrExtra](https://github.com/s-fleck/lgrExtra).
13 #'
14 #' @template abstract_class
15 #'
16 #' @aliases Appenders
17 #' @family Appenders
18 #' @include utils.R
19 #' @include utils-sfmisc.R
20 #' @include Filterable.R
21 #' @keywords internal
22 #' @export
23 Appender <- R6::R6Class(
24 "Appender",
25 inherit = Filterable,
26 cloneable = FALSE,
27
28 # +- public --------------------------------------------------------------
29 public = list(
30
31 initialize = function(
32 layout = Layout$new(),
33 threshold = NA_integer_
34 ){
35 self$set_layout(layout)
36 self$set_threshold(threshold)
37 },
38
39 #' @description Process a [LogEvent] `event`. This method is usually not
40 #' called by the user, but invoked by a [Logger]
41 append = function(event){
42 private$.layout$format_event(event)
43 },
44
45
46 #' @description Set the minimum log level that triggers this Appender. See
47 #' [threshold()] for examples
48 #' @param level `character` or `integer` scalar log level. See [log_levels].
49 set_threshold = function(level){
50 level <- standardize_threshold(level)
51 private$.threshold <- as.integer(level)
52 invisible(self)
53 },
54
55
56 #' @description Set the `Layout` that this Appender will use for formatting
57 #' `LogEvents`
58 set_layout = function(layout){
59 if (is_scalar_list(layout)){
60 # set_layout also accepts a list of length 1 containing a single Layout
61 # object. This is a workaround for resolve_r6_ctors. This behaviour is
62 # intentionally not documented and you should not rely on it.
63 layout <- layout[[1]]
64 }
65 assert(
66 inherits(layout, "Layout"),
67 "`layout` must a `Layout` object, but is ", string_repr(layout)
68 )
69 private$.layout <- layout
70 invisible(self)
71 },
72
73 format = function(
74 color = FALSE,
75 ...
76 ){
77 assert(is_scalar_bool(color))
78 if (!color)
79 style_subtle <- identity
80
81 thr <- fmt_threshold(self$threshold, type = "character")
82
83 header <- paste(
84 paste0("<", class(self)[[1]], "> [", thr, "]")
85 )
86
87 if (!is.null(self$layout)){
88 res <- c(
89 header,
90 paste0(" layout: ", self$layout$toString())
91 )
92 }
93
94 if (!is.null(self$destination)){
95 res <- c(
96 res, paste(" destination:", self$destination)
97 )
98 }
99
100 if (!color)
101 style_error <- identity
102
103 if (class(self)[[1]] == "Appender"){
104 paste(res[[1]], style_error("[abstract class]"))
105 } else {
106 res
107 }
108 }
109
110 ),
111
112
113 # +- active ---------------------------------------------------------------
114 active = list(
115 threshold = function() private$.threshold,
116
117 layout = function() private$.layout,
118
119 #' @field destination
120 #' The output destination of the `Appender` in human-readable form. This
121 #' is mainly used when printing information about the Appender itself.
122 destination = function() ""
123 ),
124
125 private = list(
126 .threshold = NA,
127 .layout = NULL
128 )
129 )
130
131
132
133
134 # AppenderConsole ---------------------------------------------------------
135
136 #' Log to the console
137 #'
138 #' An Appender that outputs to the \R console. If you have the package
139 #' **crayon** installed log levels will be coloured by default
140 #' (but you can modify this behaviour by passing a custom [Layout]).
141 #'
142 #' @param connection A connection or a `character` scalar. See the `file`
143 #' argument of [cat()] for more details. Defaults to [stdout()], except
144 #' inside \pkg{knitr} rendering processes where it defaults to [stderr()].
145 #'
146 #' @family Appenders
147 #' @seealso [LayoutFormat]
148 #' @export
149 #'
150 #' @examples
151 #' # create a new logger with propagate = FALSE to prevent routing to the root
152 #' # logger. Please look at the section "Logger Hirarchies" in the package
153 #' # vignette for more info.
154 #' lg <- get_logger("test")$set_propagate(FALSE)
155 #'
156 #' lg$add_appender(AppenderConsole$new())
157 #' lg$add_appender(AppenderConsole$new(
158 #' layout = LayoutFormat$new("[%t] %c(): [%n] %m", colors = getOption("lgr.colors"))))
159 #'
160 #' # Will output the message twice because we attached two console appenders
161 #' lg$warn("A test message")
162 #' lg$config(NULL) # reset config
163 AppenderConsole <- R6::R6Class(
164 "AppenderConsole",
165 inherit = Appender,
166 cloneable = FALSE,
167 public = list(
168 initialize = function(
169 threshold = NA_integer_,
170 layout = LayoutFormat$new(
171 fmt = "%L [%t] %m %f",
172 timestamp_fmt = "%H:%M:%OS3",
173 colors = getOption("lgr.colors", list())
174 ),
175 filters = NULL,
176 connection = NULL
177 ){
178 self$set_threshold(threshold)
179 self$set_layout(layout)
180 self$set_filters(filters)
181 if (is.null(connection)) {
182 connection <- default_console_connection()
183 }
184 self$set_connection(connection)
185 },
186
187 append = function(event){
188 cat(private$.layout$format_event(event), sep = "\n", file = get(".connection", private))
189 },
190
191 set_connection = function(connection){
192 assert(
193 inherits(connection, "connection") || is_scalar_character(connection)
194 )
195
196 private[[".connection"]] <- connection
197 }
198 ),
199
200 active = list(
201 destination = function() "console",
202 connection = function() private[[".connection"]]
203 ),
204
205 private = list(
206 .connection = NULL
207 )
208 )
209
210 default_console_connection <- function() {
211 # In knitr, default to using stderr where log messages can be better handled
212 if (isTRUE(getOption("knitr.in.progress", FALSE))) {
213 return(stderr())
214 }
215
216 # has to be this, not a call to `stdout()`
217 ""
218 }
219
220
221 # AppenderFile ------------------------------------------------------------
222
223 #' Log to a file
224 #'
225 #' @description
226 #' A simple Appender that outputs to a file in the file system. If you plan
227 #' to log to text files, consider logging to JSON files and take a look at
228 #' [AppenderJson], which is a shortcut for `AppenderFile` preconfigured with
229 #' [`LayoutJson`].
230 #'
231 #'
232 #' @export
233 #' @seealso [LayoutFormat], [LayoutJson]
234 #' @family Appenders
235 #' @name AppenderFile
236 #'
237 #' @examples
238 #' lg <- get_logger("test")
239 #' default <- tempfile()
240 #' fancy <- tempfile()
241 #' json <- tempfile()
242 #'
243 #' lg$add_appender(AppenderFile$new(default), "default")
244 #' lg$add_appender(
245 #' AppenderFile$new(fancy, layout = LayoutFormat$new("[%t] %c(): %L %m")), "fancy"
246 #' )
247 #' lg$add_appender(
248 #' AppenderFile$new(json, layout = LayoutJson$new()), "json"
249 #' )
250 #'
251 #' lg$info("A test message")
252 #'
253 #' readLines(default)
254 #' readLines(fancy)
255 #' readLines(json)
256 #'
257 #' # cleanup
258 #' lg$config(NULL)
259 #' unlink(default)
260 #' unlink(fancy)
261 #' unlink(json)
262 AppenderFile <- R6::R6Class(
263 "AppenderFile",
264 inherit = Appender,
265 cloneable = FALSE,
266 public = list(
267 initialize = function(
268 file,
269 threshold = NA_integer_,
270 layout = LayoutFormat$new(),
271 filters = NULL
272 ){
273 self$set_file(file)
274 self$set_threshold(threshold)
275 self$set_layout(layout)
276 self$set_filters(filters)
277 },
278
279 append = function(event){
280 cat(
281 private$.layout$format_event(event),
282 sep = "\n",
283 file = get(".file", envir = private),
284 append = TRUE
285 )
286 },
287
288 #' @description Set a log file
289 #' @param file `character` scalar. Path to the log file. If `file` does not
290 #' exist it will be created.
291 set_file = function(file){
292 assert(
293 is_scalar_character(file),
294 "`file` must be character scalar, not: ", string_repr(file)
295 )
296
297 assert(
298 dir.exists(dirname(file)),
299 "Cannot create file: directory '", dirname(file), "' does not exist."
300 )
301
302 private$.file <- file
303 if (!file.exists(file)) { assert(
304 file.create(file, showWarnings = FALSE),
305 "Cannot create file '", file , "'"
306 )}
307
308 invisible(self)
309 },
310
311
312 #' @description Display the contents of the log file.
313 #'
314 #' @param threshold `character` or `integer` scalar. The minimum log level
315 #' that should be displayed.
316 #' @param n `integer` scalar. Show only the last `n` log entries that match
317 #' `threshold`.
318 show = function(
319 threshold = NA_integer_,
320 n = 20L
321 ){
322 assert(is_scalar_integerish(n))
323 threshold <- standardize_threshold(threshold)
324 reader <- self$layout$read %||% default_file_reader
325
326 dd <- reader(self$file, threshold = threshold, n = n)
327
328 cat(dd, sep = "\n")
329 invisible(dd)
330 }
331 ),
332
333
334 # +- active ---------------------------------------------------------------
335 active = list(
336
337 #' @field file `character` scalar. path to the log file
338 file = function() private$.file,
339
340 #' @field data `data.frame`. Contents of `file` parsed to a
341 #' `data.frame` if used with a [Layout] that supports parsing of log
342 #' file data (notably [LayoutJson]). Will throw an error if `Layout` does
343 #' not support parsing.
344 data = function(){
345 parser <- self$layout$parse
346
347 assert(
348 !is.null(parser),
349 CannotParseLogError(paste(
350 "Neither", fmt_class(class(self)[[1]]), "nor", fmt_class(class(self$layout)[[1]]),
351 "support parsing log files to data.frames. Consider using <LayoutJson>",
352 "instead."
353 ))
354 )
355
356 parser(self$file)
357 },
358
359 #' @field data `character` scalar. Like `$data`, but returns a `data.table`
360 #' instead (requires the **data.table** package).
361 dt = function(){
362 data.table::as.data.table(self$data)
363 },
364
365 destination = function() self$file
366 ),
367
368 private = list(
369 .file = NULL
370 )
371 )
372
373
374
375
376 # AppenderJson ------------------------------------------------------------
377
378 #' Log to a JSON file
379 #'
380 #' @rdname AppenderFile
381 #'
382 #' @family Appenders
383 #' @export
384 #' @seealso [LayoutFormat], [LayoutJson]
385 #' @examples
386 #' tf <- tempfile()
387 #' lg <- get_logger("test")$
388 #' set_appenders(AppenderJson$new(tf))$
389 #' set_propagate(FALSE)
390 #'
391 #' lg$info("A test message")
392 #' lg$info("A test message %s strings", "with format strings", and = "custom_fields")
393 #'
394 #' lg$appenders[[1]]$show()
395 #' lg$appenders[[1]]$data
396 #'
397 #' # cleanup
398 #' lg$config(NULL)
399 #' unlink(tf)
400 AppenderJson <- R6::R6Class(
401 "AppenderJson",
402 inherit = AppenderFile,
403 cloneable = FALSE,
404 public = list(
405 initialize = function(
406 file,
407 threshold = NA_integer_,
408 layout = LayoutJson$new(),
409 filters = NULL
410 ){
411 assert_namespace("jsonlite")
412
413 self$set_file(file)
414 self$set_threshold(threshold)
415 self$set_layout(layout)
416 self$set_filters(filters)
417 }
418 )
419 )
420
421
422
423
424 # AppenderTable -----------------------------------------------------------
425 # nocov start
426
427 #' Abstract class for logging to tabular structures
428 #'
429 #' @template abstract_class
430 #'
431 #' @description AppenderTable is extended by Appenders that write to a data
432 #' source that can be interpreted as tables, (usually a `data.frame`). Examples
433 #' are `AppenderDbi`, `AppenderRjdbc` and `AppenderDt` from the
434 #' [lgrExtra](https://github.com/s-fleck/lgrExtra) package.
435 #'
436 #' @family Appenders
437 #' @export
438 AppenderTable <- R6::R6Class(
439 "AppenderTable",
440 inherit = Appender,
441 cloneable = FALSE,
442
443 public = list(
444 initialize = function(...){
445 stop(CannotInitializeAbstractClassError())
446 },
447
448 #' @description Show recent log entries
449 #' @param n a positive `integer` scalar. Show at most that many entries
450 #' @param threshold an `integer` or `character` [threshold][log_level].
451 #' Only show events with a log level at or below this threshold.
452 show = function(threshold = NA_integer_, n = 20L) NULL,
453
454 format = function(
455 color = FALSE,
456 ...
457 ){
458 res <- super$format(color = color, ...)
459
460 if (!color)
461 style_error <- identity
462
463 if (class(self)[[1]] == "AppenderTable"){
464 paste(res[[1]], style_error("[abstract class]"))
465 } else {
466 res
467 }
468 }
469 ),
470
471 active = list(
472 #' @field data `character` scalar. Contents of the table, parsed to a
473 #' `data.frame`.
474 data = function() as.data.frame(self$dt),
475
476 #' @field data `character` scalar. Like `$data`, but returns a `data.table`
477 #' instead (requires the **data.table** package).
478 dt = function() data.table::as.data.table(self$data)
479 )
480 )
481
482 # nocov end
483
484
485
486
487 # AppenderMemory --------------------------------------------------
488
489 #' Abstract class for logging to memory buffers
490 #'
491 #' @template abstract_class
492 #'
493 #' @description
494 #' AppenderMemory is extended by Appenders that retain an in-memory event
495 #' buffer, such as [AppenderBuffer] and `AppenderPushbullet` from the
496 #' [lgrExtra](https://github.com/s-fleck/lgrExtra) package.
497 #'
498 #' @export
499 #' @seealso [LayoutFormat]
500 #'
501 #' @export
502 AppenderMemory <- R6::R6Class(
503 "AppenderMemory",
504 inherit = Appender,
505 cloneable = FALSE,
506 public = list(
507 initialize = function(...){
508 stop(CannotInitializeAbstractClassError())
509 },
510
511 append = function(event){
512
513 i <- get("insert_pos", envir = private) + 1L
514 assign("insert_pos", i, envir = private, inherits = TRUE)
515 private[["last_event"]] <- private[["last_event"]] + 1L
516 private[["event_order"]][[i]] <- private[["last_event"]]
517 private[[".buffer_events"]][[i]] <- event
518
519 # check if buffer should be flushed
520 if ({
521 # buffer is rotated
522 i > get(".buffer_size", envir = private) &&
523 get(".flush_on_rotate", envir = private)
524 } || {
525 # flush threshold is exceeded
526 thr <- get(".flush_threshold", envir = private)
527 !is.null(thr) && (is.na(thr) || all(event[["level"]] <= thr))
528 } || {
529 # should_flush() function triggers
530 standardize_should_flush_output(
531 get(".should_flush", envir = private)(event)
532 )
533 }){
534 self$flush()
535 } else if (i > get(".buffer_size", envir = private)){
536 # check if flush should be triggered if buffer size is exceeded
537 # sepparetly from other conditions. Must be below all other flush
538 # conditions in case this causes the buffer to be cleared but not flushed.
539 if (get(".flush_on_rotate", envir = private) ){
540 self[["flush"]]()
541 } else {
542 # does not clear the buffer. this is intentional
543 assign("insert_pos", 0L, envir = private)
544 }
545 }
546
547 },
548
549
550 #' @description Sends the buffer's contents to all attached Appenders and
551 #' then clears the Buffer
552 flush = function(){self},
553
554 #' @description Clears the buffer, discarding all buffered Events
555 clear = function(){self},
556
557 #' @description Set the maximum size of the buffer
558 #' @param x an `integer` scalar `>= 0`. Number of [LogEvents] to buffer.
559 set_buffer_size = function(x){
560 assert(is_n0(x))
561 private$.buffer_size <- x
562 invisible(self)
563 },
564
565 #' @description Set function that can trigger flushing the buffer
566 #' @param x A `function` with the single argument `event`. Setting `x` to
567 #' `NULL` is a shortcut for `function(event) FALSE`. See active bindings.
568 set_should_flush = function(x){
569 if (is.null(x)) x <- function(event) FALSE
570 assert_filter(x)
571 private$.should_flush <- x
572 invisible(self)
573 },
574
575 #' @description Should the buffer be flushed when the Appender is destroyed?
576 #' @param x A `logical` scalar. See active bindings.
577 set_flush_on_exit = function(x){
578 assert(is_scalar_bool(x))
579 private$.flush_on_exit <- x
580 invisible(self)
581 },
582
583 #' @description Should the buffer be flushed if `buffer_size` is exceeded?
584 #' @param x A `logical` scalar. See active bindings.
585 set_flush_on_rotate = function(x){
586 assert(is_scalar_bool(x))
587 private$.flush_on_rotate <- x
588 invisible(self)
589 },
590
591 #' @description Set threshold that triggers flushing
592 #' @param level A `numeric` or `character` [threshold][log_level]. See
593 #' active bindings.
594 set_flush_threshold = function(level){
595 if (!is.null(level))
596 level <- standardize_threshold(level)
597
598 private$.flush_threshold <- level
599 invisible(self)
600 },
601
602
603 #' @description Display the contents of the log table. Relies on the
604 #' `$format_event` method of the [Layout] attached to this Appender.
605 #'
606 #' @param threshold `character` or `integer` scalar. The minimum log level
607 #' that should be displayed.
608 #' @param n `integer` scalar. Show only the last `n` log entries that match
609 #' `threshold`.
610 show = function(threshold = NA_integer_, n = 20L){
611 assert(is_scalar_integerish(n))
612 threshold <- standardize_threshold(threshold)
613
614 if (is.na(threshold)) threshold <- Inf
615 dd <- get("buffer_dt", envir = self)
616
617 if (identical(nrow(dd), 0L)){
618 cat("[empty log]")
619 return(invisible(NULL))
620 }
621
622 dd <- tail(dd[dd$level <= threshold, ], n)
623 dd <- as.environment(dd)
624 assign("logger", self[[".logger"]], dd)
625 cat(self$layout$format_event(dd), sep = "\n")
626 invisible(dd)
627 },
628
629 format = function(
630 color = FALSE,
631 ...
632 ){
633 res <- super$format(color = color, ...)
634
635 if (!color)
636 style_error <- identity
637
638 if (class(self)[[1]] == "AppenderMemory"){
639 paste(res[[1]], style_error("[abstract class]"))
640 } else {
641 res
642 }
643 }
644 ),
645
646
647
648 # +- active ---------------------------------------------------------------
649 active = list(
650 #' @field flush_on_exit A `logical` scalar. Should the buffer be flushed if
651 #' the Appender is destroyed (e.g. because the \R session is terminated)?
652 flush_on_exit = function() {
653 get(".flush_on_exit", private)
654 },
655
656 #' @field flush_on_rotate A `logical` scalar. Should the buffer be flushed when it is
657 #' rotated because `$buffer_size` is exceeded?
658 flush_on_rotate = function() {
659 get(".flush_on_rotate", private)
660 },
661
662 #' @field should_flush A `function` with exactly one arguments: `event`.
663 #' `$append()` calls this function internally on the current [LogEvent]
664 #' and flushes the buffer if it evaluates to `TRUE`.
665 should_flush = function(){
666 get(".should_flush", private)
667 },
668
669 #' @field buffer_size `integer` scalar `>= 0`. Maximum number of [LogEvents]
670 #' to buffer.
671 buffer_size = function() {
672 get(".buffer_size", private)
673 },
674
675 #' @field flush_threshold A `numeric` or `character` threshold. [LogEvents]
676 #' with a [log_level] equal to or lower than this threshold trigger
677 #' flushing the buffer.
678 flush_threshold = function(){
679 get(".flush_threshold", private)
680 },
681
682 #' @field buffer_events A `list` of [LogEvents]. Contents of the buffer.
683 buffer_events = function() {
684 res <- get(".buffer_events", envir = private)
685
686 if (length(res)){
687 ord <- get("event_order", envir = private)
688 ord <- ord - min(ord) + 1L
689 ord <- order(ord)
690 res <- res[ord]
691 }
692
693 as_event_list(
694 res[!vapply(res, is.null, FALSE)]
695 )
696 },
697
698 data = function(){
699 self$buffer_df
700 },
701
702 dt = function(){
703 self$buffer_dt
704 },
705
706 #' @field buffer_events A `data.frame`. Contents of the buffer converted
707 #' to a `data.frame`.
708 buffer_df = function() {
709 as.data.frame(self[["buffer_dt"]])
710 },
711
712 #' @field buffer_events A `data.frame`. Contents of the buffer converted
713 #' to a `data.table`.
714 buffer_dt = function(){
715 assert_namespace("data.table")
716 as.data.table.event_list(get("buffer_events", self))
717 }
718 ),
719
720 # +- private ---------------------------------------------------------
721 private = list(
722 initialize_buffer = function(buffer_size){
723 assert(is_n0(buffer_size))
724 private[["insert_pos"]] <- 0L
725 private[["last_event"]] <- 0L
726 private[["event_order"]] <- seq_len(buffer_size)
727 private[[".buffer_size"]] <- buffer_size
728 private[[".buffer_events"]] <- list()
729 },
730
731 insert_pos = NULL,
732 last_event = NULL,
733 event_order = NULL,
734
735 .flush_threshold = NULL,
736 .should_flush = NULL,
737 .flush_on_exit = NULL,
738 .flush_on_rotate = NULL,
739 .buffer_size = NULL,
740 .buffer_events = NULL
741 )
742 )
743
744
745
746
747 # AppenderBuffer --------------------------------------------------
748
749 #' Log to a memory buffer
750 #'
751 #' @description
752 #' An Appender that Buffers LogEvents in-memory and and redirects them to other
753 #' Appenders once certain conditions are met.
754 #'
755 #' @section Fields:
756 #'
757 #' \describe{
758 #' \item{`appenders`, `set_appenders()`}{Like for a [Logger]. Buffered events
759 #' will be passed on to these Appenders once a flush is triggered}
760 #' \item{`flush_on_exit, set_flush_on_exit(x)`}{`TRUE` or `FALSE`: Whether the
761 #' buffer should be flushed when the Appender is garbage collected (f.e when
762 #' you close \R)}
763 #' \item{`flush_on_rotate, set_flush_on_rotate`}{`TRUE` or `FALSE`: Whether
764 #' the buffer should be flushed when the Buffer is full (f.e when you close
765 #' \R). Setting this to off can have slightly negative performance impacts.}
766 #' }
767 #'
768 #' @export
769 #' @seealso [LayoutFormat]
770 #' @family Appenders
771 #' @export
772 AppenderBuffer <- R6::R6Class(
773 "AppenderBuffer",
774 inherit = AppenderMemory,
775 cloneable = FALSE,
776 public = list(
777
778 #' @description
779 #' The [Layout] for this Appender is used only to format console output of
780 #' its `$show()` method.
781 initialize = function(
782 threshold = NA_integer_,
783 layout = LayoutFormat$new(
784 fmt = "%L [%t] %m",
785 timestamp_fmt = "%H:%M:%S",
786 colors = getOption("lgr.colors")
787 ),
788 appenders = NULL,
789 buffer_size = 1e3,
790 flush_threshold = NULL,
791 flush_on_exit = TRUE,
792 flush_on_rotate = TRUE,
793 should_flush = NULL,
794 filters = NULL
795 ){
796 self$set_threshold(threshold)
797
798 private$initialize_buffer(buffer_size)
799
800 self$set_should_flush(should_flush)
801 self$set_flush_threshold(flush_threshold)
802 self$set_flush_on_exit(flush_on_exit)
803 self$set_flush_on_rotate(flush_on_rotate)
804 self$set_filters(filters)
805
806 self$set_appenders(appenders)
807 self$set_layout(layout)
808
809 invisible(self)
810 },
811
812
813 #' @description Sends the buffer's contents to all attached Appenders and
814 #' then clears the Buffer
815 flush = function(){
816 for (event in get("buffer_events", envir = self)){
817 for (app in self$appenders) {
818 if (app$filter(event)) app$append(event)
819 }
820 }
821
822 self$clear()
823 },
824
825 #' @description Clears the buffer, discarding all buffered Events
826 clear = function(){
827 assign("insert_pos", 0L, envir = private)
828 private$.buffer_events <- list()
829 invisible(self)
830 },
831
832
833 #' @description Exactly like A [Logger], an [AppenderBuffer] can have an
834 #' arbitrary amount of Appenders attached. When the buffer is flushed, the
835 #' buffered events are dispatched to these Appenders.
836 #'
837 #' @param x single [Appender] or a `list` thereof. Appenders control the
838 #' output of a Logger. Be aware that a Logger also inherits the Appenders
839 #' of its ancestors (see `vignette("lgr", package = "lgr")` for more info
840 #' about Logger inheritance).
841 set_appenders = function(x){
842 if (is.null(x)){
843 private$.appenders <- list()
844 return(invisible())
845 }
846 if (inherits(x, "Appender")) x <- list(x)
847
848 assert(
849 is.list(x) && all(vapply(x, inherits, TRUE, "Appender")),
850 "'appenders' must either be a single Appender, a list thereof, or ",
851 "NULL for no appenders."
852 )
853
854 private$.appenders <- list()
855
856 for (i in seq_along(x))
857 self$add_appender(x[[i]], name = names(x)[[i]])
858
859 invisible(self)
860 },
861
862
863 #' @description Add an Appender to the AppenderBuffer
864 #' @param appender a single [Appender]
865 #' @param name a `character` scalar. Optional but recommended.
866 #'
867 #' @description Add or remove an [Appender]. Supplying a `name` is optional but
868 #' recommended. After adding an Appender with
869 #' `appender$add_appender(AppenderConsole$new(), name = "console")` you can
870 #' refer to it via `appender$appenders$console`. `remove_appender()` can
871 #' remove an Appender by position or name.
872 add_appender = function(
873 appender,
874 name = NULL
875 ){
876 assert(inherits(appender, "Appender"))
877
878 private$.appenders[[length(private$.appenders) + 1L]] <- appender
879 if (!is.null(name))
880 names(private$.appenders)[length(private$.appenders)] <- name
881
882 invisible(self)
883 },
884
885
886 #' @description remove an appender
887 #' @param pos `integer` index or `character` name of the Appender(s) to
888 #' remove
889 #'
890 remove_appender = function(
891 pos
892 ){
893 if (is.numeric(pos)){
894 assert(
895 all(pos %in% seq_along(private$.appenders)),
896 "'pos' is out of range of the length of appenders (1:",
897 length(private$.appenders), ")"
898 )
899
900 pos <- as.integer(pos)
901 } else if (is.character(pos)) {
902 assert(
903 all(pos %in% names(private$.appenders)),
904 "'pos' is not names of appenders (",
905 paste(names(private$.appenders), collapse = ", "),
906 ")"
907 )
908 }
909
910 for (nm in pos){
911 private$.appenders[[nm]] <- NULL
912 }
913
914 invisible(self)
915 },
916
917
918 format = function(
919 ...
920 ){
921 res <- super$format()
922 appenders <- appender_summary(self$appenders)
923 if (!is.null(appenders)){
924 res <-c(
925 res, paste0(" ", appenders)
926 )
927 }
928
929 res
930 }
931 ),
932
933
934
935 # +- active ---------------------------------------------------------------
936 active = list(
937 appenders = function(value){
938 if (missing(value)) return(c(private$.appenders))
939
940 if (is.null(value)){
941 private$.appenders <- NULL
942 return(invisible())
943 }
944
945 if (inherits(value, "Appender"))
946 value <- list(value)
947
948 assert(
949 is.list(value) && all(vapply(value, inherits, TRUE, "Appender")),
950 "'appenders' must either be a single Appender, a list thereof, or NULL for no appenders."
951 )
952
953 private$.appenders <- value
954 invisible()
955 },
956
957 destination = function() paste(length(self$appenders), "child Appenders")
958 ),
959
960 # +- private ---------------------------------------------------------
961 private = list(
962 finalize = function(){
963 if (self$flush_on_exit) self$flush()
964 # Ensure child appenders are gc'ed first. This ensures more predictable
965 # behaviour when destroying an AppenderBuffer.
966 for (i in rev(seq_along(self$appenders))){
967 self$remove_appender(i)
968 gc()
969 }
970 invisible()
971 },
972
973 .appenders = list()
974 )
975 )
976
977
978
979
980
981
982
983 # AppenderFileRotating ----------------------------------------------------
984
985 #' Log to a rotating file
986 #'
987 #' An extension of [AppenderFile] that rotates logfiles based on certain
988 #' conditions. Please refer to the documentation of [rotor::rotate()] for
989 #' the meanings of the extra arguments
990 #'
991 #' @export
992 #' @seealso [AppenderFileRotatingDate], [AppenderFileRotatingTime], [rotor::rotate()]
993 #' @family Appenders
994 #' @export
995 AppenderFileRotating <- R6::R6Class(
996 "AppenderFileRotating",
997 inherit = AppenderFile,
998 public = list(
999
1000 #' @description
1001 #' @param size,max_backups,compression,backup_dir,fmt
1002 #' see [rotor::rotate()] for the meaning of these arguments. Note that
1003 #' `fmt` corresponds to `format` and `backup_dir` to `dir`.
1004 initialize = function(
1005 file,
1006 threshold = NA_integer_,
1007 layout = LayoutFormat$new(),
1008 filters = NULL,
1009
1010 size = Inf,
1011 max_backups = Inf,
1012 compression = FALSE,
1013 backup_dir = dirname(file),
1014 create_file = NULL
1015 ){
1016 assert_namespace("rotor")
1017
1018 if (!file.exists(file)) file.create(file)
1019
1020 if (length(create_file)){
1021 .Deprecated(msg = "The create_file argument is defunct and will be removed from future versions of lgr.")
1022 }
1023
1024 private$bq <- rotor::BackupQueueIndex$new(file)
1025
1026 self$set_file(file)
1027 self$set_threshold(threshold)
1028 self$set_layout(layout)
1029 self$set_filters(filters)
1030
1031 self$set_size(size)
1032 self$set_max_backups(max_backups)
1033 self$set_compression(compression)
1034 self$set_backup_dir(backup_dir)
1035 self$set_create_file(TRUE)
1036
1037 self
1038 },
1039
1040
1041 append = function(event){
1042 super$append(event)
1043 self$rotate()
1044 },
1045
1046
1047 rotate = function(
1048 force = FALSE
1049 ){
1050 assert(is_scalar_bool(force))
1051
1052 bq <- get("bq", private)
1053
1054 if (force || bq$should_rotate(size = self$size)){
1055 bq$push()
1056 bq$prune()
1057 file.remove(self$file)
1058 file.create(self$file)
1059 }
1060
1061 self
1062 },
1063
1064
1065 prune = function(max_backups = self$max_backups){
1066 get("bq", envir = private)$prune(max_backups)
1067 self
1068 },
1069
1070
1071 set_file = function(
1072 file
1073 ){
1074 super$set_file(file)
1075 private$bq$set_origin(self$file)
1076 self
1077 },
1078
1079
1080 set_size = function(
1081 x
1082 ){
1083 private[[".size"]] <- x
1084 self
1085 },
1086
1087
1088 set_max_backups = function(
1089 x
1090 ){
1091 private[["bq"]]$set_max_backups(x)
1092 self
1093 },
1094
1095
1096 set_compression = function(
1097 x
1098 ){
1099 private[["bq"]]$set_compression(x)
1100 self
1101 },
1102
1103
1104 set_create_file = function(
1105 x
1106 ){
1107 assert(is_scalar_bool(x))
1108 private[[".create_file"]] <- x
1109 self
1110 },
1111
1112
1113 set_backup_dir = function(
1114 x
1115 ){
1116 private$bq$set_dir(x, create = FALSE)
1117 self
1118 },
1119
1120
1121 format = function(
1122 color = false,
1123 ...
1124 ){
1125 res <- super$format(color = color, ...)
1126
1127 if (!color)
1128 style_subtle <- identity
1129
1130 cs <- style_subtle(
1131 sprintf("(current size: %s)", fmt_bytes(file.size(self$file)))
1132 )
1133
1134 size <- {
1135 if (is.infinite(self$size))
1136 "Inf"
1137 else if (is.numeric(self$size))
1138 fmt_bytes(self$size)
1139 else
1140 self$size
1141 }
1142
1143 size <- paste(size, cs)
1144 c(
1145 res,
1146 sprintf(" backups: %s/%s", private$bq$n_backups, self$max_backups),
1147 paste(" size:", size)
1148 )
1149 }
1150 ),
1151
1152
1153 active = list(
1154 size = function() get(".size", private),
1155 create_file = function() get(".create_file", private),
1156
1157 compression = function() get("bq", private)$compression,
1158 max_backups = function() get("bq", private)$max_backups,
1159
1160 #' @field backups A `data.frame` containing information on path, file size,
1161 #' etc... on the available backups of `file`.
1162 backups = function() get("bq", private)$files,
1163
1164
1165 backup_dir = function() get("bq", private)$dir
1166 ),
1167
1168
1169 private = list(
1170 .size = NULL,
1171 .create_file = NULL,
1172 bq = NULL
1173 )
1174 )
1175
1176
1177 # AppenderFileRotatingTime ------------------------------------------------
1178
1179 #' Log to a time-stamped rotating file
1180 #'
1181 #' An extension of [AppenderFile] that rotates logfiles based on certain
1182 #' conditions. Please refer to the documentation of [rotor::rotate_time()] for
1183 #' the meanings of the extra arguments
1184 #'
1185 #' @family Appenders
1186 #' @seealso [AppenderFileRotatingDate], [AppenderFileRotating], [rotor::rotate()]
1187 #' @export
1188 AppenderFileRotatingTime <- R6::R6Class(
1189 "AppenderFileRotatingTime",
1190 inherit = AppenderFileRotating,
1191 public = list(
1192
1193 #' @description
1194 #' @param size,age,max_backups,compression,backup_dir,fmt,overwrite,cache_backups
1195 #' see [rotor::rotate_time()] for the meaning of these arguments. Note that
1196 #' `fmt` corresponds to `format` and `backup_dir` to `dir`.
1197 initialize = function(
1198 file,
1199 threshold = NA_integer_,
1200 layout = LayoutFormat$new(),
1201 filters = NULL,
1202
1203 age = Inf,
1204 size = -1,
1205 max_backups = Inf,
1206 compression = FALSE,
1207 backup_dir = dirname(file),
1208 fmt = "%Y-%m-%d--%H-%M-%S",
1209 overwrite = FALSE,
1210 cache_backups = TRUE,
1211 create_file = NULL
1212 ){
1213 assert_namespace("rotor")
1214
1215 if (length(create_file)){
1216 .Deprecated(msg = "The create_file argument is defunct and will be removed from future versions of lgr.")
1217 }
1218
1219 if (!file.exists(file)) file.create(file)
1220
1221 private$bq <- rotor::BackupQueueDateTime$new(file)
1222
1223 self$set_file(file)
1224 self$set_threshold(threshold)
1225 self$set_layout(layout)
1226 self$set_filters(filters)
1227
1228 self$set_fmt(fmt)
1229 self$set_age(age)
1230 self$set_size(size)
1231 self$set_max_backups(max_backups)
1232 self$set_compression(compression)
1233 self$set_overwrite(overwrite)
1234 self$set_backup_dir(backup_dir)
1235 self$set_create_file(TRUE)
1236 self$set_cache_backups(cache_backups)
1237
1238 self
1239 },
1240
1241
1242 rotate = function(
1243 force = FALSE,
1244 now = Sys.time()
1245 ){
1246 assert(is_scalar_bool(force))
1247 bq <- get("bq", private)
1248
1249 if (
1250 force ||
1251 bq$should_rotate(
1252 size = self$size,
1253 age = self$age,
1254 now = now
1255 )
1256 ){
1257 bq$push(
1258 overwrite = self$overwrite,
1259 now = now
1260 )
1261 bq$prune()
1262 file.remove(self$file)
1263 file.create(self$file)
1264 }
1265
1266 self
1267 },
1268
1269
1270 set_age = function(
1271 x
1272 ){
1273 private[[".age"]] <- x
1274 self
1275 },
1276
1277
1278 set_fmt = function(
1279 x
1280 ){
1281 get("bq", private)$set_fmt(x)
1282 self
1283 },
1284
1285
1286 set_overwrite = function(
1287 x
1288 ){
1289 assert(is_scalar_bool(x))
1290 private[[".overwrite"]] <- x
1291 self
1292 },
1293
1294
1295 #' @description set the `cache_backups` flag.
1296 #' @param x a `logical` scalar
1297 set_cache_backups = function(
1298 x
1299 ){
1300 private$bq$set_cache_backups(x)
1301 self
1302 },
1303
1304 format = function(
1305 color = FALSE,
1306 ...
1307 ){
1308 res <- super$format(color = color, ...)
1309
1310 if (!color)
1311 style_subtle <- identity
1312
1313 lr <- private$bq$last_rotation
1314 if (!is.null(lr))
1315 lr <- style_subtle(sprintf(" (last rotation: %s)", format(lr)))
1316 else
1317 lr <- ""
1318
1319 c(
1320 res,
1321 sprintf(" age: %s%s", self$age, lr)
1322 )
1323 }
1324 ),
1325
1326
1327 active = list(
1328 age = function() get(".age", private),
1329 overwrite = function() get(".overwrite", private),
1330 fmt = function() get("bq", private)$fmt,
1331
1332 #' @field cache_backups
1333 #' `TRUE` or `FALSE`. If `TRUE` (the default) the list of backups is cached,
1334 #' if `FALSE` it is read from disk every time this appender triggers.
1335 #' Caching brings a significant speedup for checking whether to rotate or
1336 #' not based on the `age` of the last backup, but is only safe if
1337 #' there are no other programs/functions (except this appender) interacting
1338 #' with the backups.
1339 cache_backups = function() get("bq", private)$cache_backups
1340 ),
1341
1342
1343 private = list(
1344 .age = NULL,
1345 .overwrite = NULL
1346 )
1347 )
1348
1349
1350
1351 # AppenderFileRotatingDate ----------------------------------------------------
1352
1353 #' Log to a date-stamped rotating file
1354 #'
1355 #' This is a simpler version of AppenderFileRotatingTime when the timestamps
1356 #' do not need to include sub-day accuracy.
1357 #'
1358 #' @family Appenders
1359 #' @seealso [AppenderFileRotatingTime], [AppenderFileRotating], [rotor::rotate()]
1360 #' @export
1361 AppenderFileRotatingDate <- R6::R6Class(
1362 "AppenderFileRotatingDate",
1363 inherit = AppenderFileRotatingTime,
1364 public = list(
1365
1366
1367 #' @description
1368 #' @param size,age,max_backups,compression,backup_dir,fmt,overwrite,cache_backups
1369 #' see [rotor::rotate_date()] for the meaning of these arguments. Note that
1370 #' `fmt` corresponds to `format` (because `$format` has a special meaning
1371 #' for R6 classes).
1372 initialize = function(
1373 file,
1374 threshold = NA_integer_,
1375 layout = LayoutFormat$new(),
1376 filters = NULL,
1377
1378 age = Inf,
1379 size = -1,
1380 max_backups = Inf,
1381 compression = FALSE,
1382 backup_dir = dirname(file),
1383 fmt = "%Y-%m-%d",
1384 overwrite = FALSE,
1385 cache_backups = TRUE,
1386 create_file = NULL
1387 ){
1388 assert_namespace("rotor")
1389
1390 if (!file.exists(file)) file.create(file)
1391
1392 if (length(create_file)){
1393 .Deprecated(msg = "The create_file argument is defunct and will be removed from future versions of lgr.")
1394 }
1395
1396 private$bq <- rotor::BackupQueueDate$new(file)
1397
1398 self$set_file(file)
1399 self$set_threshold(threshold)
1400 self$set_layout(layout)
1401 self$set_filters(filters)
1402
1403 self$set_fmt(fmt)
1404 self$set_age(age)
1405 self$set_size(size)
1406 self$set_max_backups(max_backups)
1407 self$set_compression(compression)
1408 self$set_overwrite(overwrite)
1409 self$set_create_file(TRUE)
1410 self$set_backup_dir(backup_dir)
1411 self$set_cache_backups(cache_backups)
1412
1413 self
1414 }
1415 )
1416 )
1417
1418
1419
1420
1421 # print.Appender ----------------------------------------------------------
1422
1423 #' Print an Appender object
1424 #'
1425 #' The `print()` method for Loggers displays the most important aspects of
1426 #' the Appender.
1427 #'
1428 #'
1429 #' @inheritParams print.Logger
1430 #'
1431 #' @return
1432 #' `print()` returns `x` (invisibly), `format()` returns a `character` vector.
1433 #' @export
1434 #'
1435 #' @examples
1436 #' # print most important details of logger
1437 #' print(lgr$console)
1438 print.Appender <- function(
1439 x,
1440 color = requireNamespace("crayon", quietly = TRUE),
1441 ...
1442 ){
1443 assert(is_scalar_bool(color))
1444 cat(format(x, color = color), sep = "\n")
1445 invisible(x)
1446 }
1447
1448
1449
1450
1451 appender_summary <- function(x){
1452 dd <- lapply(x, srs_appender)
1453
1454 if (!length(x)){
1455 return(NULL)
1456 }
1457
1458 if (is.null(names(x))){
1459 names(x) <- ""
1460 }
1461
1462
1463 names(dd) <- ifelse(
1464 is.na(names(x)) | is_blank(names(x)),
1465 paste0("[[", seq_len(length(x)), "]]"),
1466 names(x)
1467 )
1468 dd <- do.call(rbind, dd)
1469
1470 if (is.null(dd)) return(NULL)
1471
1472 dd$name <- rownames(dd)
1473 dd$destination <- ifelse(
1474 !is_blank(dd$destination),
1475 paste("->", dd$destination),
1476 ""
1477 )
1478
1479 with(
1480 dd,
1481 paste0(
1482 pad_right(name), ": ",
1483 pad_right(class), " [",
1484 pad_left(fmt_threshold(threshold, type = "character")), "] ",
1485 destination
1486 )
1487 )
1488 }
1489
1490
1491
1492 # helpers -----------------------------------------------------------------
1493
1494 #' Default reader for files created with AppenderFile
1495 #'
1496 #' @param file a `character` scalar: path to a file
1497 #' @param threshold only `NA` is supported for the default reader, other
1498 #' values cause a warning. See `LayoutFormat$read()` for an example where
1499 #' that supports thresholds.
1500 #' @param n an `integer` scalar > 0
1501 #'
1502 #' @return
1503 #' @noRd
1504 default_file_reader <- function(file, threshold, n){
1505 assert(
1506 is_scalar_character(file),
1507 "`file` must be the path to a file, not ", string_repr(file)
1508 )
1509
1510 if (isFALSE(is.na(threshold))){
1511 warning("A threshold was supplied to AppenderFile$show(), but the ",
1512 "Appenders' Layout does not support filtering by log level")
1513 }
1514
1515 last_n(readLines(file), n)
1516 }
1517
1518
1519
1520 standardize_should_flush_output <- function(
1521 x
1522 ){
1523 if (isTRUE(x)){
1524 TRUE
1525 } else if (isFALSE(x)){
1526 FALSE
1527 } else {
1528 warning(ValueIsNotBoolWarning(paste0(
1529 "`$should_flush()` did not return `TRUE` or `FALSE` but ",
1530 string_repr(x), ". ",
1531 "Please set a valid filter function with `$set_should_flush()`."
1532 )))
1533 FALSE
1534 }
1535 }
1536
1537
1538
1539 # conditions --------------------------------------------------------------
1540
1541 CannotParseLogError <- function(message){
1542 error(message = message, class = "CannotParseLogError")
1543 }
1544
1545
1546
1547 ValueIsNotBoolWarning <- function(message){
1548 condition(message, class = c("ValueIsNotBoolWarning", "warning"))
1549 }