Logbook
Logbook is a Python library designed as a logging replacement, offering a fresh take on logging that is often considered more intuitive and powerful than Python's standard `logging` module. It focuses on clean, contextual logging and robust handler management. The current stable version is 1.9.2, with releases occurring intermittently based on contributions and maintenance.
Warnings
- breaking Logbook versions 1.x are exclusively for Python 3 (specifically >=3.9 for 1.9.x). Attempting to use a modern Logbook version with Python 2.x or older Python 3 versions will result in `SyntaxError` or other compatibility issues.
- gotcha Handlers in Logbook require explicit pushing and popping from the handler stack or usage as a context manager (`with handler.push_application():`). Forgetting to push a handler will result in no log output, and forgetting to pop can lead to resource leaks or unexpected behavior.
- gotcha When forking processes, especially with file-based handlers (`FileHandler`, `TimedRotatingFileHandler`), the file descriptors might not be correctly inherited or managed in the child process. This can lead to logs from child processes not being written or corrupting files.
Install
-
pip install logbook
Imports
- Logger
from logbook import Logger
- StreamHandler
from logbook import StreamHandler
- FileHandler
from logbook import FileHandler
- TimedRotatingFileHandler
from logbook.more import TimedRotatingFileHandler
- INFO
from logbook import INFO
- DEBUG
from logbook import DEBUG
Quickstart
from logbook import Logger, StreamHandler
import sys
log = Logger('MyApp')
def run_app():
log.info('Application started.')
log.debug('This is a debug message.')
try:
1 / 0
except ZeroDivisionError:
log.exception('An error occurred during calculation!')
log.info('Application finished.')
if __name__ == '__main__':
# Handlers should be pushed/popped or used as context managers
with StreamHandler(sys.stdout, level='INFO').push_application():
run_app()
# Example with a file handler (ensure 'app.log' is writable)
# from logbook import FileHandler
# with FileHandler('app.log', level='DEBUG').push_application():
# log.info('Logging to file...')
# log.debug('This will go to app.log if level is DEBUG or lower.')