logzero
logzero is a Python library (version 1.7.0) that provides robust and effective logging for both Python 2 and 3. It simplifies logging to the console with pretty, level-specific colored output and supports logging to rotating files. The library also includes built-in JSON logging capabilities, aiming for a low-boilerplate approach to standard Python logging. Its release cadence is generally stable with occasional updates.
Warnings
- gotcha logzero outputs all log messages to `stderr` by default, not `stdout`. Users expecting `print()`-like behavior to `stdout` might find their logs redirected, requiring explicit redirection if they want `stdout` for other application output.
- gotcha When using `logzero.logfile()`, the default parameters `maxBytes=0` and `backupCount=0` disable log file rotation. This means log files will grow indefinitely unless these parameters are explicitly configured to enable rotation.
- gotcha Functions like `logzero.loglevel()`, `logzero.logfile()`, and `logzero.formatter()` globally reconfigure the *default* `logzero.logger` instance and all its internal handlers. This can unintentionally affect logging behavior across different modules or parts of a larger application if not managed carefully.
- gotcha If a custom formatter (set via `logzero.formatter()`) includes ANSI color codes and is applied to file handlers without stripping them, log files may contain these escape sequences, making them harder to read in plain text editors.
Install
-
pip install logzero
Imports
- logger
from logzero import logger
- logzero module functions
import logzero logzero.logfile('/path/to/file.log')
Quickstart
from logzero import logger, logfile
import os
# Configure a logfile that rotates after 1MB, keeping 3 backups
log_file_path = os.path.join(os.getcwd(), "app.log")
logfile(log_file_path, maxBytes=1_000_000, backupCount=3)
# Set the global minimum log level to INFO
logger.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))
logger.debug("This is a debug message - won't show with INFO level.")
logger.info("Application started successfully.")
logger.warning("Disk space is getting low.")
try:
1 / 0
except ZeroDivisionError as e:
logger.exception(f"An error occurred: {e}")