| 1 |
--- |
| 2 |
title: "lgr: A fully featured logging framework for R" |
| 3 |
author: "Stefan Fleck" |
| 4 |
date: "`r Sys.Date()`" |
| 5 |
output: |
| 6 |
rmarkdown::html_vignette: |
| 7 |
toc: true |
| 8 |
number_sections: true |
| 9 |
vignette: > |
| 10 |
%\VignetteIndexEntry{lgr} |
| 11 |
%\VignetteEncoding{UTF-8} |
| 12 |
%\VignetteEngine{knitr::rmarkdown} |
| 13 |
editor_options: |
| 14 |
chunk_output_type: console |
| 15 |
--- |
| 16 |
|
| 17 |
```{r setup, include = FALSE} |
| 18 |
library(lgr) |
| 19 |
|
| 20 |
knitr::opts_chunk$set( |
| 21 |
collapse = TRUE, |
| 22 |
comment = "#>" |
| 23 |
) |
| 24 |
``` |
| 25 |
|
| 26 |
# Introduction |
| 27 |
|
| 28 |
lgr is a logging framework for R inspired by |
| 29 |
[Apache Log4j](https://logging.apache.org/log4j/2.x/) and |
| 30 |
[Python logging](https://docs.python.org/3/library/logging.html). |
| 31 |
It follows an object oriented design implemented through |
| 32 |
[R6 classes](https://github.com/r-lib/R6). This enables lgr to have a larger |
| 33 |
set of features than other logging packages for R, and makes it flexible and |
| 34 |
easy to extend. |
| 35 |
|
| 36 |
If you are not sure if lgr is the right package for you, take a look |
| 37 |
[examples](#examples) to see what lgr can do for you. |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
## Quickstart |
| 43 |
|
| 44 |
lgr comes with a so-called **root logger** that is ready to go after you install |
| 45 |
it. If you are a package developer you can (and should) set up a new Logger for |
| 46 |
your package, but more on that later. For many use cases the root Logger will |
| 47 |
suffice. |
| 48 |
|
| 49 |
|
| 50 |
### Logging to the console |
| 51 |
```{r} |
| 52 |
# the root logger is called "lgr" |
| 53 |
lgr$info("Vampire stories are generally located in Styria.") |
| 54 |
``` |
| 55 |
|
| 56 |
You can use formatting strings that are passed on to `sprintf()` in lgr. |
| 57 |
```{r} |
| 58 |
lgr$error("Vampires generally arrive in carriages drawn by %i black horses.", 2) |
| 59 |
``` |
| 60 |
|
| 61 |
|
| 62 |
### Logging to plaintext files |
| 63 |
|
| 64 |
Usually you don't (only) want to log to the console, you want to log to files. |
| 65 |
Output of Loggers is managed by Appenders. The root Logger is preconfigured |
| 66 |
with a console Appender (that is why we see output in the console). Let's |
| 67 |
add a file Appender: |
| 68 |
|
| 69 |
```{r} |
| 70 |
tf <- tempfile(fileext = ".info") |
| 71 |
lgr$add_appender(AppenderFile$new(tf), name = "file") |
| 72 |
lgr$info("You must think I am joking") |
| 73 |
readLines(tf) |
| 74 |
``` |
| 75 |
The various Appenders available in lgr are R6 classes. To instantiate an object |
| 76 |
of that class (i.e. create a new appender) you have to use the `$new()` function |
| 77 |
as in the example above. Whenever you see something in lgr that |
| 78 |
`IsNamedLikeThis`, you can be sure that it is such an R6 class. |
| 79 |
|
| 80 |
If you look at the output, you see that the timestamp format of the file |
| 81 |
appender is slightly different to the timestamp format of the console Appender. |
| 82 |
Formatting is handled by **Layouts**, and each Appender has exactly one: |
| 83 |
|
| 84 |
```{r} |
| 85 |
lgr$appenders$file$set_layout(LayoutFormat$new(timestamp_fmt = "%B %d %T")) |
| 86 |
lgr$info("No, I am quite serious") |
| 87 |
readLines(tf) |
| 88 |
|
| 89 |
#cleanup |
| 90 |
unlink(tf) |
| 91 |
``` |
| 92 |
|
| 93 |
|
| 94 |
### Logging to JSON files |
| 95 |
|
| 96 |
If you log to files, you should not log normal text. If you want to analyse |
| 97 |
your logs later, it's much better to log to a format like JSON: |
| 98 |
|
| 99 |
```{r} |
| 100 |
# cleanup behind the old Appender |
| 101 |
unlink(tf) |
| 102 |
lgr$remove_appender("file") |
| 103 |
|
| 104 |
# setup a JSON appender |
| 105 |
lgr$add_appender(AppenderJson$new(tf), name = "json") |
| 106 |
lgr$info("We lived in Styria") |
| 107 |
``` |
| 108 |
|
| 109 |
JSON is still somewhat human readable |
| 110 |
```{r} |
| 111 |
cat(readLines(tf)) |
| 112 |
``` |
| 113 |
|
| 114 |
and easy for machines to parse |
| 115 |
```{r} |
| 116 |
read_json_lines(tf) |
| 117 |
``` |
| 118 |
|
| 119 |
Many Appenders provide either a `$show()` method and a `$data` active |
| 120 |
binding convenience, and so you do not have to call `readLines()` & co manually. |
| 121 |
|
| 122 |
```{r} |
| 123 |
# show is a method and takes some extra arguments, like maximum number of lines |
| 124 |
# to show |
| 125 |
lgr$appenders$json$show() |
| 126 |
|
| 127 |
# $data always returns a data.frame if available. It is an active binding |
| 128 |
# rather than a method, so no extra arguments are possible |
| 129 |
lgr$appenders$json$data |
| 130 |
``` |
| 131 |
|
| 132 |
Please note that under the hood, `AppenderJson` is just an `AppenderFile` with |
| 133 |
`LayoutJson`. The only difference is AppenderJson provides a `$data()` method |
| 134 |
while AppenderFile does not. |
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
### Structured Logging (custom fields) |
| 139 |
|
| 140 |
lgr treats a *LogEvent* as a unit of data, |
| 141 |
not just a message with a timestamp. A log event can contain arbitrary data, |
| 142 |
though not all Appenders can handle that well. The JSON appender we added |
| 143 |
above is particularly good at handling most R objects. |
| 144 |
|
| 145 |
```{r} |
| 146 |
# The default console appender displays custom fields as pseudo-json after the message |
| 147 |
lgr$info("Styria has", poultry = c("capons", "turkeys")) |
| 148 |
|
| 149 |
# JSON can store most R objects quite naturally |
| 150 |
read_json_lines(tf) |
| 151 |
read_json_lines(tf)$poultry[[2]] # works because poultry is a list column |
| 152 |
``` |
| 153 |
|
| 154 |
```{r echo = FALSE} |
| 155 |
lgr$remove_appender("json") |
| 156 |
unlink(tf) |
| 157 |
``` |
| 158 |
|
| 159 |
|
| 160 |
### What Else |
| 161 |
|
| 162 |
If the examples above have piqued your interest, the rest of this vignette |
| 163 |
will provide more details on the workings of lgr. Discussing all Appenders |
| 164 |
and configuration options is beyond the scope of this vignette, please refer |
| 165 |
to the [function reference](https://s-fleck.github.io/lgr/reference/index.html) |
| 166 |
for that. |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
# Usage |
| 171 |
|
| 172 |
## Structure of the logging system |
| 173 |
|
| 174 |
If you want custom logging configurations, you have to understand the structure |
| 175 |
of the logging process. |
| 176 |
|
| 177 |
* A **Logger** collects information and dispatches it to its *Appenders*, and |
| 178 |
also the *Appenders* of its *Parent Loggers* (also see the section on |
| 179 |
hierarchical logging) |
| 180 |
* An **Appender** writes the log message to destination (the console, a file, |
| 181 |
a database, etc...). |
| 182 |
* A **Layout** is used by an Appender to format LogEvents. For example, |
| 183 |
`AppenderFile` uses `LayoutFormat` by default to write human readable log |
| 184 |
events to a text file, but can also use `LayoutJson` produce machine |
| 185 |
readable JSON lines logfiles. |
| 186 |
* **LogEvents** are produced by the Logger and dispatched to Appenders. They |
| 187 |
contain all the information that is being logged (think of |
| 188 |
it as a row in table). LogEvents usually contain the log level, a timestamp, |
| 189 |
a message, the name of the calling function, and a |
| 190 |
[reference](https://adv-r.hadley.nz/r6.html#r6-semantics]) to the Logger |
| 191 |
that created it. In addition, a LogEvent can contain any number of custom |
| 192 |
fields. See [examples 1 & 2](#examples) |
| 193 |
|
| 194 |
|
| 195 |
### On R6 classes |
| 196 |
|
| 197 |
The elements described above are R6 classes. R6 is an object orientation |
| 198 |
system for R that is used by many popular packages such as shiny, dplyr, |
| 199 |
plumber, roxygen2, and testthat but often behind the scenes and not as exposed |
| 200 |
as in lgr. |
| 201 |
|
| 202 |
You recognize R6 classes in this package because they are named following the |
| 203 |
`UpperCamelCase` naming convention. While there is only one kind of Logger and |
| 204 |
one kind of LogEvent, there are several subclasses of Appenders and Layouts. |
| 205 |
|
| 206 |
An introduction to R6 classes is beyond the scope of this document, but you |
| 207 |
can find the official documentation [here](https://r6.r-lib.org/) and there is |
| 208 |
also this [talk on Youtube](https://www.youtube.com/watch?v=3GEFd8rZQgY). In |
| 209 |
short R6 classes store data (fields) together with functions (methods) and |
| 210 |
have to be instantiated with `<classname>$new()`. So if you want to create |
| 211 |
a new `AppenderFile`, you do this by calling |
| 212 |
`AppenderFile$new(file = tempfile())`. |
| 213 |
|
| 214 |
Please not that Loggers should never be instantiated directly with `$new()` but |
| 215 |
always with `get_logger()`. |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
## Log levels |
| 220 |
|
| 221 |
lgr supports the standard log4j Log Levels outlined bellow. The Log Level of |
| 222 |
an event represents its severity. The named log levels are really just |
| 223 |
nicknames for integer values, and you can use the `character` or `integer` |
| 224 |
representations interchangeably. You can also use arbitrary integer values |
| 225 |
(greater than `0`), but you are encouraged to stick to the ones bellow. |
| 226 |
|
| 227 |
```{r, echo = FALSE} |
| 228 |
ll <- data.frame( |
| 229 |
`Level` = c(0, seq(100, 600, by = 100), NA), |
| 230 |
`Name` = c("off", "fatal", "error", "warn", "info", "debug", "trace", "all"), |
| 231 |
`Description` = c( |
| 232 |
"Tells a Logger or Appender to suspend all logging", |
| 233 |
"Critical error that leads to program abort. Should always indicate a `stop()` or similar", |
| 234 |
"A severe error that does not trigger program abort", |
| 235 |
"A potentially harmful situation, like `warning()`", |
| 236 |
"An informational message on the progress of the application", |
| 237 |
"Finer grained informational messages that are mostly useful for debugging", |
| 238 |
"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))", |
| 239 |
"Tells a Logger or Appender to process all log events" |
| 240 |
) |
| 241 |
) |
| 242 |
|
| 243 |
knitr::kable(ll) |
| 244 |
``` |
| 245 |
|
| 246 |
`off` and `all` are valid thresholds for Appenders and Loggers, |
| 247 |
but not valid levels for LogEvents; e.g. `lgr$set_threshold(NA)` makes sense, |
| 248 |
but `lgr$log("all", "an example message")` does not. |
| 249 |
|
| 250 |
The list of named log levels is stored as a global option |
| 251 |
(`getOption("lgr.log_levels")`) and you can use `add_log_levels()` and |
| 252 |
`remove_log_levels()` to define your own named levels if you want to. |
| 253 |
There are only predefined logging methods (`lgr$fatal()`, etc..) for the |
| 254 |
standard log levels and you have to use `lgr$log(level, message)` to create |
| 255 |
a LogEvent with a custom log level. |
| 256 |
|
| 257 |
|
| 258 |
## Logging with the Root Logger |
| 259 |
|
| 260 |
lgr comes with a pre-configured root Logger. It is called *root* because |
| 261 |
you can [set up a tree of Loggers](#hierarchy) that descent from it, but for |
| 262 |
basic use you will not have to worry about that. |
| 263 |
|
| 264 |
|
| 265 |
### Logging syntax |
| 266 |
|
| 267 |
lgr Loggers are R6 objects with *methods* (functions) for logging. You can refer |
| 268 |
to the *root* logger with `lgr`. |
| 269 |
|
| 270 |
```{r} |
| 271 |
lgr$fatal("This is an important message about %s going wrong", "->something<-") |
| 272 |
lgr$trace("Trace messages are still hidden") |
| 273 |
lgr$set_threshold("trace") |
| 274 |
lgr$trace("Unless we lower the threshold") |
| 275 |
|
| 276 |
``` |
| 277 |
|
| 278 |
### Formatting strings |
| 279 |
|
| 280 |
You can use `sprintf()` style formatting strings directly in log messages. |
| 281 |
```{r} |
| 282 |
lgr$info("The sky was the color of %s, tuned to a dead chanel", "television") |
| 283 |
``` |
| 284 |
|
| 285 |
|
| 286 |
## LogEvents: The atomic unit of logging |
| 287 |
|
| 288 |
LogEvents are objects that store all information collected by the Logger. They |
| 289 |
are passed on to Appenders that output them, but Appenders usually don't |
| 290 |
utilize all the information present in a log event. The last event produced |
| 291 |
by a Logger is stored in its `last_event` field. |
| 292 |
|
| 293 |
```{r} |
| 294 |
lgr$info("Vampire stories are generally located in Styria") |
| 295 |
lgr$last_event # a summary output of the event |
| 296 |
lgr$last_event$values # all values stored in the event as a list |
| 297 |
``` |
| 298 |
|
| 299 |
LogEvents can contain not only these standard values, but an arbitrary number |
| 300 |
of extra values. These extra values are passed as named arguments to the logging |
| 301 |
function (as opposed as to parameters to `sprintf()`, which are passed as |
| 302 |
unnamed arguments). It is up to the Appender whether to process them further or |
| 303 |
not. |
| 304 |
|
| 305 |
You should consider making use of structured logging liberally and using output |
| 306 |
formats that support them (such as JSON), rather than producing elaborately |
| 307 |
formatted but hard to parse log messages. |
| 308 |
|
| 309 |
```{r} |
| 310 |
# bad |
| 311 |
lgr$info("Processing track '%s' with %s waypoints", "track.gpx", 32) |
| 312 |
|
| 313 |
# Good |
| 314 |
tf <- tempfile() |
| 315 |
lgr$add_appender(AppenderJson$new(tf), "json") |
| 316 |
lgr$info("Processing track", file = "track.gpx", waypoints = 32) |
| 317 |
lgr$appenders$json$data |
| 318 |
|
| 319 |
``` |
| 320 |
```{r echo = FALSE} |
| 321 |
lgr$remove_appender("json") |
| 322 |
unlink(tf) |
| 323 |
``` |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
## Thresholds & Filters: controlling output detail {#thresholds} |
| 329 |
|
| 330 |
To control the level of detail of the log output, you can set **thresholds** for |
| 331 |
Loggers and Appenders. A Logger with a threshold of `warn` will only create |
| 332 |
LogEvents of the priorities `warn`, `error` and `fatal` and dispatch them |
| 333 |
to its Appenders. |
| 334 |
|
| 335 |
> A **threshold** of a Logger or Appender is the minimum **log level** a |
| 336 |
> LogEvent must have so that that Logger/Appender processes it. |
| 337 |
|
| 338 |
If you require more complex logic to decide whether a LogEvent should be |
| 339 |
created/processed you can also assign **filters** to Loggers/Appenders. |
| 340 |
Filters are just functions that have exactly one argument, |
| 341 |
`event` (the LogEvent to be filtered), and return `TRUE` or `FALSE`. They |
| 342 |
will be applied after the threshold is checked. Alternatively there is also a |
| 343 |
formal R6 class for Filters (?EventFilter) that you can use, but this is usually |
| 344 |
not necessary. |
| 345 |
|
| 346 |
examples: |
| 347 |
```{r} |
| 348 |
f1 <- function(event) { grepl("bird", event$msg) } |
| 349 |
lgr$set_filters(list(f1)) |
| 350 |
|
| 351 |
lgr$info("is it a plane?") |
| 352 |
lgr$info("no! is it a bird?") |
| 353 |
|
| 354 |
# since this is not a very useful filter, we better remove it again |
| 355 |
lgr$set_filters(NULL) |
| 356 |
``` |
| 357 |
|
| 358 |
|
| 359 |
## Appenders: Managing log destinations |
| 360 |
|
| 361 |
The root logger only logs to the console by default. If you want to redirect |
| 362 |
the output to a file you can just add a file appender to lgr. |
| 363 |
|
| 364 |
```{r} |
| 365 |
tf <- tempfile() |
| 366 |
|
| 367 |
# Add a new appender to a logger. We don't have to supply a name, but that |
| 368 |
# makes it easier to remove later. |
| 369 |
lgr$add_appender(AppenderFile$new(file = tf), name = "file") |
| 370 |
|
| 371 |
# configure lgr so that it logs everything to the file, but only info and above |
| 372 |
# to the console |
| 373 |
lgr$set_threshold(NA) |
| 374 |
lgr$appenders$console$set_threshold("info") |
| 375 |
lgr$appenders$file$set_threshold(NA) |
| 376 |
lgr$info("Another informational message") |
| 377 |
lgr$debug("A debug message not shown by the console appender") |
| 378 |
|
| 379 |
readLines(tf) |
| 380 |
|
| 381 |
# Remove the appender again |
| 382 |
lgr$remove_appender("file") |
| 383 |
unlink(tf) |
| 384 |
``` |
| 385 |
|
| 386 |
|
| 387 |
## Inheritance: Hierarchical Loggers {#hierarchy} |
| 388 |
|
| 389 |
Logger hierarchies are a powerful concept to organize logging for different |
| 390 |
parts of a larger system. This is mainly relevant for package developers. It |
| 391 |
is good practice to have a separate Logger for each package. Since it is not |
| 392 |
common in R to build complex systems of hierarchically organised packages, |
| 393 |
hierarchies will usually be pretty flat (i.e. most Loggers will only inherit |
| 394 |
from the root logger). |
| 395 |
|
| 396 |
Each newly created Logger is child to a parent Logger, derived from its name. |
| 397 |
So `lg <- get_logger("foo/bar")` creates the logger with the qualified |
| 398 |
name `foo/bar` whose parent is the logger `foo` whose parent is (implicitly) |
| 399 |
the `root` logger. If the logger `foo` does not exist in that scenario, it is |
| 400 |
created automatically. This behaviour might sound strange at first, but it mimics |
| 401 |
tried and tested behaviour of python logging. This way logging is decoupled |
| 402 |
from the business logic and your program will not abort if you forgot to |
| 403 |
initialize some logger up the hierarchy for whatever reason. |
| 404 |
|
| 405 |
A logger dispatches the LogEvents it creates not only to its own |
| 406 |
Appenders, but also to the Appenders of all its ancestral Loggers (ignoring |
| 407 |
the threshold and Filters of the ancestral Loggers, but not of the Appenders). |
| 408 |
When you define Loggers for your package, you should *not* configure them |
| 409 |
(with custom Appenders or thresholds); that should be left to the user of the |
| 410 |
package. |
| 411 |
|
| 412 |
If all this sounds confusing to you, take a look at the |
| 413 |
[examples](#examples-hierarchy) and `?logger_tree`. The common use |
| 414 |
cases are pretty easy to understand and illustrate the *how* and *why* pretty |
| 415 |
well. |
| 416 |
|
| 417 |
Example hierarchy for the package **fancymodel** that provides a model along |
| 418 |
with a plumber API and a shiny web-interface to the package. |
| 419 |
``` r |
| 420 |
# prints a tree structure of all registered loggers |
| 421 |
logger_tree() |
| 422 |
``` |
| 423 |
|
| 424 |
``` |
| 425 |
root [info] -> 1 appenders |
| 426 |
└─fancymodel |
| 427 |
├─plumber |
| 428 |
└─#shiny |
| 429 |
├─server [trace] -> 2 appenders |
| 430 |
└─ui -> 1 appenders |
| 431 |
``` |
| 432 |
|
| 433 |
### Log flow |
| 434 |
|
| 435 |
The graph bellow outlines the flow of LogEvents through the logging system. |
| 436 |
This is an important reference if you want to work with Filters and Logger |
| 437 |
hierarchies. |
| 438 |
|
| 439 |
|
| 440 |
 |
| 441 |
|
| 442 |
|
| 443 |
## Logging with LoggerGlue |
| 444 |
|
| 445 |
[glue](https://glue.tidyverse.org/) is very nicely designed package for string |
| 446 |
interpolation. It makes composing log messages more flexible and comfortable |
| 447 |
at the price of an additional dependency and slightly less performance than |
| 448 |
`sprintf()` (which is used by normal Loggers). |
| 449 |
To take advantage of glue, simply create a new LoggerGlue like this: |
| 450 |
|
| 451 |
```{r} |
| 452 |
# install.packages("glue") |
| 453 |
|
| 454 |
lg <- get_logger_glue("glue/logger") |
| 455 |
|
| 456 |
lg$info( |
| 457 |
"glue automatically ", |
| 458 |
"pastes together unnamed arguments ", |
| 459 |
"and evaluates arbitray expressions inside braces {Sys.Date()}" |
| 460 |
) |
| 461 |
|
| 462 |
``` |
| 463 |
|
| 464 |
Glue lets you define temporary variables inside the `glue()` call. |
| 465 |
As with the normal Logger, named arguments get turned into custom fields. |
| 466 |
```{r} |
| 467 |
lg$info("For more info on glue see {website}", website = "https://glue.tidyverse.org/") |
| 468 |
``` |
| 469 |
|
| 470 |
You can suppress this behaviour by making named argument start with a `"."`. |
| 471 |
```{r} |
| 472 |
lg$info("Glue is available from {.cran}", .cran = "https://CRAN.R-project.org/package=glue") |
| 473 |
``` |
| 474 |
|
| 475 |
|
| 476 |
# Configuration |
| 477 |
|
| 478 |
|
| 479 |
## With setters |
| 480 |
|
| 481 |
There are several different ways to configure loggers. The most straight |
| 482 |
forward one is to use *setters* to specify the Loggers properties. |
| 483 |
```{r} |
| 484 |
lg <- get_logger("test") |
| 485 |
lg$config(NULL) # resets logger to unconfigured state |
| 486 |
lg$set_threshold("fatal") |
| 487 |
``` |
| 488 |
|
| 489 |
lgr sets up Loggers in a way so that R6 piping with `$` is possible. This works |
| 490 |
similar to the magrittr (`#%>#`) pipes. |
| 491 |
```{r} |
| 492 |
lg$ |
| 493 |
set_threshold("info")$ |
| 494 |
set_appenders(AppenderConsole$new(threshold = "info"))$ |
| 495 |
set_propagate(FALSE) |
| 496 |
``` |
| 497 |
|
| 498 |
## With a list object |
| 499 |
```{r} |
| 500 |
lg$config(list( |
| 501 |
threshold = "info", |
| 502 |
propagate = FALSE, |
| 503 |
appenders = AppenderConsole$new(threshold = "info") |
| 504 |
)) |
| 505 |
``` |
| 506 |
|
| 507 |
## With YAML or JSON |
| 508 |
|
| 509 |
You can use YAML and JSON config files with lgr. |
| 510 |
```{r eval = FALSE} |
| 511 |
lg$config("path/to/config.yaml") |
| 512 |
lg$config("path/to/config.json") |
| 513 |
``` |
| 514 |
|
| 515 |
You can also pass in YAML/JSON directly as a character string (or vector with |
| 516 |
one element per line) |
| 517 |
```{r} |
| 518 |
# Via YAML |
| 519 |
cfg <- " |
| 520 |
Logger: |
| 521 |
threshold: info |
| 522 |
propagate: false |
| 523 |
appenders: |
| 524 |
AppenderConsole: |
| 525 |
threshold: info |
| 526 |
" |
| 527 |
lg$config(cfg) |
| 528 |
``` |
| 529 |
|
| 530 |
|
| 531 |
# Examples {#examples} |
| 532 |
|
| 533 |
## Logging to the console |
| 534 |
|
| 535 |
lgr comes with simple but powerful formatting syntax for LogEvents. Please |
| 536 |
refer to `?format.LogEvent` for the full list of available placeholders. |
| 537 |
|
| 538 |
```{r} |
| 539 |
lg <- get_logger("test") |
| 540 |
lg$set_appenders(list(cons = AppenderConsole$new())) |
| 541 |
lg$set_propagate(FALSE) |
| 542 |
|
| 543 |
|
| 544 |
lg$info("the default format") |
| 545 |
lg$appenders$cons$layout$set_fmt("%L (%n) [%t] %c(): !! %m !!") |
| 546 |
lg$info("A more involved custom format") |
| 547 |
``` |
| 548 |
|
| 549 |
If this is not enough for you, you can use `LayoutGlue` based on the awesome |
| 550 |
[glue](https://github.com/tidyverse/glue) package. The syntax is a bit more |
| 551 |
verbose, and `AppenderGlue` is a bit less performant than `AppenderFormat`, but |
| 552 |
the possibilities are endless. |
| 553 |
|
| 554 |
```{r} |
| 555 |
# install.packages("glue") |
| 556 |
library(glue) |
| 557 |
lg$appenders$cons$set_layout(LayoutGlue$new( |
| 558 |
fmt = "{.logger$name} {level_name} {caller}: {toupper(msg)}" |
| 559 |
)) |
| 560 |
lg$info("with glue") |
| 561 |
``` |
| 562 |
All fields of the [LogEvent] object are exposed through LayoutGlue, so please |
| 563 |
refer to `?LogEvent` for a list of all available Fields. |
| 564 |
|
| 565 |
|
| 566 |
## Logging to JSON files |
| 567 |
|
| 568 |
JavaScript Object Notation (JSON) is an open-standard file format that uses |
| 569 |
human-readable text to transmit data objects consisting of attribute–value |
| 570 |
pairs and array data types ([Wikipedia](https://en.wikipedia.org/wiki/JSON)). |
| 571 |
JSON is the **recommended text-based logging format when logging to files** |
| 572 |
^[Technically, the logger does not produce standard JSON files but |
| 573 |
[JSON lines](https://jsonlines.org/)], |
| 574 |
as it is human- as well as machine readable. You should only log to a different |
| 575 |
format if you have very good reasons for it. The easiest way to log to |
| 576 |
JSON files is with AppenderJson^[AppenderJson is just an AppenderFile with |
| 577 |
LayotJson as default Layout and a few extra features] |
| 578 |
|
| 579 |
|
| 580 |
```{r} |
| 581 |
# install.packages("jsonlite") |
| 582 |
tf <- tempfile() |
| 583 |
|
| 584 |
lg <- get_logger("test") |
| 585 |
|
| 586 |
lg$set_appenders(list(json = AppenderJson$new(file = tf))) |
| 587 |
lg$set_propagate(FALSE) |
| 588 |
|
| 589 |
lg$info("JSON naturally ", field = "custom") |
| 590 |
lg$info("supports custom", numbers = 1:3) |
| 591 |
lg$info("log fields", use = "JSON") |
| 592 |
|
| 593 |
``` |
| 594 |
|
| 595 |
JSON is easy to parse and analyse with R. lgr provides the function |
| 596 |
`read_json_lines()` that can be used to read JSON log files, but you can also |
| 597 |
use AppenderJson's `$data` binding for an even more convenient method to |
| 598 |
read the logfile. |
| 599 |
|
| 600 |
```{r eval = FALSE} |
| 601 |
lg$appenders$json$data |
| 602 |
# same as |
| 603 |
read_json_lines(tf) |
| 604 |
``` |
| 605 |
```{r echo = FALSE} |
| 606 |
lg$appenders$json$data |
| 607 |
``` |
| 608 |
|
| 609 |
JSON is also human readable, though this vignette does not transport that fact |
| 610 |
very well because of the lack of horizontal space. |
| 611 |
```{r eval = FALSE} |
| 612 |
lg$appenders$json$show() |
| 613 |
# same as |
| 614 |
cat(readLines(tf), sep = "\n") |
| 615 |
``` |
| 616 |
```{r echo = FALSE} |
| 617 |
lg$appenders$json$show() |
| 618 |
``` |
| 619 |
```{r} |
| 620 |
# cleanup |
| 621 |
lg$config(NULL) |
| 622 |
unlink(tf) |
| 623 |
``` |
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
## Logging to rotating files |
| 628 |
|
| 629 |
lgr can also log to rotating files. The following example logs to a file that |
| 630 |
is reset and backed-up once it reaches a size of 10kb. Only the last 5 backups |
| 631 |
of the logfile are kept. |
| 632 |
|
| 633 |
```{r} |
| 634 |
# install.packages("rotor") |
| 635 |
tf <- tempfile(fileext = ".log") |
| 636 |
|
| 637 |
lg <- get_logger("test")$ |
| 638 |
set_propagate(FALSE)$ |
| 639 |
set_appenders(list(rotating = AppenderFileRotating$new( |
| 640 |
file = tf, |
| 641 |
size = "10 kb", |
| 642 |
max_backups = 5)) |
| 643 |
) |
| 644 |
|
| 645 |
for (i in 1:100) lg$info(paste(LETTERS, sep = "-")) |
| 646 |
|
| 647 |
# display info on the backups of tf |
| 648 |
lg$appenders$rotating$backups |
| 649 |
|
| 650 |
# manually delete all backups |
| 651 |
invisible(lg$appenders$rotating$prune(0)) |
| 652 |
lg$appenders$rotating$backups |
| 653 |
|
| 654 |
#cleanup |
| 655 |
unlink(tf) |
| 656 |
``` |
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
## Logger hierarchies {#examples-hierarchy} |
| 661 |
|
| 662 |
The most common use cases for creating a new Logger rather than just using the |
| 663 |
root Logger is if you create a Package that should contain logging. This |
| 664 |
way you can have separate Appenders (e.g logfiles) and thresholds for each |
| 665 |
package. |
| 666 |
|
| 667 |
```{r} |
| 668 |
# The logger name should be the same as the package name |
| 669 |
tf <- tempfile() |
| 670 |
lg <- get_logger("mypackage") |
| 671 |
lg$add_appender(AppenderFile$new(tf)) |
| 672 |
``` |
| 673 |
|
| 674 |
The `print()` method for Loggers gives a nice overview of the newly created |
| 675 |
Logger: |
| 676 |
|
| 677 |
```{r} |
| 678 |
print(lg) |
| 679 |
``` |
| 680 |
|
| 681 |
This tells us that `lg` logs all events of at least level `info`. It does |
| 682 |
have a single (unnamed) Appender that logs to a temporary file, and dispatches |
| 683 |
all LogEvents it creates to the Appenders of the root Logger (ignoring the |
| 684 |
threshold and filters of the root Logger, but not of its Appenders). |
| 685 |
|
| 686 |
We can use `lg$fatal()`, `lg$info()`, etc.. to log messages with this Logger: |
| 687 |
```{r} |
| 688 |
lg$info("A test message for lg") |
| 689 |
``` |
| 690 |
|
| 691 |
If we do not want `lg` to dispatch to the root Logger, we can set |
| 692 |
`propagate` to `FALSE`. |
| 693 |
```{r} |
| 694 |
lg$set_propagate(FALSE) |
| 695 |
``` |
| 696 |
When we take a look at the Logger again, we now see that it does not inherit |
| 697 |
any Appenders anymore |
| 698 |
```{r} |
| 699 |
print(lg) |
| 700 |
``` |
| 701 |
|
| 702 |
Consequently, `lg` no longer outputs log messages to he console |
| 703 |
```{r} |
| 704 |
lg$info("Nothing to see here") |
| 705 |
``` |
| 706 |
```{r} |
| 707 |
# cleanup |
| 708 |
lg$config(NULL) |
| 709 |
unlink(tf) |
| 710 |
``` |
| 711 |
|
| 712 |
|
| 713 |
## Buffered logging |
| 714 |
|
| 715 |
The main purpose of AppenderBuffer is to retain LogEvents in memory and write |
| 716 |
them to destinations at a later point in time, e.g. when the Buffer is full and |
| 717 |
needs to be flushed. For example, if you log to a |
| 718 |
remote database you can postpone this costly operation until after your analysis |
| 719 |
is finished. |
| 720 |
|
| 721 |
By setting a [filter](#thresholds) as a custom `$should_flush()` method for an |
| 722 |
AppenderBuffer, you can define more complex conditions to trigger flushing. |
| 723 |
For example, the will output the last 5 LogEvents that happened before an |
| 724 |
`error` occurred. |
| 725 |
|
| 726 |
```{r} |
| 727 |
lg <- get_logger("buffer") |
| 728 |
|
| 729 |
lg$ |
| 730 |
set_threshold(NA)$ |
| 731 |
set_propagate(FALSE)$ |
| 732 |
set_appenders( |
| 733 |
AppenderBuffer$new( |
| 734 |
threshold = NA, |
| 735 |
buffer_size = 5, # can hold 5 events, the 6th will trigger flushing |
| 736 |
flush_on_exit = FALSE, |
| 737 |
flush_on_rotate = FALSE, |
| 738 |
flush_threshold = "error", |
| 739 |
appenders = AppenderConsole$new(threshold = NA) |
| 740 |
)) |
| 741 |
|
| 742 |
# The for loop below stores 8 log events in the Buffer |
| 743 |
for (nm in month.name[1:8]) lg$debug("%s", nm) |
| 744 |
|
| 745 |
# An event of level 'error' or 'fatal' triggers flushing of the buffer |
| 746 |
lg$error("But the days grow short when you reach September") |
| 747 |
``` |
| 748 |
|
| 749 |
|
| 750 |
## Logging to databases |
| 751 |
|
| 752 |
Logging to databases is simple, though a few aspects can be tricky to |
| 753 |
configure based on the backend used. For performance reasons database inserts |
| 754 |
are buffered by default. This works exactly identical as described above for |
| 755 |
AppenderBuffer. If you want to write each LogEvent directly to the database, |
| 756 |
just set the buffer size to `0`. As of lgr 0.4.0, database appenders are |
| 757 |
part of the **lgrExtra** package that has to be installed separately. |
| 758 |
**Database logging is still somewhat experimental**. |
| 759 |
|
| 760 |
```{r, eval = FALSE} |
| 761 |
# install.packages("RSQLite") |
| 762 |
# install.packages("lgrExtra") |
| 763 |
lg <- get_logger("db_logger") |
| 764 |
lg$ |
| 765 |
set_propagate(FALSE)$ |
| 766 |
add_appender( |
| 767 |
name = "db", |
| 768 |
lgrExtra::AppenderDbi$new( |
| 769 |
conn = DBI::dbConnect(RSQLite::SQLite()), |
| 770 |
table = "log", |
| 771 |
buffer_size = 2L |
| 772 |
) |
| 773 |
) |
| 774 |
|
| 775 |
lg$info("Logging to databases uses a buffer") |
| 776 |
lg$info("As the buffer size is 2, no insert took place till now") |
| 777 |
lg$appenders$db$show() |
| 778 |
|
| 779 |
lg$info("Now as the buffer is rotated, all events are output to the db") |
| 780 |
lg$appenders$db$show() |
| 781 |
``` |
| 782 |
|
| 783 |
|
| 784 |
## Adding default extra fields to messages |
| 785 |
|
| 786 |
By abusing Filters, lgr can modify LogEvents as they are processed. One example |
| 787 |
for when this is useful is assigning a grouping identifier to a series of log |
| 788 |
calls. |
| 789 |
|
| 790 |
```{r} |
| 791 |
# setup an example function |
| 792 |
clean <- function() lgr$info("cleaning data") |
| 793 |
process <- function() lgr$info("processing data") |
| 794 |
output <- function() lgr$info("outputing data") |
| 795 |
|
| 796 |
analyze <- function(){ |
| 797 |
clean() |
| 798 |
process() |
| 799 |
output() |
| 800 |
} |
| 801 |
``` |
| 802 |
|
| 803 |
`with_log_value()` provides a convenient wrapper to inject values into log |
| 804 |
calls. |
| 805 |
```{r eval = FALSE} |
| 806 |
with_log_value( |
| 807 |
list(dataset_id = "dataset1"), |
| 808 |
analyze() |
| 809 |
) |
| 810 |
``` |
| 811 |
|
| 812 |
An alternative way to achieve the same is to use one of the preconfigured |
| 813 |
Filters that come with lgr. This approach is more more comfortable for |
| 814 |
use within functions. |
| 815 |
```{r eval = FALSE} |
| 816 |
analyze <- function(id = "dataset1"){ |
| 817 |
lgr$add_filter(FilterInject$new(dataset_id = id), name = "inject") |
| 818 |
on.exit(lgr$remove_filter("inject")) |
| 819 |
|
| 820 |
clean() |
| 821 |
process() |
| 822 |
output() |
| 823 |
} |
| 824 |
analyze() |
| 825 |
``` |
| 826 |
The result is the same in both cases: |
| 827 |
```{r, echo = FALSE} |
| 828 |
with_log_value( |
| 829 |
list(dataset_id = "dataset1"), |
| 830 |
analyze() |
| 831 |
) |
| 832 |
``` |
| 833 |
|
| 834 |
You can use `with_log_level()` and `FilterForceLevel` in a similar fashion to |
| 835 |
modify the log level of events conveniently. |
| 836 |
|
| 837 |
|
| 838 |
## Temporarily disable logging |
| 839 |
|
| 840 |
Temporary disabling logging for portions of code is straight forward and easy |
| 841 |
with lgr: |
| 842 |
|
| 843 |
```{r} |
| 844 |
without_logging({ |
| 845 |
lgr$warn("Oh Yeah?") |
| 846 |
lgr$fatal("Oh No") |
| 847 |
}) |
| 848 |
``` |
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
## Adding a custom logger to a package |
| 853 |
|
| 854 |
If you are a package author, it is good practice to define a separate logger |
| 855 |
for your package. This gives users the ability to easily enable/disable |
| 856 |
logging on a per-package basis. Loggers must be initialized in the packages |
| 857 |
.onLoad hook. You can do this by adding the following code to any `.R` file |
| 858 |
inside the `R/` directory of your package: |
| 859 |
|
| 860 |
```{r} |
| 861 |
# mypackage/R/mypackage-package.R |
| 862 |
.onLoad <- function(...){ |
| 863 |
assign( |
| 864 |
"lg", # the recommended name for a logger object |
| 865 |
lgr::get_logger(name = "mypackage"), # should be the same as the package name |
| 866 |
envir = parent.env(environment()) |
| 867 |
) |
| 868 |
} |
| 869 |
|
| 870 |
``` |
| 871 |
|
| 872 |
You can also just use `lgr::use_logger()` to generate the appropriate code for |
| 873 |
your package automatically. |
| 874 |
|
| 875 |
After you set this up you can use `lg$fatal()`, `lg$info()`, etc... |
| 876 |
inside your package. You do not have to define any appenders, since all log |
| 877 |
events will get redirected to the root Logger (see [Inheritance](#hierarchy)). |
| 878 |
|
| 879 |
|
| 880 |
## Creating a Layout that mimics NodeJS Winston logstash |
| 881 |
|
| 882 |
see https://github.com/s-fleck/lgr/issues/29 |
| 883 |
|
| 884 |
|
| 885 |
## Adding the source file / R-script to the log event |
| 886 |
|
| 887 |
Getting the source file is sadly non-trivial in R, otherwise it would have |
| 888 |
been included in the core logging functions. Luckily, this is easy to add |
| 889 |
with filters and the awesome [this.path](https://CRAN.R-project.org/package=this.path) |
| 890 |
package. This solution works in most scenarios, but not in all |
| 891 |
(for example, building this vignette). |
| 892 |
|
| 893 |
```{r, eval = FALSE} |
| 894 |
# install.packages("this.path") |
| 895 |
|
| 896 |
lg <- get_logger("srcfile") |
| 897 |
lg$add_filter(function(event){ |
| 898 |
tryCatch({ |
| 899 |
event$srcfile <- this.path::this.path() |
| 900 |
}, error = function(e) NULL) |
| 901 |
TRUE |
| 902 |
}) |
| 903 |
``` |
| 904 |
|
| 905 |
|
| 906 |
# References |
| 907 |
|
| 908 |
[Python Logging](https://docs.python.org/3/library/logging.html) |
| 909 |
|
| 910 |
[Eric Stenbock: The True Story of A Vampire](https://gutenberg.net.au/ebooks06/0606601h.html) |