Reputation: 991
I'm writing R code where I would like to have it run either in "non-debug" or "debug" mode. Under the debug mode, I would like the code to print-out runtime information.
In other languages, I would typically have some sort of print function that does nothing unless a flag is turned on (either for compilation or runtime).
For example, I can use #ifdef DEBUG (in compilation time), or set a debug level in run time.
What would be the equivalent way of doing this in R?
Upvotes: 7
Views: 1023
Reputation: 151
Extending Richie's code:
also, you can check for the system environment variable DEBUG for initialization:
isdbg <- function()
{
if(exists(".DEBUG", envir = globalenv()))
{
return(get(".DEBUG", envir = globalenv()))
} else #initialise from shell environment variable
{
debugmode <- !(toupper(Sys.getenv("DEBUG")) %in% c("", "FALSE", "0"))
assign(".DEBUG", debugmode, envir = globalenv())
return(debugmode)
}
}
setdbg <- function(on = FALSE)
{
old_value <- isdbg()
.DEBUG <<- on
invisible(old_value)
}
ifdbg <- function(x)
{
if(isdbg()) x
}
usage: setdbg(TRUE) #turn debug mode on setdbg(FALSE) #turn debug mode off
if(isdbg())
{
#do some logging or whatever
}
or
ifdebug(...do something here...)
Upvotes: 1
Reputation: 3955
Another possibility is log4r
To quote this page:
log4r: A simple logging system for R, based on log4j
logr4 provides an object-oriented logging system that uses an API roughly equivalent to log4j and its related variants.
Upvotes: 0
Reputation: 121057
A slightly fancier version of Dirk's answer:
is_debug_mode <- function()
{
exists(".DEBUG", envir = globalenv()) &&
get(".DEBUG", envir = globalenv())
}
set_debug_mode <- function(on = FALSE)
{
old_value <- is.debug.mode()
.DEBUG <<- on
invisible(old_value)
}
Usage is, e.g.,
if(is_debug_mode())
{
#do some logging or whatever
}
and
set_debug_mode(TRUE) #turn debug mode on
set_debug_mode(FALSE) #turn debug mode off
Upvotes: 4
Reputation: 7023
It might also be worth looking at the Verbose
class in the R.utils package, which allows you very fine control for printing run-time information of various sorts.
Upvotes: 2
Reputation: 368201
Same thing, minus the preprocessor:
options()
value) ..., verbose=options(myVerbose))
, in your packages, etc pp--verbose
or --debug
.Upvotes: 9