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 message | No, it scrolls away | Yes, to a file or a log service |
| Says how important it is | No | Five levels, from DEBUG to CRITICAL |
| Says when and where it came from | No | Time, 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.
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 brokeINFO 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.
| Part | What it does | You set it with |
|---|---|---|
| Logger | The part your code talks to. One per module, named after it | getLogger(__name__) |
| Level | Drops notes less important than your threshold | setLevel(...) |
| Handler | Sends the note to a destination: console, file, a service | StreamHandler, FileHandler |
| Formatter | Lays the note out: time, level, module, message | Formatter(...) |
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.
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())INFO: question classified as billing --- the file received --- DEBUG demo.flow: raw prompt: ... INFO demo.flow: question classified as billing
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.
| Level | Use it for | Example |
|---|---|---|
| DEBUG | Fine detail while building | The raw prompt before it is sent |
| INFO | Normal milestones | "Question classified as billing" |
| WARNING | Odd, but still working | "Search was slow, retrying" |
| ERROR | Something failed | "Tool call failed" |
| CRITICAL | The system cannot continue | "No database connection" |
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()))DEBUG 10 INFO 20 WARNING 30 ERROR 40 CRITICAL 50 fresh process printed: 'warning note'
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.
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 tracebackERROR 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.
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"}){"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.
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"}){"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:
| Record | Why |
|---|---|
| Request id | Ties every step of one request together |
| Step name and intent or route | Shows the path the agent took |
| Model name | The model can change under you; know which one answered |
| Input and output tokens | Cost and context limits, per step |
| Tool name, latency, attempt number | Finds slow tools and retry storms |
| Outcome | Answered, 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.
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.
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))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.
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.