Agentic AI · Intermediate level

Intermediate level · Module 1: Python for AI Agent Development · Lesson 3 of 3

Logging and Testing Agent Code

Learners add structured logging of every model and tool call and write tests that run against the scripted model, so that agent code can be changed safely.

In this lesson you will

  • Log agent steps in a structured way
  • Test agent code with the scripted model

Key concepts

logging modulestructured log recordstrace IDspytestdeterministic tests

The lesson

Use Python's logging module to record each step with a task ID: the model call (without secrets), the tool requested, its arguments, the result size, the time taken and the tokens used. Writing records as JSON lines makes them easy to search later.

Tests run against the scripted model, so they are fast, free and repeatable: given this question and these scripted responses, the agent must call this tool and produce this output.

Keep personal data out of logs where possible, and decide how long logs are kept.

Step by step

  1. Configure logging to write JSON lines with a task ID.
  2. Log model and tool calls in the agent loop.
  3. Write three pytest tests using the scripted model.
  4. Run the tests and read one complete trace.

Practice activity

Add structured logging and three tests to the project skeleton.

Expected result: Passing tests and a readable JSON trace for one task.

Check your understanding

  1. Why run tests against a scripted model?

    Show answer

    They are fast, free and give the same result every time.

  2. What should never be written to logs?

    Show answer

    Secrets such as API keys, and unnecessary personal data.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.