Capturing Rscript Errors in an Output File

Capturing Rscript errors in an output file


Rscript --no-save --no-restore --verbose myRfile.R > outputFile.Rout 2> errorFile.Rout

To put the output and error in the same file (assuming sh/bash)

Rscript --no-save --no-restore --verbose myRfile.R > outputFile.Rout 2>&1

R - `try` in conjunction with capturing ALL console output?

Based on @user2554330 s most excellent answer, I constructed an ugly thing that does exactly what I want:

  1. try to execute the statement
  2. don't fail fatally
  3. leave no ugly messages
  4. allow me access to errors and messages

So here it is in all it's despicable glory:

  saveMessages <- c()
query_results <- suppressMessages(
withCallingHandlers(
try(
UniProt.ws::select(
x = uniprot_object,
keys = 'BAA08084.1',
keytype = 'EMBL/GENBANK/DDBJ',
columns = c('ENSEMBL','UNIPROTKB')),
silent = TRUE),
message = function(e)
saveMessages <<- c(saveMessages, conditionMessage(e))))

Output error/warning log (txt file) when running R script under command line

You can use sink() to divert messages as well as warnings to a file. The trick is to set the argument type="message":

Here is an example adapted from the help for ?sink:

setwd(tempdir())

## capture messages and errors to a file.
zz <- file("all.Rout", open="wt")
sink(zz, type="message")

try(log("a"))

## reset message sink and close the file connection
sink(type="message")
close(zz)

## Display the log file
readLines("all.Rout")
[1] "Error in log(\"a\") : Non-numeric argument to mathematical function"

R code runs well on one computer but not on another (via Task Scheduler in RScript.exe)

Whenever you schedule jobs, consider using a command line shell such as PowerShell or Bash to handle the automation steps, capture, and log errors and messages. Rscript fails on the second machine for some unknown reason which you cannot determine since you do not receive any error messages from console using TaskScheduler.

Therefore, consider PowerShell to run all needed Rscript.exe calls and other commands and capture all errors to date-stamped log file. Below script redirects all console output to a .log file with messages. When Rscript command fails, the log will dump error or any console output (i.e., head, tail) below it. Regularly check logs after scheduled jobs.

PowerShell script (save as .ps1 file)

cd "C:\path\to\scripts"

& {
echo "`nAutomation Start: $(Get-Date -format 'u')"

echo "`nSTEP 1: myscript.R - $(Get-Date -format 'u')"
Rscript myscript.R

# ... ADD ANY OTHER COMMANDS ...


echo "`nCAutomation End: $(Get-Date -format 'u')"

} 3>&1 2>&1 > "C:\path\to\logs\automation_run_$(Get-Date -format 'yyyyMMdd').log"

Command Line (to be used in Task Scheduler)

Powershell.exe -executionpolicy remotesigned -File myscheduler.ps1

Note: Either change directory in TaskScheduler job settings where myscheduler.ps1 resides or run absolute path in -File argument.



Related Topics



Leave a reply



Submit