Python · The language, not just syntax

How do you use logging correctly in a Python service?

MediumloggingobservabilityproductionUpdated Oct 2026
Quiz this track

Short answer

Use the logging module with a module-level logger, configure handlers once at the application entry point, log structured context at appropriate levels, and never log secrets or use print in production.

Loggers form a hierarchy by dotted name. Records propagate to ancestor handlers, and the root logger is configured once by the application. Libraries should add a NullHandler and leave configuration to the host application.

python
import logging

logger = logging.getLogger(__name__)

def charge(order_id, amount):
    logger.info("charging order", extra={"order_id": order_id, "amount": amount})
    try:
        return gateway.charge(amount)
    except TimeoutError:
        logger.exception("gateway timeout", extra={"order_id": order_id})
        raise
logger.exception records the traceback at error level. extra attaches structured fields that log aggregation can index.

Production rules

  • Log at boundaries with identifiers, outcome and latency, not every internal step
  • Use lazy formatting: logger.info("user %s", user_id) instead of an f-string
  • Never log passwords, tokens, full card numbers or personal data
  • Configure JSON output in production so logs are queryable and consistent

Log levels are an operational contract. DEBUG for development detail, INFO for significant business events, WARNING for recoverable anomalies, ERROR for failed operations, CRITICAL for service-threatening conditions. If everything is INFO, alerts become noise.

Include a correlation or request id in every log line so you can trace one request across services. Without it, distributed debugging turns into guesswork.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why should a library not call basicConfig?
  2. 2What does logger.exception add compared to logger.error?
  3. 3Why is lazy formatting preferred over f-strings in log calls?
  4. 4What would you include in a structured log for a request?

Say it in the interview

I create a module-level logger with getLogger(__name__) and configure handlers once at the entry point. I log business events with identifiers and outcomes, use logger.exception when I want a traceback, and keep secrets out. I prefer lazy formatting so work is skipped when a level is disabled and structured JSON so logs are queryable. Correlation ids are essential for tracing requests across services.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.