TryCatchLog
R package for better error handling incl. logging with a full (!) stack trace incl. line numbers, post-mortem analysis and support for parallel processing
Install / Use
/learn @aryoda/TryCatchLogREADME
tryCatchLog
An R package to improve the error handling of the standard tryCatch and try function
Current version: See the NEWS for the most recent changes.
Table of contents
- Overview
- Tutorial slides
- Installation
- Usage
- Demo
- FAQ
- Build the package from source using RStudio
- How can I contribute?
- Links
- License
Overview
This repository provides the source code of an advanced tryCatch function for the programming language R called tryCatchLog.
The main advantages of the tryCatchLog function over tryCatch are
- Easy logging of errors, warnings and messages into a file or console
- supports code with parallel execution logic
- Complete stack trace with references to the source file names and line numbers
to identify the source of errors and warnings
(R's
tracebackdoes not contain the full stack trace if you catch errors and warnings!) - allows post-mortem analysis after errors by creating a dump file with all variables of the global environment (workspace) and each function called (via
dump.frames) - very helpful for batch jobs that you cannot debug on the server directly to reproduce the error! - Logs warnings (and other non-error conditions)
without stopping the execution of the evaluated expression
(unlike
tryCatchdoes if you pass a warning handler function, see this example)
This package was initially created as an answer to the stackoverflow question.
Tutorial slides for condition handling with standard R and tryCatchLog
You can find a tutorial slide deck here:
https://aryoda.github.io/tutorials/tryCatchLog/tryCatchLog-intro-slides.html
It is a single self-contained HTML file (made with revealjs, see https://revealjs.com) so you can save it locally to read it offline.
If you have installed the vignette of the package on your local computer you can also read the tutorial offline via
# devtools::install(build_vignettes = TRUE) # workaround to install the vignette if you build via RStudio
browseVignettes("tryCatchLog")
Important:
-
The vignette is only installed automatically if you install
tryCatchLogfrom CRAN. -
RStudio does currently not install the vignette HTML file if you "build and install".
Workaround manually to build and install the vignette in RStudio:
devtools::install(build_vignettes = TRUE)
Installation
Option 1: Install the stable version from CRAN
install.packages("tryCatchLog")
# browseVignettes("tryCatchLog") # to show the vignette(s)
Option 2: Install a stable version from github
This is the recommended installation procedure for using (beta) releases that are not yet published at CRAN but already stable enough (not in active development)!
- Pick a (beta) release from the list of Github releases (git tags)
- Install the version by specifying the tag name, eg.
# install.packages("devtools")
library(devtools)
install_github("aryoda/tryCatchLog", ref = "v1.1.7")`
Option 3: Install the most recent development version from github
This is the recommended installation procedure for the up-to-date development version!
To install the package using the source code at github you can use the package devtools:
# install.packages("devtools")
library(devtools)
install_github("aryoda/tryCatchLog")
If you want to install the vignette (tutorial) on your local computer you can build it during the installation (make sure you have installed the suggested packages of the DESCRIPTION file before):
devtools::install_github("aryoda/tryCatchLog", build_vignettes = TRUE)
# browseVignettes("tryCatchLog") # to show the vignette(s)
Dependencies
tryCatchLog has minimal dependencies: Only base R and utils.
It optionally (= if installed) uses the package
futile.logger
or lgr
to write logging messages in a nice and structured format.
You can find the source code of futile.logger here: https://github.com/zatonovo/futile.logger
Note: To use your own logging functionality you just have to register your logging functions
via set.logging.functions() which uses by default the very basic internal logging function log2console()
(that does not support any convenience functionality like setting the verbosity level but minimizes the dependencies from any other logging framework).
For a list of supported logging packages see feature request #42 (add convenience functions to activate other logging packages).
Since version 1.3.2 there is a new function set.logging.package() for that.
Usage
tryCatchLog function
library(tryCatchLog)
library(futile.logger)
tryCatchLog(log("abc"))
results in a log entry that shows the function call hierarchy with the last call (number 5 in the compact call stack) showing the R code line causing the error:
ERROR [2016-11-13 17:53:35] non-numeric argument to mathematical function
Compact call stack:
1 source("~/dev/R/tryCatchLog/demo/tryCatchLog_demo.R", echo = TRUE)
2 tryCatchLog_demo.R#46: tryCatchLog({
3 tryCatchLog.R#228: tryCatch(withCallingHandlers(expr, error = function(e) {
4 tryCatchLog_demo.R#48: bad.function(a.string)
5 tryCatchLog_demo.R#42: .handleSimpleError(function (e)
Full call stack:
1 source("~/dev/R/tryCatchLog/demo/tryCatchLog_demo.R", echo = TRUE)
2 withVisible(eval(ei, envir))
3 eval(ei, envir)
4 eval(expr, envir, enclos)
5 tryCatchLog_demo.R#46: tryCatchLog({
bad.function(a.negative.number)
bad.function(a.string)
}, error = function(e) {
print("Error handling starts now...")
}, finally = {
print("Finally...")
})
6 tryCatchLog.R#228: tryCatch(withCallingHandlers(expr, error = function(e) {
...
<omitted>
...
11 tryCatchLog_demo.R#48: bad.function(a.string)
12 tryCatchLog_demo.R#42: .handleSimpleError(function (e)
{
call.stack <- sys.calls()
log.message <- e$message
if (write.error.dump.file == TRUE) {
dump.file.name <- format(Sys.time(), format = "dump_%Y%m%d_%H%M%S")
dump.frames()
save.image(file = paste0(dump.file.name, ".rda"))
log.message <- paste0(log.message, "\nEnvironment dumped into file: ", dump.file.name, ".rda")
}
flog.error(buildLogMessage(log.message, call.stack, 1))
}, "non-numeric argument to mathematical function", quote(log(value)))
tryLog function
The pendant to try in R is the tryLog function which evaluates an expression and traps errors without
stopping the script execution:
print("Start")
tryLog(log("not a number!"))
print("Errors cannot stop me")
results in
> print("Start")
[1] "Start"
> tryLog(log("not a number!"))
ERROR [2016-11-26 23:32:04] non-numeric argument to mathematical function
Compact call stack:
1 tryLog(log("not a number!"))
2 tryCatchLog.R#319: tryCatchLog(expr = expr, write.error.dump.file = write.error.dump.file, error = function(e) {
3 tryCatchLog.R#247: tryCatch(withCallingHandlers(expr, error = function(e) {
Full call stack:
1 tryLog(log("not a number!"))
2 tryCatchLog.R#319: tryCatchLog(expr = expr, write.error.dump.file = write.error.dump.file, error = function(e) {
<... omitted ...>
> print("Errors cannot stop me")
[1] "Errors cannot stop me"
>
Observe that the error did not stop the execution of the script so that the next line has been executed too.
You could have achived similar behaviour (but with more code and without logging) using
print("Start")
tryCatchLog(log("not a number!"), error = function(e) {})
print("Errors cannot stop me")
Demo
To learn how tryCatchLog works you should open the demo source file that includes many
explanatory comments and run it.
To run the demo source code open the file in the demo sub folder of the source code
demo/tryCatchLog_demo.R
with the RStudio IDE.
If you have installed tryCatchLog as a package you could also run a demo with
demo(package = "tryCatchLog") # see a list of all demos
demo(package = "tryCatchLog", topic = "tryCatchLog_demo") # start a demo
FAQ
How do I find bug reports, feature requests and other issues?
You can browse and add your own issues at https://github.com/aryoda/tryCatchLog/issues
