← Home · Tutorial 15 · Production engineering

Logging for AI apps

Replace print() with logging, record what matters for each model call, and keep secrets out of your logs.

Last reviewed 19 October 2026 · Written with AI assistance and reviewed by me

Where this comes from: Python's own Logging HOWTO and Logging Cookbook, plus Anthropic's Messages API reference for the token-usage fields. The examples are my own, and every snippet that does not call an API was run to produce the output shown.
Who this is for: anyone who has built a small AI script or agent and wants to know what it did when something went wrong. You will learn how to replace print() with Python's logging module, what to record for each model call, and what to keep out of your logs.

1Purpose first

Why a record written at the time matters.

When an agent gives a strange answer at 2 a.m., nobody was watching. The only way to find out what happened is a record written at the time. That record is the log.

Most people start with print(). It shows a message once, on your screen, and then it is gone. Logging is a note-taker built into Python: it writes each message down, stamps it with a time, marks how important it is, says which part of the code wrote it, and sends it wherever you choose.

2print() versus logging

What you gain by switching.

print()logging
Remembers the messageNo, it scrolls awayYes, to a file or a log service
Says how important it isNoFive levels, from DEBUG to CRITICAL
Says when and where it came fromNoTime, level and module name, if you ask

The practical difference is control. With logging you can switch detail up while chasing a bug and back down afterwards, without editing a single line of your code.

3Hire the note-taker

Two lines of set-up, one per note.

Two lines of set-up, and one line per note. Python's documentation recommends one logger per module, named after the module with logging.getLogger(__name__), so each line tells you where it came from.

Python
import logging, sys

logging.basicConfig(stream=sys.stdout, force=True, level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")   # real use adds %(asctime)s too
logger = logging.getLogger("agent")

logger.debug("raw prompt: ...")                    # below INFO, so it is skipped
logger.info("question classified as billing")      # normal milestone
logger.warning("search was slow, retrying")        # odd, but still working
logger.error("tool call failed")                   # something broke
Output (run to check)
INFO agent: question classified as billing
WARNING agent: search was slow, retrying
ERROR agent: tool call failed

The debug note is missing because the threshold is set to INFO and DEBUG sits below it. Setting the level to DEBUG while you investigate, and back to INFO afterwards, is the whole trick. In real use, add %(asctime)s to the format so every line carries a time.

4How the note-taker works

Logger, level, handler and formatter.

Four parts, each with one job. Your code only says what happened. The rest is set up once, at the top of the app.

How one note travels
Your codelogger.info(...)
→
Loggeris it important enough?
→
Handlerwhere does it go?
→
Formatterhow does it look?
→
Destinationscreen, file, service
PartWhat it doesYou set it with
LoggerThe part your code talks to. One per module, named after itgetLogger(__name__)
LevelDrops notes less important than your thresholdsetLevel(...)
HandlerSends the note to a destination: console, file, a serviceStreamHandler, FileHandler
FormatterLays the note out: time, level, module, messageFormatter(...)

One logger can feed several handlers, each with its own level and layout. Here the screen shows INFO and above in a short layout, while a second handler keeps everything, including DEBUG, in a fuller one.

Python
import io, logging, sys

log = logging.getLogger("demo.flow")
log.handlers = []; log.propagate = False; log.setLevel(logging.DEBUG)

screen = logging.StreamHandler(sys.stdout)       # destination 1: the console
screen.setLevel(logging.INFO)                    # shows INFO and above
screen.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))

notebook = io.StringIO()                         # destination 2: stands in for a log file
filed = logging.StreamHandler(notebook)
filed.setLevel(logging.DEBUG)                    # keeps everything
filed.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))

log.addHandler(screen); log.addHandler(filed)

log.debug("raw prompt: ...")
log.info("question classified as billing")

print("--- the file received ---")
print(notebook.getvalue().strip())
Output (run to check)
INFO: question classified as billing
--- the file received ---
DEBUG demo.flow: raw prompt: ...
INFO demo.flow: question classified as billing
Ease of use: it ships with Python, so there is nothing to install. Two lines get you started, as in the next section. Detail goes up or down with one setting, and nothing needs deleting afterwards, unlike print(). The basicConfig() shortcut wires up one handler and one formatter for you.

