Creating log files in R

I want to create a log file for my algorithm that stores INFO, ERRORS, WARNINGS
I saw the logging package but can anyone direct me to any implementation go it. It emulates the Python logging package but I'm finding It a bit complex to apply

Any help is appropriated. Thanks in advance!

Most logging packages will be a little complex to setup and then very easy in use.
Below you will find an example with the log4r package. Other packages work similar.
This example will give you log messages in the console output and in a text file.

After loading the package we have four statements that setup the logging:

  • set the name of the text file that will contain the log messages
  • define the function that will write messages to the console (all default arguments)
  • define the function that will write messages to the text file (all default arguments except the name of the text file)
  • indicate that you want to use logging messages with severity INFO and higher with the functions you just defined

Then I define three functions as examples of a log call for resp. the INFO, ERROR and DEBUG level.
In your algorithm you will insert the log4r::info, log4r::error and log4r::debug calls at the points where you want them.

Then I call the three functions and at the end I show that the text file indeed contains the same messages that are shown in the console output.

library(log4r)
#> 
#> Attaching package: 'log4r'
#> The following object is masked from 'package:base':
#> 
#>     debug

my_logfile = "my_logfile.txt"

my_console_appender = console_appender(layout = default_log_layout())
my_file_appender = file_appender(my_logfile, append = TRUE, 
                            layout = default_log_layout())

my_logger <- log4r::logger(threshold = "INFO", 
                appenders= list(my_console_appender,my_file_appender))

log4r_info <- function() {
  log4r::info(my_logger, "Info_message.")
}

log4r_error <- function() {
  log4r::error(my_logger, "Error_message")
}

log4r_debug <- function() {
  log4r::debug(my_logger, "Debug_message")
}

log4r_debug() # will not trigger log entry because threshold was set to INFO

log4r_info() 
#> INFO  [2020-07-01 12:48:02] Info_message.

log4r_error() 
#> ERROR [2020-07-01 12:48:02] Error_message

readLines(my_logfile)
#> [1] "INFO  [2020-07-01 12:48:02] Info_message."
#> [2] "ERROR [2020-07-01 12:48:02] Error_message"

Created on 2020-07-01 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.