daroczig / logger

A lightweight, modern and flexible, log4j and futile.logger inspired logging utility for R
https://daroczig.github.io/logger
280 stars 41 forks source link

log_fatal not stopping script #102

Closed przell closed 2 years ago

przell commented 2 years ago

Thanks for the great logging package. I would like to stop my script from running when I use log_fatal(). It is stated in the documentation that it stops the script (https://cran.r-project.org/web/packages/logger/logger.pdf, p. 15).

... List of supported log levels:

  1. FATAL severe error that will prevent the application from continuing ...

But it doesn't. I would expect it to work like stopifnot(). Which halts the execution and throws an error. Is there a way to accomplish that using the logger package. Or do I have to wrap it in an if() statement using log_fatal() and then stop().

Here's an example of a script i sourced to test the behaviour:

library(logger)

1+2
log_fatal("Error.")
2+3 # is evaluated: log_fatal() doesn't stop the script

a = 3+4
stopifnot(a == 8)
4+5 # is not evaluated: stopifnot() stops the script

# I would like to avoid this construct...
# a = 3+4
# if (a != 8) {
#   log_fatal("a != 8")
#   stop()
# }
# 4+5 # is not evaluated: stop() stops the script
daroczig commented 2 years ago

Setting a higher log level will not stop the application, the log levels are just suggestions on what level to use for different use cases, e.g. FATAL for the most serious problems, to log something before the application stops (outside of logger). I hope this makes sense -- I'm happy to take PRs to improve the related documentation :pray:

To your point, maybe log_failure might be a better fit?

library(logger)
a <- 3 + 4
log_failure(stopifnot(a == 8))

Or just enable log_errors and then let the R script handle the handling of the exception (e.g. exiting) after logging the error messages.

I am closing this, as the reported problem is actually working as expected (as per my intention), but again, looking forward to any PRs improving docs or feel free to reopen if the above might not be helpful.

przell commented 2 years ago

Thanks for the quick reply and the clarification! Both suggestions are very helpful! Maybe this is something to be added to the "Introduction to logger" vignette. Here's a suggestion:

To combine error handling (i.e., stopping a script under certain circumstances) and logging from logger you can either explicitly add the error handling to a logger function

a = 7
log_failure(stopifnot(a == 8))

or enable logger::log_errors() and let the R script handle the exception after logging the error messages.

# enable log errors at the beginning of your script
log_errors()
a = 7
stopifnot(a == 8)