Sub topic 3
Rotating Logs and Production Logging Patterns
Assume you know Python modules, try/except, classes, and how to run scripts from a terminal. This chapter covers practical logging configuration beyond basicConfig.
Rotating log files
A RotatingFileHandler limits file size. When the limit is reached, it renames the current file and starts a new one. backupCount controls how many old files remain.
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler(
"app.log", maxBytes=1_000_000, backupCount=3, encoding="utf-8"
)
handler.setFormatter(logging.Formatter(
"%(asctime)s %(levelname)s %(name)s: %(message)s"
))
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("The log rotates after about 1 MB")Declarative configuration with `dictConfig`
dictConfig describes formatters, handlers, and loggers in one dictionary. This keeps configuration separate from application logic.
import logging
import logging.config
config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {"format": "%(asctime)s %(levelname)s %(name)s: %(message)s"}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "standard",
"level": "INFO",
}
},
"root": {"level": "INFO", "handlers": ["console"]},
"loggers": {"myapp.database": {"level": "WARNING"}},
}
logging.config.dictConfig(config)Libraries and structured output
A library should create a named logger and avoid configuring output. A NullHandler prevents warnings when the application has not configured logging.
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
def compute(value):
logger.debug("Computing %r", value)
return value * 2For machine-readable logs, a custom formatter can emit one JSON object per line.
import json
import logging
class JsonFormatter(logging.Formatter):
def format(self, record):
return json.dumps({
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
})
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("User %s logged in", "alice")Testing and non-blocking logging
assertLogs verifies that code emits the expected level and message.
import logging
import unittest
class LoggingTest(unittest.TestCase):
def test_warning(self):
with self.assertLogs("myapp", level="WARNING") as captured:
logging.getLogger("myapp").warning("Disk %d%% full", 91)
self.assertEqual(captured.output, ["WARNING:myapp:Disk 91% full"])Slow handlers can delay application code. QueueHandler puts records on a queue, and QueueListener processes them elsewhere.
Practical guidelines
- Use
DEBUGfor diagnostic details,INFOfor normal milestones,WARNINGfor recoverable problems, andERRORfor failed operations. - Use
logger.exception()inside anexceptblock to include the traceback. - Pass values as logging arguments, such as
logger.info("User %s", user_id), rather than formatting eagerly. - Configure handlers once. Duplicate handlers can print every record multiple times.
- Do not log passwords, tokens, or other secrets.
- Set
propagate = Falsewhen a logger must not send records to ancestor handlers.
Exercise
Which component should a library configure: a formatter and output handler, or a named logger with a NullHandler?
Show answer
It should configure a named logger with a NullHandler and leave output decisions to the application.