5Levels, and the default that surprises people

Five levels and one gotcha.

LevelUse it forExample
DEBUGFine detail while buildingThe raw prompt before it is sent
INFONormal milestones"Question classified as billing"
WARNINGOdd, but still working"Search was slow, retrying"
ERRORSomething failed"Tool call failed"
CRITICALThe system cannot continue"No database connection"
Python
import logging
for name in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]:
    print(name.ljust(9), getattr(logging, name))

# what happens with NO setup at all? Run a fresh Python process to find out.
import subprocess, sys
fresh = "import logging; log = logging.getLogger('app'); log.info('info note'); log.warning('warning note')"
out = subprocess.run([sys.executable, "-c", fresh], capture_output=True, text=True)
print("fresh process printed:", repr((out.stdout + out.stderr).strip()))
Output (run to check)
DEBUG     10
INFO      20
WARNING   30
ERROR     40
CRITICAL  50
fresh process printed: 'warning note'
The mistake almost everyone makes: out of the box, only WARNING and above are shown. logger.info() prints nothing until you set the level to INFO, as the output above shows. Many people conclude logging is broken when it is only filtering.

6Recording errors

The traceback, for free.

Inside an except block, use logger.exception() instead of logger.error(). It writes your message and the full traceback, which is usually what you wanted at 2 a.m.

Python
import logging, sys
logging.basicConfig(stream=sys.stdout, force=True, level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("agent.tools")

def lookup(order_id):
    return {"A1": "shipped"}[order_id]             # raises KeyError for an unknown id

try:
    lookup("Z9")
except KeyError:
    log.exception("order lookup failed")           # message plus the full traceback
Output (run to check)
ERROR order lookup failed
Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "<string>", line 7, in lookup
KeyError: 'Z9'

Call it only inside an exception handler. Elsewhere there is no traceback to record.

7Structured logs

One JSON object per event.

A line such as "tool called get_order_status in 212 ms" is easy for you to read and awkward for a machine to search. Structured logging writes each event as data, usually one JSON object per line, so you can filter by field: every slow tool call, every retry, every request by one user.

Python's extra= argument attaches fields to a record, and a small formatter turns the record into JSON.

Python
import json, logging, sys

class JsonFormatter(logging.Formatter):
    # fields every record has; anything else came in through extra=
    BUILTIN = set(logging.LogRecord("", 0, "", 0, "", (), None).__dict__) | {"message"}
    def format(self, record):
        data = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}
        data.update({k: v for k, v in record.__dict__.items() if k not in self.BUILTIN})
        return json.dumps(data)          # add a timestamp field in real use

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("demo.json")
log.handlers = [handler]; log.propagate = False; log.setLevel(logging.INFO)

log.info("tool called", extra={"tool": "get_order_status", "latency_ms": 212})
log.warning("retrying", extra={"attempt": 2, "reason": "rate_limited"})
Output (run to check)
{"level": "INFO", "logger": "demo.json", "msg": "tool called", "tool": "get_order_status", "latency_ms": 212}
{"level": "WARNING", "logger": "demo.json", "msg": "retrying", "attempt": 2, "reason": "rate_limited"}

Log services read JSON lines directly, so the same line works on your laptop and in production. Libraries such as structlog package this up, but the idea needs only the standard library.

8What to log per model call

Request id, tokens, latency, outcome.

An agent makes several steps per request, so a log that cannot tie the steps together is hard to use. Give each request an id and stamp it on every line. A LoggerAdapter does the stamping so you do not repeat it.

Python
import json, logging, sys

class JsonFormatter(logging.Formatter):
    BUILTIN = set(logging.LogRecord("", 0, "", 0, "", (), None).__dict__) | {"message"}
    def format(self, record):
        data = {"level": record.levelname, "step": record.getMessage()}
        data.update({k: v for k, v in record.__dict__.items() if k not in self.BUILTIN and k != "name"})
        return json.dumps(data)

class Ctx(logging.LoggerAdapter):                 # stamps every line with the same request id
    def process(self, msg, kwargs):
        kwargs["extra"] = {**self.extra, **kwargs.get("extra", {})}
        return msg, kwargs

