Writing messages, errors, and warnings into a log file in R

   Logging is needed to track the running process and the get full info about it. In this post, I will show how to implement logging in R script.
    First, we create log directory and define it as a log_path.

# Define log directory path
log_path <- "/home/mytool/log" 

    A log file is created on a daily basis, and file name contains current date e.g., log_file_20170911.log

# Create log file name
get_log_file_name <- function(file_name="log_file")
{
  file_name <- paste(file_name,format(Sys.time(), "%Y%m%d"),sep="_")
  file_name <- paste(log_path, paste(file_name,"log", sep="."), sep="/")
  return(file_name)
}

We assign log file into a logger variable.

logger <- file(get_log_file_name(), open = "at")

Sometimes, warnings and errors might appear during the process, those messages should also be directed into the log file. Below function can handle this process.

# This for redirecting any warning or error outputs
sink(logger, type="message")

A logit function below writes a message into a log file. It can accept multiple message parameters.

# logging function
logit <- function(msg, ...) 
{
   cat(format(Sys.time(), "%Y-%m-%d %X"), ":", paste(msg, ...), "\n", append = T,
       file = logger)
}


By this we can write multiple messages into log file.


Usage of function.

logit("Started")
logit("This is","multiple", "messages")
logit("Done!)

A log file locates in log directory.

#  ls /home/mytool/log
log_file_20170911.log

Content of log file looks as below,

# cat log_file_20170911.log
2017-19-11 06:19:15 PM : Started
2017-19-11 06:19:15 PM : This is multiple messages
2017-19-11 06:19:15 PM : Done!

 

Source code listing

 

log_path <- "/home/mytool/log"  
 
get_log_file_name <- function(file_name="log_file")
{   
  file_name <- paste(file_name,format(Sys.time(), "%Y%m%d"),sep="_")
  file_name <- paste(log_path, paste(file_name,"log", sep="."), sep="/")
  return(file_name)
}

logger <- file(get_log_file_name(), open = "at")
 
sink(logger, type="message") 
 
logit <- function(msg, ...)  
{
   cat(format(Sys.time(), "%Y-%m-%d %X"), ":", paste(msg, ...),
      "\n", append = T, file = logger)
}


2 comments:

  1. Very helpful piece. Thanks kindly!

    ReplyDelete
  2. hello thanks for the help. I have followed the entire code and I have a question on how to put this in my code. I want my code to be able to catch the errors and warnings and store them in a text file

    ReplyDelete