Logging in R and Python
A reference from Chapter 4, Logging and Monitoring, of DevOps for Data Science. The working exercise lives in Penguin Explorer. The examples below are reference snippets, not executable Quarto chunks.
The common model
A logging statement records an event at a severity level. Configuration decides which events are emitted, where they go, and how they look. Logging records what happened; exception handling determines what the application does next.
| Responsibility | R logger |
R log4r |
Python logging |
|---|---|---|---|
| Minimum severity | log_threshold() |
Logger threshold, level() |
Logger and handler levels |
| Emit an event | log_info() |
info(log, ...) |
logging.info() or log.info() |
| Destination | Appender | Appender | Handler |
| Record format | Formatter and layout | Layout | Formatter |
| Configuration scope | Global or named namespaces | Explicit logger object | Root and hierarchical named loggers |
INFO is useful for ordinary progress; DEBUG provides diagnostic details; WARNING flags a concerning condition; ERROR records a failed operation; CRITICAL signals severe application-level failure. Severity reflects impact, not whether an exception can be caught. Level names differ slightly: R commonly uses WARN and FATAL where Python uses WARNING and CRITICAL.
R: logger
Install logger in the intended R environment before using it. Its global configuration makes ordinary scripts concise:
logger::log_threshold(logger::INFO)
logger::log_info("Requesting prediction")
logger::log_debug("Hidden at INFO level")
logger::log_threshold(logger::DEBUG)
logger::log_debug("Visible now")
logger::log_threshold() # retrieve the current thresholdThe default configuration namespace is global. A namespace can have independent configuration once customized; changing the global threshold does not override all customized namespaces. log_appender() chooses the destination; log_layout() chooses the record layout. A formatter constructs the message itself, while a layout arranges the message with metadata.
R: log4r
The book uses log4r. Its explicit object carries configuration:
log <- log4r::logger(threshold = "INFO")
log4r::info(log, "Requesting prediction")
log4r::debug(log, "Hidden at INFO level")
log4r::level(log) <- "DEBUG"
log4r::debug(log, "Visible now")Pass the logger object to code that needs it. Its appenders select destinations, such as the console or a file; layouts control formatting. Both R packages cover the essentials. Familiarity with logger is a reasonable reason to keep using it; the book’s choice does not require migrating existing projects.
See the log4r reference.
Python: standard-library logging
No installation is required. Module-level calls use the shared root logger:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logging.info("Requesting prediction")
logging.debug("Prediction inputs: %s", penguin)Here, penguin stands for the request dictionary built by the application. basicConfig() configures the root logger, normally adding a console handler that writes to stderr. It normally does nothing if root handlers already exist. To change an existing root logger’s level explicitly:
logging.getLogger().setLevel(logging.DEBUG)Handler thresholds can still filter records. For applications split across modules, obtain a named logger in each module and configure logging centrally:
log = logging.getLogger(__name__)
log.info("Prediction received successfully")Named loggers form a hierarchy and can propagate records to ancestor handlers. Enabling DEBUG broadly may reveal networking-library messages as well as your own. Loggers and handlers can be configured separately when that becomes noisy.
Inside an exception handler, logging.exception("Prediction request failed") records an ERROR with the current traceback. Returning a readable browser message is a separate action; logging alone does not recover from the error.
See Python logging and the Logging HOWTO.
What the Penguin exercise demonstrated
We recorded request attempts and successful predictions at INFO. At DEBUG we recorded encoded inputs and returned mass. We stopped the API, observed a connection failure, added exception handling and an ERROR log, then restarted the API and confirmed Shiny recovered on the next click without restarting.
Console output is not automatically a durable log file. A hosting platform may capture stdout and stderr; otherwise configure a file destination if persistence is needed. Configure retention too, rather than letting files grow indefinitely. Avoid logging passwords, tokens, or unnecessary personal data. DEBUG does not make sensitive data safe to record.
Finally, HTTP 200 and a success log demonstrate operational success, not model accuracy. Plausibility checks can catch extreme outputs. Measuring predictive error requires observed outcomes matched to predictions; detecting drift without outcomes does not establish accuracy.