handler = logging.StreamHandler(sys.stdout); handler.setFormatter(JsonFormatter())
base = logging.getLogger("demo.agent"); base.handlers = [handler]; base.propagate = False; base.setLevel(logging.INFO)
log = Ctx(base, {"request_id": "req-7f3a"})

# a stand-in agent run: the numbers are made up, the pattern is what matters
log.info("classify", extra={"intent": "billing", "input_tokens": 120, "output_tokens": 6})
log.info("tool_call", extra={"tool": "get_order_status", "latency_ms": 212, "attempt": 1})
log.info("respond", extra={"input_tokens": 410, "output_tokens": 85, "outcome": "answered"})
Output (run to check)
{"level": "INFO", "step": "classify", "request_id": "req-7f3a", "intent": "billing", "input_tokens": 120, "output_tokens": 6}
{"level": "INFO", "step": "tool_call", "request_id": "req-7f3a", "tool": "get_order_status", "latency_ms": 212, "attempt": 1}
{"level": "INFO", "step": "respond", "request_id": "req-7f3a", "input_tokens": 410, "output_tokens": 85, "outcome": "answered"}

The numbers here are made up, but the fields are the useful ones for any model-backed app:

RecordWhy
Request idTies every step of one request together
Step name and intent or routeShows the path the agent took
Model nameThe model can change under you; know which one answered
Input and output tokensCost and context limits, per step
Tool name, latency, attempt numberFinds slow tools and retry storms
OutcomeAnswered, refused, handed to a human, failed

The model response already carries the token counts. In the Anthropic API they are in the usage object, as input_tokens and output_tokens, with separate fields for cache writes and reads.

Shape from the docs, not run here
response = client.messages.create(model=MODEL_ID_FROM_THE_DOCS, ...)
log.info("respond", extra={
    "input_tokens": response.usage.input_tokens,
    "output_tokens": response.usage.output_tokens,
})

9What never to log

Secrets and personal data.

Logs are copied, searched, kept for months and read by people who never saw the conversation. Treat them as less private than the app itself.

Never log: API keys, passwords or tokens, and payment details. Do not log whole prompts and replies by default either, because they often contain personal data. Log sizes and ids instead, and capture full text only when needed, only briefly, and with redaction.
Python
import re

def redact(text):
    text = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "[email]", text)       # email addresses
    text = re.sub(r"\b\d{10,}\b", "[number]", text)                    # long digit runs (phones, cards)
    return text

msg = "Customer asked: write to priya@example.com or call 9876543210 about order A1"
print(redact(msg))
Output (run to check)
Customer asked: write to [email] or call [number] about order A1

This regex is a starting point, not a guarantee. Real redaction needs testing against your own data, and the safest log line is the one that never held the secret.

10Habits that save you

Cost, noise and where set-up belongs.

  • Pass arguments, do not build strings. log.info("found %s chunks", n) only formats the message if it will be emitted, which matters when the level filters it out.
  • Do not log in a tight loop. One line per step is useful, one per token is noise and cost.
  • Libraries do not configure logging. Application code sets handlers and levels once at the top. Modules just call getLogger(__name__).
  • Logs record what happened. They do not prove the answer was right. For quality, see Evaluating RAG.

11Check yourself

Short questions, a try-it and one line to remember.

Why does logger.info() show nothing by default?

The default threshold is WARNING, so INFO and DEBUG are filtered until you set a lower level.

When do you use logger.exception()?

Inside an except block, to record your message plus the full traceback.

Why log as JSON?

Each event becomes data you can filter by field, such as tool name or request id, instead of text you have to parse.

What should an agent log for each model call?

A request id, step, model, input and output tokens, latency and outcome. Not secrets, and not full personal text.

Try it: take any script you have that uses print() for progress. Replace each print with a logger call at the right level. Run it at INFO, then at DEBUG, and compare the output. Then add one JSON field, such as a duration, to a line.
One line to remember: "print() talks to you now; logging leaves notes for whoever investigates later, usually future you."
Sources: Python Logging HOWTO and Logging Cookbook; Anthropic Messages API reference for usage fields. Library and API details change, so check the current docs. Independent notes, not affiliated with or endorsed by any company or course named here. Examples and wording are my own.