# NOT RUN {
# lgr::lgr is the root logger that is always available
lgr$info("Today is a good day")
lgr$fatal("This is a serious error")
# Loggers use sprintf() for string formatting by default
lgr$info("Today is %s", Sys.Date() )
# If no unnamed `...` are present, msg is not passed through sprintf()
lgr$fatal("100% bad") # so this works
lgr$fatal("%s%% bad", 100) # if you use unnamed arguments, you must escape %
# You can create new loggers with get_logger()
tf <- tempfile()
lg <- get_logger("mylogger")$set_appenders(AppenderFile$new(tf))
# The new logger passes the log message on to the appenders of its parent
# logger, which is by default the root logger. This is why the following
# writes not only the file 'tf', but also to the console.
lg$fatal("blubb")
readLines(tf)
# This logger's print() method depicts this relationship.
child <- get_logger("lg/child")
print(child)
print(child$name)
# use formatting strings and custom fields
tf2 <- tempfile()
lg$add_appender(AppenderFile$new(tf2, layout = LayoutJson$new()))
lg$info("Not all %s support custom fields", "appenders", type = "test")
cat(readLines(tf), sep = "\n")
cat(readLines(tf2), sep = "\n")
# cleanup
unlink(c(tf, tf2))
lg$config(NULL) # reset logger config
# LoggerGlue
# You can also create a new logger that uses the awesome glue library for
# string formatting instead of sprintf
if (requireNamespace("glue")){
lg <- get_logger_glue("glue")
lg$fatal("blah ", "fizz is set to: {fizz}", foo = "bar", fizz = "buzz")
# prevent creation of custom fields with prefixing a dot
lg$fatal("blah ", "fizz is set to: {.fizz}", foo = "bar", .fizz = "buzz")
#' # completely reset 'glue' to an unconfigured vanilla Logger
get_logger("glue", reset = TRUE)
}
# Configuring a Logger
lg <- get_logger("test")
lg$config(NULL) # resets logger to unconfigured state
# With setters
lg$
set_threshold("error")$
set_propagate(FALSE)$
set_appenders(AppenderConsole$new(threshold = "info"))
lg$config(NULL)
# With a list
lg$config(list(
threshold = "error",
propagate = FALSE,
appenders = list(AppenderConsole$new(threshold = "info"))
))
lg$config(NULL) # resets logger to unconfigured state
# Via YAML
cfg <- "
Logger:
threshold: error
propagate: false
appenders:
AppenderConsole:
threshold: info
"
lg$config(cfg)
lg$config(NULL)
# }
Run the code above in your browser using DataLab