Debian Codegraph @

inst/doc/lgr.R

raw
1 ## ----setup, include = FALSE---------------------------------------------------
2 library(lgr)
3
4 knitr::opts_chunk$set(
5 collapse = TRUE,
6 comment = "#>"
7 )
8
9 ## -----------------------------------------------------------------------------
10 # the root logger is called "lgr"
11 lgr$info("Vampire stories are generally located in Styria.")
12
13 ## -----------------------------------------------------------------------------
14 lgr$error("Vampires generally arrive in carriages drawn by %i black horses.", 2)
15
16 ## -----------------------------------------------------------------------------
17 tf <- tempfile(fileext = ".info")
18 lgr$add_appender(AppenderFile$new(tf), name = "file")
19 lgr$info("You must think I am joking")
20 readLines(tf)
21
22 ## -----------------------------------------------------------------------------
23 lgr$appenders$file$set_layout(LayoutFormat$new(timestamp_fmt = "%B %d %T"))
24 lgr$info("No, I am quite serious")
25 readLines(tf)
26
27 #cleanup
28 unlink(tf)
29
30 ## -----------------------------------------------------------------------------
31 # cleanup behind the old Appender
32 unlink(tf)
33 lgr$remove_appender("file")
34
35 # setup a JSON appender
36 lgr$add_appender(AppenderJson$new(tf), name = "json")
37 lgr$info("We lived in Styria")
38
39 ## -----------------------------------------------------------------------------
40 cat(readLines(tf))
41
42 ## -----------------------------------------------------------------------------
43 read_json_lines(tf)
44
45 ## -----------------------------------------------------------------------------
46 # show is a method and takes some extra arguments, like maximum number of lines
47 # to show
48 lgr$appenders$json$show()
49
50 # $data always returns a data.frame if available. It is an active binding
51 # rather than a method, so no extra arguments are possible
52 lgr$appenders$json$data
53
54 ## -----------------------------------------------------------------------------
55 # The default console appender displays custom fields as pseudo-json after the message
56 lgr$info("Styria has", poultry = c("capons", "turkeys"))
57
58 # JSON can store most R objects quite naturally
59 read_json_lines(tf)
60 read_json_lines(tf)$poultry[[2]] # works because poultry is a list column
61
62 ## ----echo = FALSE-------------------------------------------------------------
63 lgr$remove_appender("json")
64 unlink(tf)
65
66 ## ----echo = FALSE-------------------------------------------------------------
67 ll <- data.frame(
68 `Level` = c(0, seq(100, 600, by = 100), NA),
69 `Name` = c("off", "fatal", "error", "warn", "info", "debug", "trace", "all"),
70 `Description` = c(
71 "Tells a Logger or Appender to suspend all logging",
72 "Critical error that leads to program abort. Should always indicate a `stop()` or similar",
73 "A severe error that does not trigger program abort",
74 "A potentially harmful situation, like `warning()`",
75 "An informational message on the progress of the application",
76 "Finer grained informational messages that are mostly useful for debugging",
77 "An even finer grained message than debug ([more info](https://softwareengineering.stackexchange.com/questions/279690/why-does-the-trace-level-exist-and-when-should-i-use-it-rather-than-debug))",
78 "Tells a Logger or Appender to process all log events"
79 )
80 )
81
82 knitr::kable(ll)
83
84 ## -----------------------------------------------------------------------------
85 lgr$fatal("This is an important message about %s going wrong", "->something<-")
86 lgr$trace("Trace messages are still hidden")
87 lgr$set_threshold("trace")
88 lgr$trace("Unless we lower the threshold")
89
90
91 ## -----------------------------------------------------------------------------
92 lgr$info("The sky was the color of %s, tuned to a dead chanel", "television")
93
94 ## -----------------------------------------------------------------------------
95 lgr$info("Vampire stories are generally located in Styria")
96 lgr$last_event # a summary output of the event
97 lgr$last_event$values # all values stored in the event as a list
98
99 ## -----------------------------------------------------------------------------
100 # bad
101 lgr$info("Processing track '%s' with %s waypoints", "track.gpx", 32)
102
103 # Good
104 tf <- tempfile()
105 lgr$add_appender(AppenderJson$new(tf), "json")
106 lgr$info("Processing track", file = "track.gpx", waypoints = 32)
107 lgr$appenders$json$data
108
109
110 ## ----echo = FALSE-------------------------------------------------------------
111 lgr$remove_appender("json")
112 unlink(tf)
113
114 ## -----------------------------------------------------------------------------
115 f1 <- function(event) { grepl("bird", event$msg) }
116 lgr$set_filters(list(f1))
117
118 lgr$info("is it a plane?")
119 lgr$info("no! is it a bird?")
120
121 # since this is not a very useful filter, we better remove it again
122 lgr$set_filters(NULL)
123
124 ## -----------------------------------------------------------------------------
125 tf <- tempfile()
126
127 # Add a new appender to a logger. We don't have to supply a name, but that
128 # makes it easier to remove later.
129 lgr$add_appender(AppenderFile$new(file = tf), name = "file")
130
131 # configure lgr so that it logs everything to the file, but only info and above
132 # to the console
133 lgr$set_threshold(NA)
134 lgr$appenders$console$set_threshold("info")
135 lgr$appenders$file$set_threshold(NA)
136 lgr$info("Another informational message")
137 lgr$debug("A debug message not shown by the console appender")
138
139 readLines(tf)
140
141 # Remove the appender again
142 lgr$remove_appender("file")
143 unlink(tf)
144
145 ## -----------------------------------------------------------------------------
146 # install.packages("glue")
147
148 lg <- get_logger_glue("glue/logger")
149
150 lg$info(
151 "glue automatically ",
152 "pastes together unnamed arguments ",
153 "and evaluates arbitray expressions inside braces {Sys.Date()}"
154 )
155
156
157 ## -----------------------------------------------------------------------------
158 lg$info("For more info on glue see {website}", website = "https://glue.tidyverse.org/")
159
160 ## -----------------------------------------------------------------------------
161 lg$info("Glue is available from {.cran}", .cran = "https://CRAN.R-project.org/package=glue")
162
163 ## -----------------------------------------------------------------------------
164 lg <- get_logger("test")
165 lg$config(NULL) # resets logger to unconfigured state
166 lg$set_threshold("fatal")
167
168 ## -----------------------------------------------------------------------------
169 lg$
170 set_threshold("info")$
171 set_appenders(AppenderConsole$new(threshold = "info"))$
172 set_propagate(FALSE)
173
174 ## -----------------------------------------------------------------------------
175 lg$config(list(
176 threshold = "info",
177 propagate = FALSE,
178 appenders = AppenderConsole$new(threshold = "info")
179 ))
180
181 ## ----eval = FALSE-------------------------------------------------------------
182 # lg$config("path/to/config.yaml")
183 # lg$config("path/to/config.json")
184
185 ## -----------------------------------------------------------------------------
186 # Via YAML
187 cfg <- "
188 Logger:
189 threshold: info
190 propagate: false
191 appenders:
192 AppenderConsole:
193 threshold: info
194 "
195 lg$config(cfg)
196
197 ## -----------------------------------------------------------------------------
198 lg <- get_logger("test")
199 lg$set_appenders(list(cons = AppenderConsole$new()))
200 lg$set_propagate(FALSE)
201
202
203 lg$info("the default format")
204 lg$appenders$cons$layout$set_fmt("%L (%n) [%t] %c(): !! %m !!")
205 lg$info("A more involved custom format")
206
207 ## -----------------------------------------------------------------------------
208 # install.packages("glue")
209 library(glue)
210 lg$appenders$cons$set_layout(LayoutGlue$new(
211 fmt = "{.logger$name} {level_name} {caller}: {toupper(msg)}"
212 ))
213 lg$info("with glue")
214
215 ## -----------------------------------------------------------------------------
216 # install.packages("jsonlite")
217 tf <- tempfile()
218
219 lg <- get_logger("test")
220
221 lg$set_appenders(list(json = AppenderJson$new(file = tf)))
222 lg$set_propagate(FALSE)
223
224 lg$info("JSON naturally ", field = "custom")
225 lg$info("supports custom", numbers = 1:3)
226 lg$info("log fields", use = "JSON")
227
228
229 ## ----eval = FALSE-------------------------------------------------------------
230 # lg$appenders$json$data
231 # # same as
232 # read_json_lines(tf)
233
234 ## ----echo = FALSE-------------------------------------------------------------
235 lg$appenders$json$data
236
237 ## ----eval = FALSE-------------------------------------------------------------
238 # lg$appenders$json$show()
239 # # same as
240 # cat(readLines(tf), sep = "\n")
241
242 ## ----echo = FALSE-------------------------------------------------------------
243 lg$appenders$json$show()
244
245 ## -----------------------------------------------------------------------------
246 # cleanup
247 lg$config(NULL)
248 unlink(tf)
249
250 ## -----------------------------------------------------------------------------
251 # install.packages("rotor")
252 tf <- tempfile(fileext = ".log")
253
254 lg <- get_logger("test")$
255 set_propagate(FALSE)$
256 set_appenders(list(rotating = AppenderFileRotating$new(
257 file = tf,
258 size = "10 kb",
259 max_backups = 5))
260 )
261
262 for (i in 1:100) lg$info(paste(LETTERS, sep = "-"))
263
264 # display info on the backups of tf
265 lg$appenders$rotating$backups
266
267 # manually delete all backups
268 invisible(lg$appenders$rotating$prune(0))
269 lg$appenders$rotating$backups
270
271 #cleanup
272 unlink(tf)
273
274 ## -----------------------------------------------------------------------------
275 # The logger name should be the same as the package name
276 tf <- tempfile()
277 lg <- get_logger("mypackage")
278 lg$add_appender(AppenderFile$new(tf))
279
280 ## -----------------------------------------------------------------------------
281 print(lg)
282
283 ## -----------------------------------------------------------------------------
284 lg$info("A test message for lg")
285
286 ## -----------------------------------------------------------------------------
287 lg$set_propagate(FALSE)
288
289 ## -----------------------------------------------------------------------------
290 print(lg)
291
292 ## -----------------------------------------------------------------------------
293 lg$info("Nothing to see here")
294
295 ## -----------------------------------------------------------------------------
296 # cleanup
297 lg$config(NULL)
298 unlink(tf)
299
300 ## -----------------------------------------------------------------------------
301 lg <- get_logger("buffer")
302
303 lg$
304 set_threshold(NA)$
305 set_propagate(FALSE)$
306 set_appenders(
307 AppenderBuffer$new(
308 threshold = NA,
309 buffer_size = 5, # can hold 5 events, the 6th will trigger flushing
310 flush_on_exit = FALSE,
311 flush_on_rotate = FALSE,
312 flush_threshold = "error",
313 appenders = AppenderConsole$new(threshold = NA)
314 ))
315
316 # The for loop below stores 8 log events in the Buffer
317 for (nm in month.name[1:8]) lg$debug("%s", nm)
318
319 # An event of level 'error' or 'fatal' triggers flushing of the buffer
320 lg$error("But the days grow short when you reach September")
321
322 ## ----eval = FALSE-------------------------------------------------------------
323 # # install.packages("RSQLite")
324 # # install.packages("lgrExtra")
325 # lg <- get_logger("db_logger")
326 # lg$
327 # set_propagate(FALSE)$
328 # add_appender(
329 # name = "db",
330 # lgrExtra::AppenderDbi$new(
331 # conn = DBI::dbConnect(RSQLite::SQLite()),
332 # table = "log",
333 # buffer_size = 2L
334 # )
335 # )
336 #
337 # lg$info("Logging to databases uses a buffer")
338 # lg$info("As the buffer size is 2, no insert took place till now")
339 # lg$appenders$db$show()
340 #
341 # lg$info("Now as the buffer is rotated, all events are output to the db")
342 # lg$appenders$db$show()
343
344 ## -----------------------------------------------------------------------------
345 # setup an example function
346 clean <- function() lgr$info("cleaning data")
347 process <- function() lgr$info("processing data")
348 output <- function() lgr$info("outputing data")
349
350 analyze <- function(){
351 clean()
352 process()
353 output()
354 }
355
356 ## ----eval = FALSE-------------------------------------------------------------
357 # with_log_value(
358 # list(dataset_id = "dataset1"),
359 # analyze()
360 # )
361
362 ## ----eval = FALSE-------------------------------------------------------------
363 # analyze <- function(id = "dataset1"){
364 # lgr$add_filter(FilterInject$new(dataset_id = id), name = "inject")
365 # on.exit(lgr$remove_filter("inject"))
366 #
367 # clean()
368 # process()
369 # output()
370 # }
371 # analyze()
372
373 ## ----echo = FALSE-------------------------------------------------------------
374 with_log_value(
375 list(dataset_id = "dataset1"),
376 analyze()
377 )
378
379 ## -----------------------------------------------------------------------------
380 without_logging({
381 lgr$warn("Oh Yeah?")
382 lgr$fatal("Oh No")
383 })
384
385 ## -----------------------------------------------------------------------------
386 # mypackage/R/mypackage-package.R
387 .onLoad <- function(...){
388 assign(
389 "lg", # the recommended name for a logger object
390 lgr::get_logger(name = "mypackage"), # should be the same as the package name
391 envir = parent.env(environment())
392 )
393 }
394
395
396 ## ----eval = FALSE-------------------------------------------------------------
397 # # install.packages("this.path")
398 #
399 # lg <- get_logger("srcfile")
400 # lg$add_filter(function(event){
401 # tryCatch({
402 # event$srcfile <- this.path::this.path()
403 # }, error = function(e) NULL)
404 # TRUE
405 # })
406