Logging
Validate settings once and separate operational events from user output.
On this page
The concept
Configuration is input too. Read it at a boundary, validate it, and pass the resulting value to the operations that need it. The example accepts a mapping so configuration behavior can be tested without changing the real environment. A production boundary could supply os.environ.
Logging records events with levels such as DEBUG, INFO, WARNING, and ERROR. Configure handlers in the entry point rather than inside every utility function. Log useful context, not secrets. Parameterized log messages defer message formatting until it is needed.
Worked example
import logging
import sys
def load_limit(config):
limit = int(config.get("APP_LIMIT", "10"))
if not 1 <= limit <= 100:
raise ValueError("APP_LIMIT must be between 1 and 100")
return limit
def main():
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s", stream=sys.stdout)
logger = logging.getLogger(__name__)
limit = load_limit({"APP_LIMIT": "5"})
logger.info("Processing up to %s records", limit)
if __name__ == "__main__":
main()Trace the result
- load_limit converts a setting and rejects values outside 1 through 100.
- main configures a deterministic INFO stream for the demonstration.
- The logger reports a validated limit; it is not responsible for parsing the setting.
INFO Processing up to 5 recordsLine-by-line walkthrough
Line 1: import logging
Load logging (operational event reporting). Importing makes these names available; it is not a call to every function in the module.
Line 2: import sys
Load sys (interpreter information and command-line arguments). Importing makes these names available; it is not a call to every function in the module.
Lines 5–9: def load_limit(config):
Define the function load_limit with input names config. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 6: limit = int(config.get("APP_LIMIT", "10"))
Evaluate int(config.get('APP_LIMIT', '10')), then bind or update limit with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Lines 7–8: if not 1 <= limit <= 100:
Evaluate not 1 <= limit <= 100. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 8: raise ValueError("APP_LIMIT must be between 1 and 100")
Raise ValueError('APP_LIMIT must be between 1 and 100'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Line 9: return limit
Evaluate limit and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 12–16: def main():
Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 13: logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s", stream=sys.stdout)
Call logging.basicConfig with the displayed arguments. This call may have an effect even when its return value is not assigned.
Line 14: logger = logging.getLogger(__name__)
Evaluate logging.getLogger(__name__), then bind or update logger with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 15: limit = load_limit({"APP_LIMIT": "5"})
Evaluate load_limit({'APP_LIMIT': '5'}), then bind or update limit with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 16: logger.info("Processing up to %s records", limit)
Call logger.info with the displayed arguments. This call may have an effect even when its return value is not assigned.
Lines 19–20: if __name__ == "__main__":
Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.
Line 20: main()
Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.
Common mistake
Do not log passwords, tokens, or full confidential payloads. Also avoid silently accepting malformed settings as defaults.