---
title: "Log agent step events with hooks in C#"
url: https://recursiveai.org/onellm/cookbook/register-local-agent-lifecycle-hook/
description: "Log AI agent step events in C# with OneLLM lifecycle hooks. See state changes and tool names in a runnable .NET 10 example that needs no API key."
version: "1.0.1"
---

# Log agent step events with hooks in C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/register-local-agent-lifecycle-hook/register-local-agent-lifecycle-hook.zip)

Use `BeforeToolCall` or `AfterToolCall` to log tool steps and `OnStateChange` to log changes in the run’s state.

```shell
dotnet add package RecursiveAI.OneLlm
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneLlm;
var runtime = new Runtime();
runtime.Hooks.OnStateChange((step, _) => {
    Console.WriteLine(step.To);
    return ValueTask.CompletedTask;
});
```

Unzip [the example](https://recursiveai.org/onellm/cookbook/register-local-agent-lifecycle-hook/register-local-agent-lifecycle-hook.zip), then `dotnet run`.

Start an agent on that `runtime` to see its state changes. The example below logs `running` and `stopped`, with the tool call between them.

## The full program

The agent definition and its only input, “Print a label,” are YAML inside `Program.cs`. The example doesn’t print a physical label: the in-process `ScriptedProvider`, which ignores the model name `gpt-6-luna` when choosing its reply, supplies the `task_complete` call so you can see the callbacks fire without a model server or an API key.

```csharp
using OneLlm;
using OneLlm.Definitions;
using OneLlm.Hooks;
using OneLlm.Testing;

var runtime = new Runtime();
runtime.Hooks.OnStateChange((step, _) =>
{
    Console.WriteLine(step.To);
    return ValueTask.CompletedTask;
});

var stub = new ScriptedProvider("openai");
runtime.Providers.Set("openai", stub);
stub.Enqueue(new ScriptStep { ToolCalls =
    [new("done", "task_complete", """
        {"result":"Label printed.","summary":"Done"}
        """)]
});

runtime.Hooks.BeforeToolCall((step, _) =>
{
    Console.WriteLine($"Calling {step.Call.Tool}");
    return ValueTask.FromResult(HookDecision.Continue);
});

var agent = AgentDefinition.Parse("""
    name: label
    model: gpt-6-luna
    systemPrompt: Confirm the label with task_complete.
    initialPrompts:
      - user: [{text: Print a label.}]
    references:
      - tools: [task_complete]
    """);
var result = await runtime.RunAgentAsync(agent);
Console.WriteLine(result.Text);
```

```text
running
Calling task_complete
stopped
Label printed.
```

If a logging callback throws, the hook type matters: an `OnStateChange` failure is recorded and the run continues, but a `BeforeToolCall` failure blocks that tool step.

## Variations

**Log the transition, not just the new state.** Replace the first callback with this one:

```csharp
runtime.Hooks.OnStateChange((step, _) =>
{
    var from = step.From ?? "(none)";
    Console.WriteLine($"{from} -> {step.To}");
    return ValueTask.CompletedTask;
});
```

## Related recipes

- [Build an AI agent with tool calling in C#](https://recursiveai.org/onellm/cookbook/ai-agent-with-tools-csharp/)
- [Test LLM code without an API key](https://recursiveai.org/onellm/cookbook/test-llm-code-without-api-key/)

## The short answer

Use `Runtime.Hooks.OnStateChange` for lifecycle events like entering `running` or `stopped`. For individual steps inside a run, register `BeforeToolCall` or `AfterToolCall`. A tool hook returns a decision; return `HookDecision.Continue` when all you want to do is log the step.

## What is an example of an agent hook?

In the example, `BeforeToolCall` writes the name of `task_complete` just before OneLLM invokes it. That line means the agent is about to call the tool, not that the tool succeeded. The `stopped` line comes from a separate callback that observes a change in the agent’s state. Keep the two lines distinct in a production log: a tool event answers “What is it doing?” and a state event answers “Is the run still going?”

The sample logs only state and tool name. You don’t need to copy the prompt, arguments, or tool result into your log to tell when a step ran. If your app runs several agents, add the instance ID from the hook context so you can group their lines separately.

## When should you use an agent hook?

Use a state observer for a progress display or a lifecycle log. It doesn’t return a decision, so you can’t use it to veto a state transition. Use `BeforeInference` if you need to see when a model call is about to start, or `BeforeToolCall` when you want to see local tool invocations. Those are interceptors: they can affect the run, so a logging-only interceptor should return `Continue` and keep its logging path simple. The [hook decision table](https://recursiveai.org/onellm/docs/agents/#hooks) lists which decisions each callback accepts.

Register host hooks before you start the run. The [registry at this release](https://github.com/recursive-ai-oss/onellm-csharp/blob/ea17c434f4e469046ea583ad334deb6a8974e28b/src/OneLlm/Hooks/HookRegistry.cs#L9-L11) says “Changes apply to runs that start afterwards.” Two hooks at the same point run in registration order, so if an earlier interceptor blocks the step, don’t count on a later one to log it.
