Debian Codegraph @

R/simple_logging.R

raw
1 #' Simple Logging
2 #'
3 #' lgr provides convenience functions managing the root Logger. These are
4 #' designed chiefly for interactive use and are less verbose than their
5 #' R6 method counterparts.
6 #'
7 #' @name simple_logging
8 #'
9 NULL
10
11
12
13
14
15 # logging -----------------------------------------------------------------
16
17 #' @inheritParams with_log_value
18 #' @param logfun a `function` for processing the log request, usually
19 #' `lgr$info()`, `lgr$debug()`, etc... .
20 #' @param caller a `character` scalar. The name of the calling function
21 #'
22 #' @export
23 #' @rdname simple_logging
24 log_exception <- function(
25 code,
26 logfun = lgr$fatal,
27 caller = get_caller(-3)
28 ){
29 force(caller)
30 force(logfun)
31 tryCatch(
32 force(code),
33 error = function(e){
34 logfun(unlist(strsplit(e$message, split = "\n", fixed = TRUE)), caller = caller)
35 stop(e)
36 }
37 )
38 }
39
40
41
42
43 # managment ---------------------------------------------------------------
44
45 #' @param target a [Logger] or [Appender] or the name of a Logger as `character`
46 #' scalar
47 #'
48 #' @description
49 #' `threshold()` sets or retrieves the threshold for an [Appender] or [Logger]
50 #' (the minimum level of log messages it processes). It's `target` defaults to
51 #' the root logger. (equivalent to `lgr::lgr$threshold` and
52 #' `lgr::lgr$set_threshold`)
53 #'
54 #' `console_threshold()` is a shortcut to set the threshold of the root
55 #' loggers [AppenderConsole], which is usually the only Appender that manages
56 #' console output for a given \R session. (equivalent to
57 #' `lgr::lgr$appenders$console$threshold` and
58 #' `lgr::lgr$appenders$console$set_threshold`)
59 #'
60 #' `add_appender()` and `remove_appender()` add Appenders to Loggers and other
61 #' Appenders. (equivalent to `lgr::lgr$add_appender` and
62 #' `lgr::lgr$remove_appender`)
63 #'
64 #' @rdname simple_logging
65 #' @return
66 #' `threshold()` and `console_threshold()` return the [log_level] of `target`
67 #' as `integer` (invisibly)
68 #'
69 #' @export
70 #'
71 #'
72 #' @examples
73 #' # Get and set the threshold of the root logger
74 #' threshold("error")
75 #' threshold()
76 #' lgr$info("this will be supressed")
77 #' lgr$error("an important error message")
78 #'
79 #' # you can also specify a target to modify other loggers
80 #' lg <- get_logger("test")
81 #' threshold("fatal", target = lg)
82 #' threshold(target = lg)
83 #'
84 #' # If a Logger's threshold is not set, the threshold is inherited from
85 #' # its parent, in this case the root logger (that we set to error/200 before)
86 #' threshold(NULL, target = lg)
87 #' threshold(target = lg)
88 #'
89 #' # Alternative R6 API for getting/setting thresholds
90 #' lg$set_threshold("info")
91 #' lg$threshold
92 #' lg$set_threshold(300)
93 #' lg$threshold
94 #' lg$set_threshold(NULL)
95 #' lg$threshold
96 #'
97 #' # cleanup
98 #' lgr$config(NULL)
99 #' lg$config(NULL)
100 threshold <- function(
101 level,
102 target = lgr::lgr
103 ){
104 if (missing(level))
105 return(target[["threshold"]])
106 else
107 target$set_threshold(level)
108
109 invisible(target$threshold)
110 }
111
112
113
114
115 #' @rdname simple_logging
116 #' @export
117 console_threshold <- function(
118 level,
119 target = lgr::lgr$appenders$console
120 ){
121 assert(inherits(target, "AppenderConsole"))
122 if (missing(level))
123 target$threshold
124 else
125 target$set_threshold(level)
126
127 invisible(target$threshold)
128 }
129
130
131
132
133 #' @rdname simple_logging
134 #' @param appender an `Appender`
135 #' @param name `character` scalar. An optional name for the new Appender.
136 #' @return `add_appender()` and `remove_appender()` return `target`.
137 #' @export
138 #' @examples
139 #'
140 #'
141 #' # add Appenders to a Logger
142 #' add_appender(AppenderConsole$new(), "second_console_appender")
143 #' lgr$fatal("Multiple console appenders are a bad idea")
144 #' remove_appender("second_console_appender")
145 #' lgr$info("Good that we defined an appender name, so it's easy to remove")
146 add_appender <- function(
147 appender,
148 name = NULL,
149 target = lgr::lgr
150 ){
151 target$add_appender(appender, name = name)
152 }
153
154
155
156
157 #' @param pos `integer` index or `character` names of the appenders to remove
158 #' @rdname simple_logging
159 #' @export
160 remove_appender <- function(
161 pos,
162 target = lgr::lgr
163 ){
164 target$remove_appender(pos)
165 }
166
167
168
169
170 #' @description
171 #' `show_log()` displays the last `n` log entries of an Appender (or a Logger
172 #' with such an Appender attached) with a `$show()` method. Most, but not all
173 #' Appenders support this function (try [AppenderFile] or [AppenderBuffer]).
174 #'
175 #' `show_data()` and `show_dt()` work similar to `show_log()`, except that
176 #' they return the log as `data.frame` or `data.table` respectively. Only
177 #' Appenders that log to formats that can easily be converted to `data.frames`
178 #' are supported (try [AppenderJson] or [AppenderBuffer]).
179 #'
180 #' The easiest way to try out this features is by adding an AppenderBuffer
181 #' to the root logger with [`basic_config(memory = TRUE)`][basic_config()].
182 #'
183 #' @param n `integer` scalar. Show only the last `n` log entries that match
184 #' `threshold`
185 #'
186 #' @inheritParams basic_config
187 #'
188 #' @return `show_log()` prints to the console and returns whatever the target
189 #' Appender's `$show()` method returns, usually a `character` vector,
190 #' `data.frame` or `data.table` (invisibly).
191 #'
192 #' `show_data()` always returns a `data.frame` and `show_dt()` always returns
193 #' a `data.table`.
194 #' @rdname simple_logging
195 #' @export
196 #'
197 #' @examples
198 #'
199 #' # Reconfigure the root logger
200 #' basic_config(memory = TRUE)
201 #'
202 #' # log some messages
203 #' lgr$info("a log message")
204 #' lgr$info("another message with data", data = 1:3)
205 #'
206 #' show_log()
207 #' show_data()
208 #'
209 #' # cleanup
210 #' lgr$config(NULL)
211 show_log <- function(
212 threshold = NA_integer_,
213 n = 20L,
214 target = lgr::lgr
215 ){
216 dd <- find_target(target, "show")
217 dd$show(n = n, threshold = threshold)
218 }
219
220
221
222
223 #' @rdname simple_logging
224 #' @export
225 show_dt <- function(
226 target = lgr::lgr
227 ){
228 tryCatch(
229 find_target(target, "dt")[["dt"]],
230 error = function(e){
231 data.table::as.data.table(find_target(target, "data")[["data"]])
232 }
233 )
234 }
235
236
237
238
239 #' @rdname simple_logging
240 #' @export
241 show_data <- function(
242 target = lgr::lgr
243 ){
244 dd <- find_target(target, "data")
245 as.data.frame(dd$data)
246 }
247
248
249
250
251 #' Return the first Appender that has a method or field called `name`
252 #'
253 #' @param x a [Logger] or [Appender]
254 #' @param name
255 #'
256 #' @return an Appender
257 #' @noRd
258 find_target <- function(
259 x,
260 name
261 ){
262 assert(is_scalar_character(name))
263
264 if (is_scalar_character(x)) {
265 x <- get_logger(x)
266 }
267
268 if (inherits(x, "Appender")){
269 if (name %in% names(x)){
270 return(x)
271 } else {
272 stop(
273 "This ", class_fmt(x, c("R6", "Filterable", "Appender")),
274 " has no method or field called `", name, "`"
275 )
276 }
277
278 } else if (inherits(x, "Logger")){
279 for (app in x$appenders){
280 res <- try(find_target(app, name), silent = TRUE)
281 if (inherits(res, "Appender")) return(res)
282 }
283 stop(
284 "This ", class_fmt(x, c("R6", "Filterable")),
285 " has no Appender with a field or method called `", name, "`"
286 )
287 } else {
288 stop("`x` is not a Logger or Appender")
289 }
290 }
291
292
293
294
295 # simple setup ------------------------------------------------------------
296
297 default_appenders <- function(
298 ){
299 log_files <- getOption("lgr.log_file", NULL)
300 thresholds <- names(log_files)
301
302 if (is.null(thresholds)){
303 thresholds <- rep(NA, length(log_files))
304 }
305
306 lf <- lapply(seq_along(log_files), function(i){
307 tryCatch(
308 setup_file_appender(log_files[[i]], thresholds[[i]]),
309 error = function(e){
310 warning(
311 sprintf(paste(
312 "Cannot setup logfile '%s' as specified in the global options:",
313 "%s\nSee '?lgr' for help."),
314 log_files[[i]], e)
315 )
316 NULL
317 }
318 )
319 })
320 }
321
322
323
324
325 setup_file_appender <- function(path, threshold = NA){
326
327 if (grepl("\\.json.*", path)){
328 lo <- LayoutJson$new()
329 } else {
330 lo <- LayoutFormat$new()
331 }
332
333 AppenderFile$new(file = path, threshold = threshold, layout = lo)
334 }