Logging#
As programs grow beyond a few lines it becomes impractical to rely on print() statements to understand what the program is doing. Print output is ephemeral — it disappears when the terminal closes, cannot be filtered by severity, and cannot easily be redirected to a file or a monitoring system. In production systems, where a human is rarely watching a console, structured log records are the primary window into what an application is doing.
Python’s standard library includes the logging module, which provides a flexible, hierarchical logging system used across virtually every serious Python project. It allows you to:
Emit messages at different severity levels and filter them independently at different destinations
Write log output to the console, one or more files, network sockets, email, or any custom destination
Include rich context in each record: timestamp, module name, line number, function name, and custom fields
Configure the entire logging system from an external configuration file without changing application code
By the end of this notebook, you will:
explain the five standard log levels and when each is appropriate
configure basic logging with
basicConfig()for console and file outputcreate named
Loggerobjects and understand how the logger hierarchy worksattach
Handlerobjects to loggers to control where records are writtenattach
Formatterobjects to handlers to control the record layoutuse
Filterobjects to selectively pass or block log recordsconfigure logging with
dictConfig()for application-scale projectslog exception tracebacks with
logger.exception()andexc_info=Trueadd structured context to log records with the
extraparameter
Log Levels#
Every log record carries a level that indicates its severity. The logging module defines five standard levels in ascending order:
Level |
Numeric value |
When to use |
|---|---|---|
|
10 |
Detailed diagnostic information useful only during development |
|
20 |
Confirmation that things are working as expected |
|
30 |
Something unexpected happened, but the program can continue |
|
40 |
A serious problem that prevented part of the program from running |
|
50 |
A severe error that may cause the program to terminate |
A logger (or handler) has a minimum level set on it. Any record with a lower level is silently discarded. This lets you leave debug calls in your code permanently and switch them on only when needed — without touching the code itself.
1import logging
2
3# The root logger's default level is WARNING.
4# DEBUG and INFO are suppressed until we change the configuration.
5logging.debug("DEBUG: Fetching portfolio positions") # suppressed
6logging.info("INFO: Portfolio loaded") # suppressed
7logging.warning("WARNING: Price data is stale") # visible
8logging.error("ERROR: Order rejected") # visible
9logging.critical("CRITICAL: Database connection lost") # visible
WARNING:root:WARNING: Price data is stale
ERROR:root:ERROR: Order rejected
CRITICAL:root:CRITICAL: Database connection lost
Notice that DEBUG and INFO produced no output. The root logger’s default threshold is WARNING, so only records at WARNING level and above are processed.
Also note the default output format: LEVEL:logger_name:message. We will customise this shortly.
You can also log at a level by passing the numeric value directly, or use logging.log(level, message) when the level is determined at runtime:
1# Log at a level determined at runtime
2severity = logging.ERROR
3logging.log(severity, "Dynamic level logging: connection timed out")
4
5# Inspect the numeric value of each level
6for name in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
7 print(f"{name:8s} = {logging.getLevelName(name)}")
ERROR:root:Dynamic level logging: connection timed out
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
CRITICAL = 50
Basic Configuration#
logging.basicConfig() is the simplest way to configure the root logger. Call it once near the entry point of your program before any logging calls.
Key parameters:
Parameter |
Purpose |
|---|---|
|
Minimum level to process (e.g. |
|
Format string for each record |
|
|
|
Write to this file instead of |
|
|
|
Write to this stream instead of |
|
If |
basicConfig() is a no-op if the root logger already has handlers. The force=True parameter overrides this and is essential inside notebooks where the root logger may have been configured by a previous cell.
1import logging
2import sys
3
4logging.basicConfig(
5 level=logging.DEBUG,
6 format="%(levelname)-8s %(message)s",
7 stream=sys.stdout, # stdout so Jupyter shows it in normal (non-red) output
8 force=True
9)
10
11logging.debug("Fetching portfolio positions from database")
12logging.info("Portfolio loaded: 4 positions, total value $42,350")
13logging.warning("TSLA position: last price data is 6 hours old")
14logging.error("Market data feed connection refused")
15logging.critical("Risk limit breached — halting order submission")
DEBUG Fetching portfolio positions from database
INFO Portfolio loaded: 4 positions, total value $42,350
WARNING TSLA position: last price data is 6 hours old
ERROR Market data feed connection refused
CRITICAL Risk limit breached — halting order submission
All five levels now appear because we set level=logging.DEBUG. To write log output to a file instead of the console, use the filename parameter:
1import logging
2
3LOG_FILE = "/tmp/trading_app.log"
4
5logging.basicConfig(
6 level=logging.INFO,
7 format="%(asctime)s %(levelname)-8s %(message)s",
8 filename=LOG_FILE,
9 filemode="w",
10 force=True
11)
12
13logging.info("Application started")
14logging.info("Connected to market data feed")
15logging.warning("Quote latency above threshold: 120ms")
16logging.error("Order #4421 rejected: insufficient buying power")
17
18# Read back the file to verify
19with open(LOG_FILE) as f:
20 print(f.read())
2026-05-25 22:31:51,734 INFO Application started
2026-05-25 22:31:51,734 INFO Connected to market data feed
2026-05-25 22:31:51,734 WARNING Quote latency above threshold: 120ms
2026-05-25 22:31:51,734 ERROR Order #4421 rejected: insufficient buying power
Formatting Log Messages#
The format string uses %-style placeholders drawn from the LogRecord attributes. The most useful ones are:
Attribute |
Meaning |
|---|---|
|
Human-readable timestamp (formatted by |
|
Logger name |
|
Level as a string ( |
|
The formatted log message |
|
Source file name |
|
Source line number |
|
Function or method name |
|
Thread ID |
|
Process ID |
1import logging, sys
2
3logging.basicConfig(
4 level=logging.DEBUG,
5 format="%(asctime)s | %(name)-20s | %(levelname)-8s | %(filename)s:%(lineno)d | %(message)s",
6 datefmt="%Y-%m-%d %H:%M:%S",
7 stream=sys.stdout,
8 force=True
9)
10
11logging.info("Application initialised")
12logging.warning("Configuration file not found — using defaults")
2026-05-25 22:31:51 | root | INFO | 1393065992.py:11 | Application initialised
2026-05-25 22:31:51 | root | WARNING | 1393065992.py:12 | Configuration file not found — using defaults
Logger Objects#
The functions called so far (logging.info(), logging.warning(), etc.) are convenience wrappers that log to the root logger. For any code that might be used as a library — or for any module in a multi-module application — you should create a named logger instead:
logger = logging.getLogger(__name__)
Using __name__ makes the logger name match the fully qualified module name (e.g., myapp.trading.orders). This has two important benefits:
Log records include the source module automatically
The configuration of parent loggers flows down to children through the hierarchy
getLogger() always returns the same Logger object for a given name — it is safe to call at module level and in functions.
1import logging, sys
2
3# Restore a clean root logger configuration
4logging.basicConfig(
5 level=logging.DEBUG,
6 format="%(name)-25s %(levelname)-8s %(message)s",
7 stream=sys.stdout,
8 force=True
9)
10
11# Named logger — in real code this would be at the top of the module file
12logger = logging.getLogger("trading.orders")
13
14logger.debug("Building order for AAPL x 50 shares")
15logger.info("Order #5001 submitted")
16logger.warning("Order #5001 partially filled: 32 of 50 shares")
17logger.error("Order #5001 cancelled: session closed")
18
19# getLogger() returns the same object every time
20logger_b = logging.getLogger("trading.orders")
21print("\nSame object:", logger is logger_b)
trading.orders DEBUG Building order for AAPL x 50 shares
trading.orders INFO Order #5001 submitted
trading.orders WARNING Order #5001 partially filled: 32 of 50 shares
trading.orders ERROR Order #5001 cancelled: session closed
Same object: True
Logger Level vs Handler Level#
A Logger has its own level setting and each of its Handlers has its own level. A record must pass both checks to be emitted:
The Logger’s level gates whether the record is created at all.
Each Handler’s level gates whether that handler processes the record.
By default a new named logger has level NOTSET (0), which means it defers to its parent’s level. Only override this when you need a specific logger to behave differently from its parent.
1import logging, sys
2
3logging.basicConfig(stream=sys.stdout, force=True, format="%(name)s %(levelname)s %(message)s")
4
5# This logger only emits ERROR and above, regardless of root logger level
6noisy_lib_logger = logging.getLogger("noisy_vendor_lib")
7noisy_lib_logger.setLevel(logging.ERROR)
8
9noisy_lib_logger.debug("Internal cache miss") # suppressed
10noisy_lib_logger.info("Heartbeat OK") # suppressed
11noisy_lib_logger.error("Vendor API rate limit hit") # visible
12
13# Our own logger inherits the root level (WARNING by default)
14app_logger = logging.getLogger("myapp")
15app_logger.warning("Retrying in 5 seconds") # visible
noisy_vendor_lib ERROR Vendor API rate limit hit
myapp WARNING Retrying in 5 seconds
The Logger Hierarchy#
Loggers are organised in a tree rooted at the root logger. The tree is defined by dotted names: a logger named myapp.trading is a child of myapp, which is a child of the root logger.
By default, when a child logger emits a record it propagates the record up to its parent, and so on up to the root. This means:
You only need to attach handlers to the root (or to a top-level application logger)
Child loggers inherit effective levels from ancestors unless you override them
Setting
propagate = Falseon a child stops propagation at that point
1import logging, sys
2
3# Configure only the root logger
4logging.basicConfig(
5 level=logging.DEBUG,
6 format="%(name)-30s %(levelname)-8s %(message)s",
7 stream=sys.stdout,
8 force=True
9)
10
11# Child loggers have no handlers or level set — they propagate to root
12app = logging.getLogger("trading")
13orders = logging.getLogger("trading.orders")
14positions = logging.getLogger("trading.positions")
15
16orders.info("Order submitted") # propagates to root → appears
17positions.warning("Position limit 90%") # propagates to root → appears
18app.debug("Heartbeat OK") # propagates to root → appears at DEBUG
trading.orders INFO Order submitted
trading.positions WARNING Position limit 90%
trading DEBUG Heartbeat OK
1import logging, sys
2
3logging.basicConfig(
4 level=logging.DEBUG,
5 format="%(name)-30s %(levelname)-8s %(message)s",
6 stream=sys.stdout,
7 force=True
8)
9
10# Stop propagation for the vendor library logger
11vendor = logging.getLogger("vendor")
12vendor.propagate = False # records go nowhere — vendor logger has no handlers
13vendor.warning("Vendor heartbeat missed") # silently discarded
14
15# Our own logger still propagates normally
16app = logging.getLogger("trading")
17app.info("Application running normally") # appears
Vendor heartbeat missed
trading INFO Application running normally
Handlers#
A Handler is the object that actually writes (or sends) a log record to its destination. A single Logger can have multiple handlers attached — for example one that writes everything to a file and another that only writes ERROR and above to the console.
The most useful built-in handlers:
Handler |
Destination |
|---|---|
|
Any stream (default |
|
A single file |
|
File that rolls over when it reaches a maximum size |
|
File that rolls over on a time interval |
|
Discards all records (used in library code) |
|
Sends records over a TCP socket |
|
Sends records as email |
|
Sends records to |
Attach a handler with logger.addHandler(handler). Set its minimum level with handler.setLevel().
1import logging, sys
2
3# Create a fresh logger (clear any handlers from previous cell runs)
4app_log = logging.getLogger("app_demo")
5app_log.handlers.clear()
6app_log.setLevel(logging.DEBUG)
7app_log.propagate = False # don't also send to root logger
8
9# Console handler — INFO and above
10console = logging.StreamHandler(sys.stdout)
11console.setLevel(logging.INFO)
12console.setFormatter(logging.Formatter("CONSOLE %(levelname)-8s %(message)s"))
13
14# File handler — DEBUG and above (captures everything)
15file_h = logging.FileHandler("/tmp/app_demo.log", mode="w")
16file_h.setLevel(logging.DEBUG)
17file_h.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
18
19app_log.addHandler(console)
20app_log.addHandler(file_h)
21
22app_log.debug("Cache warmed") # file only (below console threshold)
23app_log.info("Server listening on port 8080") # console + file
24app_log.warning("Memory usage at 78%") # console + file
25app_log.error("Worker process crashed") # console + file
26
27print("\n--- File contents ---")
28with open("/tmp/app_demo.log") as f:
29 print(f.read())
CONSOLE INFO Server listening on port 8080
CONSOLE WARNING Memory usage at 78%
CONSOLE ERROR Worker process crashed
--- File contents ---
2026-05-25 22:31:51,761 DEBUG Cache warmed
2026-05-25 22:31:51,761 INFO Server listening on port 8080
2026-05-25 22:31:51,761 WARNING Memory usage at 78%
2026-05-25 22:31:51,761 ERROR Worker process crashed
Rotating File Handlers#
Production applications need to prevent log files from growing without bound. RotatingFileHandler caps the file at a maximum byte size and keeps a configurable number of backup files (app.log, app.log.1, app.log.2, …). When the current file is full it is renamed and a new file is started.
1import logging
2from logging.handlers import RotatingFileHandler
3
4rotate_log = logging.getLogger("rotating_demo")
5rotate_log.handlers.clear()
6rotate_log.setLevel(logging.DEBUG)
7rotate_log.propagate = False
8
9handler = RotatingFileHandler(
10 "/tmp/rotating_demo.log",
11 maxBytes=500, # tiny for demo purposes; use 5_000_000 (5 MB) in production
12 backupCount=3
13)
14handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
15rotate_log.addHandler(handler)
16
17# Write enough records to trigger at least one rotation
18for i in range(20):
19 rotate_log.info(f"Trade #{i:04d}: AAPL x 10 @ $189.30 executed")
20
21import glob
22rotated = sorted(glob.glob("/tmp/rotating_demo.log*"))
23print("Log files created:", rotated)
Log files created: ['/tmp/rotating_demo.log', '/tmp/rotating_demo.log.1', '/tmp/rotating_demo.log.2']
Formatters#
A Formatter object determines the text layout of each emitted record. You attach a Formatter to a Handler (not to a Logger). This means different handlers on the same logger can use different formats — for example, a verbose format for the file and a concise format for the console.
1import logging, sys
2
3fmt_log = logging.getLogger("formatter_demo")
4fmt_log.handlers.clear()
5fmt_log.setLevel(logging.DEBUG)
6fmt_log.propagate = False
7
8# Verbose formatter for the file — includes every useful field
9verbose_fmt = logging.Formatter(
10 fmt="%(asctime)s | %(name)s | %(levelname)-8s | %(filename)s:%(lineno)d | %(message)s",
11 datefmt="%Y-%m-%dT%H:%M:%S"
12)
13
14# Terse formatter for the console — just level and message
15terse_fmt = logging.Formatter("[%(levelname)s] %(message)s")
16
17file_h = logging.FileHandler("/tmp/formatter_demo.log", mode="w")
18file_h.setFormatter(verbose_fmt)
19
20console_h = logging.StreamHandler(sys.stdout)
21console_h.setFormatter(terse_fmt)
22
23fmt_log.addHandler(file_h)
24fmt_log.addHandler(console_h)
25
26fmt_log.info("Portfolio rebalanced")
27fmt_log.warning("Dividend data missing for MSFT")
28
29print("\n--- Verbose file output ---")
30with open("/tmp/formatter_demo.log") as f:
31 print(f.read())
[INFO] Portfolio rebalanced
[WARNING] Dividend data missing for MSFT
--- Verbose file output ---
2026-05-25T22:31:51 | formatter_demo | INFO | 1059926292.py:26 | Portfolio rebalanced
2026-05-25T22:31:51 | formatter_demo | WARNING | 1059926292.py:27 | Dividend data missing for MSFT
Filters#
A Filter provides finer-grained control than a level threshold. You can attach filters to Loggers or Handlers. A record is only processed if every attached filter passes it.
Create a custom filter by subclassing logging.Filter and implementing the filter(record) method. Return a truthy value to allow the record through or a falsy value to block it.
1import logging, sys
2
3class SuppressVendorDebug(logging.Filter):
4 """Block DEBUG records from any logger whose name starts with 'vendor'."""
5 def filter(self, record: logging.LogRecord) -> bool:
6 if record.name.startswith("vendor") and record.levelno == logging.DEBUG:
7 return False
8 return True
9
10
11handler = logging.StreamHandler(sys.stdout)
12handler.setFormatter(logging.Formatter("%(name)-20s %(levelname)-8s %(message)s"))
13handler.addFilter(SuppressVendorDebug())
14
15# Attach the handler to the root logger so all loggers share it
16root = logging.getLogger()
17root.handlers.clear()
18root.setLevel(logging.DEBUG)
19root.addHandler(handler)
20
21app_log = logging.getLogger("trading")
22vendor_log = logging.getLogger("vendor.http")
23
24app_log.debug("Order book loaded") # passes — not a vendor logger
25vendor_log.debug("HTTP keep-alive sent") # blocked by filter
26vendor_log.warning("Rate limit approaching") # passes — not DEBUG level
trading DEBUG Order book loaded
Rate limit approaching
Configuring Logging with dictConfig#
basicConfig() is convenient for scripts but quickly becomes unwieldy for applications with multiple loggers and handlers. logging.config.dictConfig() accepts a plain Python dictionary that fully describes the logging configuration — loggers, handlers, formatters, and the connections between them.
This approach separates configuration from code. The dictionary can be loaded from a JSON or YAML file, from environment variables, or from a configuration management system — without changing any application source.
1import logging
2import logging.config
3import sys
4
5LOGGING_CONFIG = {
6 "version": 1,
7 "disable_existing_loggers": False,
8 "formatters": {
9 "verbose": {
10 "format": "%(asctime)s | %(name)-20s | %(levelname)-8s | %(message)s",
11 "datefmt": "%Y-%m-%d %H:%M:%S",
12 },
13 "simple": {
14 "format": "[%(levelname)s] %(message)s",
15 },
16 },
17 "handlers": {
18 "console": {
19 "class": "logging.StreamHandler",
20 "level": "WARNING",
21 "formatter": "simple",
22 "stream": "ext://sys.stdout",
23 },
24 "file": {
25 "class": "logging.FileHandler",
26 "level": "DEBUG",
27 "formatter": "verbose",
28 "filename": "/tmp/dictconfig_demo.log",
29 "mode": "w",
30 },
31 },
32 "loggers": {
33 "trading": {
34 "level": "DEBUG",
35 "handlers": ["console", "file"],
36 "propagate": False,
37 },
38 },
39 "root": {
40 "level": "WARNING",
41 "handlers": ["console"],
42 },
43}
44
45logging.config.dictConfig(LOGGING_CONFIG)
46
47logger = logging.getLogger("trading")
48logger.debug("Order validator initialised") # file only
49logger.info("Session opened") # file only
50logger.warning("Equity limit at 95%") # console + file
51logger.error("Margin call triggered") # console + file
52
53print("--- File output ---")
54with open("/tmp/dictconfig_demo.log") as f:
55 print(f.read())
[WARNING] Equity limit at 95%
[ERROR] Margin call triggered
--- File output ---
2026-05-25 22:31:51 | trading | DEBUG | Order validator initialised
2026-05-25 22:31:51 | trading | INFO | Session opened
2026-05-25 22:31:51 | trading | WARNING | Equity limit at 95%
2026-05-25 22:31:51 | trading | ERROR | Margin call triggered
Loading Configuration from a File#
In production, store the config dictionary in a JSON or YAML file and load it at startup:
import json, logging.config
with open("logging_config.json") as f:
config = json.load(f)
logging.config.dictConfig(config)
The older fileConfig() function reads INI-style configuration files. dictConfig() is more flexible and is the recommended approach for new projects.
disable_existing_loggers — set this to False (as above) when calling dictConfig() after other modules have already created loggers; otherwise those loggers will be silently disabled.
Logging Exceptions#
Capturing full exception information — including the traceback — is one of the most important uses of logging in production code. There are two ways to include traceback information in a log record:
logger.exception(msg)— logs atERRORlevel and automatically attaches the current exception’s traceback. Use this inside anexceptblock.logger.error(msg, exc_info=True)— equivalent but lets you choose the level.exc_info=Truecan be added to any level call.
1import logging, sys
2
3logging.basicConfig(
4 level=logging.DEBUG,
5 format="%(levelname)-8s %(name)s: %(message)s",
6 stream=sys.stdout,
7 force=True
8)
9
10logger = logging.getLogger("trading.risk")
11
12def calculate_var(returns: list, confidence: float) -> float:
13 """Value at Risk calculation (simplified)."""
14 if not returns:
15 raise ValueError("Cannot calculate VaR on an empty returns list")
16 sorted_returns = sorted(returns)
17 index = int((1 - confidence) * len(sorted_returns))
18 return sorted_returns[index]
19
20try:
21 var = calculate_var([], 0.95)
22except ValueError:
23 # logger.exception logs at ERROR and appends the full traceback automatically
24 logger.exception("VaR calculation failed")
[ERROR] VaR calculation failed
Traceback (most recent call last):
File "/var/folders/f0/69wncpqd02s3j1r_z5sfddd00000gq/T/ipykernel_48758/4191591863.py", line 21, in <module>
var = calculate_var([], 0.95)
File "/var/folders/f0/69wncpqd02s3j1r_z5sfddd00000gq/T/ipykernel_48758/4191591863.py", line 15, in calculate_var
raise ValueError("Cannot calculate VaR on an empty returns list")
ValueError: Cannot calculate VaR on an empty returns list
1import logging, sys
2
3logging.basicConfig(
4 level=logging.DEBUG,
5 format="%(levelname)-8s %(message)s",
6 stream=sys.stdout,
7 force=True
8)
9
10logger = logging.getLogger("trading.feed")
11
12# exc_info=True works at any level — useful when you want CRITICAL with traceback
13try:
14 prices = {"AAPL": 189.30, "MSFT": 415.20}
15 _ = prices["TSLA"] # KeyError
16except KeyError:
17 logger.critical("Missing price for required ticker", exc_info=True)
[CRITICAL] Missing price for required ticker
Traceback (most recent call last):
File "/var/folders/f0/69wncpqd02s3j1r_z5sfddd00000gq/T/ipykernel_48758/609590004.py", line 15, in <module>
_ = prices["TSLA"] # KeyError
~~~~~~^^^^^^^^
KeyError: 'TSLA'
Adding Context with extra#
Sometimes the message alone is insufficient — you need to attach structured data to a record (a user ID, request ID, ticker symbol, etc.) without stuffing it all into the message string. The extra parameter accepts a dictionary whose keys are added as attributes on the LogRecord.
You can then reference those custom fields in the format string with %(field_name)s.
1import logging, sys
2
3logging.basicConfig(
4 level=logging.DEBUG,
5 format="%(asctime)s %(levelname)-8s [user=%(user_id)s ticker=%(ticker)s] %(message)s",
6 datefmt="%H:%M:%S",
7 stream=sys.stdout,
8 force=True
9)
10
11logger = logging.getLogger("trading.orders")
12
13ctx = {"user_id": "U-4821", "ticker": "AAPL"}
14
15logger.info("Order validated", extra=ctx)
16logger.info("Order submitted to exchange", extra=ctx)
17logger.warning("Partial fill: 32 of 50 shares", extra=ctx)
[WARNING] Partial fill: 32 of 50 shares
Structured (JSON) Logging#
For applications that ship logs to a centralised platform (Elasticsearch, Splunk, Datadog, etc.), plain-text log records are harder to parse and query than structured JSON. The third-party library python-json-logger provides a JsonFormatter that serialises the entire LogRecord — including extra fields — as a single JSON object per line:
pip install python-json-logger
from pythonjsonlogger import jsonlogger
handler = logging.StreamHandler()
handler.setFormatter(jsonlogger.JsonFormatter(
fmt="%(asctime)s %(name)s %(levelname)s %(message)s"
))
logger.addHandler(handler)
logger.info("Trade executed", extra={"ticker": "AAPL", "shares": 50})
# Output: {"asctime": "...", "name": "trading", "levelname": "INFO",
# "message": "Trade executed", "ticker": "AAPL", "shares": 50}
Best Practices#
Use
logging.getLogger(__name__)at module level — Placelogger = logging.getLogger(__name__)near the top of each module file, outside any function or class. The name tracks the source automatically.Never use the root logger in library code — Libraries should create named loggers and attach only a
NullHandler(so output is suppressed by default). Let the application that imports the library configure where output goes.# At the top of your library package's __init__.py import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
Use
%slazy formatting, not f-strings — Writelogger.debug("Price: %s", price)rather thanlogger.debug(f"Price: {price}"). With lazy formatting, the string is only constructed if the record is actually going to be emitted, avoiding unnecessary work when the level is below the threshold.Set levels on handlers as well as loggers — The logger’s level gates record creation; each handler’s level gates whether that handler processes the record. Use both to route different severity ranges to different destinations.
Prefer
dictConfig()for applications — Externalising logging configuration makes it easy to change verbosity or destinations without touching application code.Close file handlers explicitly — Call
handler.close()when aFileHandleris no longer needed, or use a context manager, to ensure buffers are flushed and file handles are released.Use
logger.exception()insideexceptblocks — Always capture tracebacks in exception handlers. A log record without a traceback rarely contains enough information to diagnose a production issue.
Suggested LLM Prompts#
Explain the Python logging hierarchy in detail. How does log record propagation work from a child logger to the root logger? Provide a diagram or code example showing a three-level hierarchy with different levels and handlers at each level.
Compare Python’s
loggingmodule with simply usingprint()statements for debugging. In what scenarios is each approach appropriate? What specific production scenarios make the logging module indispensable?Describe how to implement structured logging in Python for a microservices architecture. Include examples using
extrafields and a JSON formatter, and explain how structured logs improve observability when forwarded to a centralised log aggregation platform.Walk through how to configure Python logging in a large application with multiple modules, a third-party library you want to silence, and two separate log destinations (console and rotating file). Show the full
dictConfigdictionary.What is the difference between
logger.error(),logger.exception(), andlogger.error(exc_info=True)? When would you choose each? Provide concrete examples from a financial application context.Explain the
LogRecordobject. What attributes does it carry, and how can you add custom attributes? Show how to write a customFormattersubclass that modifies the output based onLogRecordattributes.
Review Questions#
What are the five standard log levels in Python’s
loggingmodule? List them in order from lowest to highest severity and describe when each should be used.What is the default log level of the root logger, and why does this matter for a new Python program that has not called
basicConfig()?Why is
logging.basicConfig()sometimes a no-op? How do you force it to reconfigure the root logger in a Jupyter notebook environment?What is the difference between attaching a
Formatterto a Logger versus attaching it to a Handler? Why does the distinction matter?Explain log record propagation. What does
logger.propagate = Falsedo, and when would you use it?What is a
RotatingFileHandlerand why is it preferred over a plainFileHandlerin production applications?How does
logger.exception()differ fromlogger.error()? Why is it preferable inside anexceptblock?What is the purpose of the
extraparameter when calling a logging method? Give an example where usingextrais more appropriate than embedding context directly in the message string.What advantage does
logging.config.dictConfig()offer overlogging.basicConfig()for a production application?Why should library authors use
logging.NullHandler()and avoid callingbasicConfig()inside their library code?
Drill#
Open a terminal and create a file monitor.py. Work through the following steps:
At the top of the file, import
loggingand create a module-level logger:logger = logging.getLogger(__name__).Write a function
check_price(ticker: str, price: float, limit: float) -> Nonethat:Logs at
DEBUGlevel:"Checking {ticker}: price={price}, limit={limit}"Logs at
WARNINGlevel ifprice > limit:"{ticker} price ${price} exceeds limit ${limit}"Otherwise logs at
INFOlevel:"{ticker} within limit"
In a
if __name__ == "__main__":block, configure logging withbasicConfig()atDEBUGlevel using a format that includes timestamp, logger name, level, and message.Call
check_pricefor three tickers — make at least one exceed its limit.Run
python monitor.pyand observe the output.Change the
basicConfiglevel toINFOand re-run. What disappears?Modify the configuration to write output to both the console (
WARNINGand above) and a filemonitor.log(DEBUGand above) using explicitStreamHandlerandFileHandlerobjects instead ofbasicConfig.
Exercises#
Module-level logger with dual handlers — Write a module
trade_logger.pythat creates agetLogger(__name__)logger, attaches aStreamHandler(WARNING and above) and aFileHandler(DEBUG and above, filetrades.log), and exposes a functionlog_trade(ticker, shares, price, side)that logs the trade atINFOlevel. Demonstrate that the file contains DEBUG-level setup messages that do not appear on the console.Rotating log — Write a function
stress_log(n: int) -> Nonethat logsnrecords to aRotatingFileHandlercapped at 2 KB with 3 backup files. Call it withn=100. After it returns, list the backup files that were created and print the line count of each.Exception logger — Write a function
safe_divide(a: float, b: float) -> floatthat returnsa / bbut catchesZeroDivisionErrorand logs the full traceback usinglogger.exception(). Return0.0on error. Verify that the traceback appears in the log output.Custom filter — Create a filter class
HighValueFilterthat blocks any log record whose message does not contain the string"HIGH". Attach it to aStreamHandler. Emit three records — one with"HIGH"in the message and two without — and confirm only the matching record appears.