Logging in R Programming Language

Here’s the translation of the Go logging example to R, formatted in Markdown suitable for Hugo:

Our example demonstrates various logging techniques in R. We’ll use the logger package for basic logging and the jsonlite package for JSON-formatted structured logging.

First, let’s install and load the necessary packages:

install.packages(c("logger", "jsonlite"))
library(logger)
library(jsonlite)

Now, let’s go through different logging scenarios:

# Basic logging with the logger package
log_info("standard logger")

# Set log level to include microseconds
log_threshold(TRACE)
log_formatter(formatter_sprintf)
log_layout(layout_glue_generator(
  format = '{level} [{time}] {msg}'
))
Sys.setenv(LOG_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%OS6")
log_info("with micro")

# Include file and line information
log_layout(layout_glue_generator(
  format = '{level} [{time}] {caller}: {msg}'
))
log_info("with file/line")

# Create a custom logger with a prefix
mylog <- function(msg) {
  log_info(paste("my:", msg))
}
mylog("from mylog")

# Change the prefix
mylog <- function(msg) {
  log_info(paste("ohmy:", msg))
}
mylog("from mylog")

# Log to a file
log_appender(appender_file("log.txt"))
log_info("hello")

# Read and print the contents of the log file
cat("from logfile:", readLines("log.txt"), "\n")

# JSON-formatted structured logging
log_json <- function(msg, ...) {
  json_data <- toJSON(list(time = Sys.time(), level = "INFO", msg = msg, ...))
  cat(json_data, "\n")
}

log_json("hi there")
log_json("hello again", key = "val", age = 25)

Sample output; the date and time emitted will depend on when the example ran:

INFO [2023-05-22 10:45:16] standard logger
INFO [2023-05-22 10:45:16.904141] with micro
INFO [2023-05-22 10:45:16.904141] #5: with file/line
INFO [2023-05-22 10:45:16.904141] #7: my: from mylog
INFO [2023-05-22 10:45:16.904141] #11: ohmy: from mylog
from logfile: INFO [2023-05-22 10:45:16.904141] #14: hello 
{"time":["2023-05-22 10:45:16"],"level":["INFO"],"msg":["hi there"]}
{"time":["2023-05-22 10:45:16"],"level":["INFO"],"msg":["hello again"],"key":["val"],"age":[25]}

This example demonstrates various logging techniques in R:

  1. Basic logging using the logger package.
  2. Configuring log format to include microseconds.
  3. Including file and line information in logs.
  4. Creating custom loggers with prefixes.
  5. Logging to a file.
  6. JSON-formatted structured logging using the jsonlite package.

Note that R doesn’t have built-in logging capabilities as extensive as Go’s, so we use third-party packages to achieve similar functionality. The logger package provides a flexible logging system, while jsonlite allows us to create JSON-formatted logs for structured logging.