---
title: "Logger"
description: ""
icon: "scroll"
---

## Overview

Logger is a core component designed to record and track events, errors, and other important actions during application execution. It provides valuable insights into application behavior, performance, and potential issues, helping developers troubleshoot and monitor systems effectively.

In the BeeAI framework, the `Logger` class is an abstraction built on top of Python's built-in logging module, offering enhanced capabilities specifically designed for AI agent workflows.

<Note>
Supported in Python and TypeScript.
</Note>

---

## Key features

* Custom log levels: Adds additional log levels like TRACE (below DEBUG) for fine-grained control
* Customized formatting: Different formatting for regular logs vs. event messages
* Agent interaction logging: Special handling for agent-generated events and communication
* Error integration: Seamless integration with the framework's error handling system

---

## Getting started

### Basic usage

To use the logger in your application:

<CodeGroup>

{/* <!-- embedme python/examples/logger/base.py --> */}
```py Python [expandable]
from beeai_framework.logger import Logger

# Configure logger with default log level from the BEEAI_LOG_LEVEL variable
logger = Logger("app")

# Log at different levels
logger.trace("Trace!")
logger.debug("Debug!")
logger.info("Info!")
logger.warning("Warning!")
logger.error("Error!")
logger.fatal("Fatal!")

```

{/* <!-- embedme typescript/examples/logger/base.ts --> */}
```ts TypeScript [expandable]
import { Logger, LoggerLevel } from "beeai-framework/logger/logger";

// Configure logger defaults
Logger.defaults.pretty = true; // Pretty-print logs (default: false, can also be set via ENV: BEE_FRAMEWORK_LOG_PRETTY=true)
Logger.defaults.level = LoggerLevel.TRACE; // Set log level to trace (default: TRACE, can also be set via ENV: BEE_FRAMEWORK_LOG_LEVEL=trace)
Logger.defaults.name = undefined; // Optional name for logger (default: undefined)
Logger.defaults.bindings = {}; // Optional bindings for structured logging (default: empty)

// Create a child logger for your app
const logger = Logger.root.child({ name: "app" });

// Log at different levels
logger.trace("Trace!");
logger.debug("Debug!");
logger.info("Info!");
logger.warn("Warning!");
logger.error("Error!");
logger.fatal("Fatal!");

```

</CodeGroup>

## Configuration

The logger's behavior can be customized through environment variables:

* `BEEAI_LOG_LEVEL`: Sets the default log level (defaults to "INFO")

You can also set a specific level when initializing the logger.

### Custom log levels

The logger adds a TRACE level below DEBUG for extremely detailed logging:

```py Python [expandable]
# Configure a logger with a specific level
logger = Logger("app", level="TRACE")  # Or use logging constants like logging.DEBUG

# Log with the custom TRACE level
logger.trace("This is a very low-level trace message")
```

---

## Working with the logger

### Formatting

The logger uses a custom formatter that distinguishes between regular log messages and event messages:

* Regular logs: `{timestamp} | {level} | {module}:{function}:{line} - {message}`
* Event messages: `{timestamp} | {level} | {message}`

### Icons and formatting

When logging agent interactions, the logger automatically adds visual icons:

* User messages: 👤
* Agent messages: 🤖

This makes logs easier to read and understand when reviewing conversational agent flows.

## Error handling

The logger integrates with BeeAI framework's error handling system through the `LoggerError` class.

---

## Usage with agents

The Logger seamlessly integrates with agents in the framework. Below is an example that demonstrates how logging can be used in conjunction with agents and event emitters.

<CodeGroup>

{/* <!-- embedme python/examples/logger/agent.py --> */}
```py Python [expandable]
import asyncio
import sys
import traceback

from beeai_framework.agents.react import ReActAgent
from beeai_framework.backend import ChatModel
from beeai_framework.errors import FrameworkError
from beeai_framework.logger import Logger
from beeai_framework.memory import UnconstrainedMemory


async def main() -> None:
    logger = Logger("app", level="TRACE")

    agent = ReActAgent(llm=ChatModel.from_name("ollama:llama3.1"), tools=[], memory=UnconstrainedMemory())

    output = await agent.run("Hello!").observe(
        lambda emitter: emitter.on(
            "update", lambda data, event: logger.info(f"Event {event.path} triggered by {type(event.creator).__name__}")
        )
    )

    logger.info(f"Agent 🤖 : {output.last_message.text}")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except FrameworkError as e:
        traceback.print_exc()
        sys.exit(e.explain())

```

{/* <!-- embedme typescript/examples/logger/agent.ts --> */}
```ts TypeScript [expandable]
import { ReActAgent } from "beeai-framework/agents/react/agent";
import { UnconstrainedMemory } from "beeai-framework/memory/unconstrainedMemory";
import { Logger } from "beeai-framework/logger/logger";
import { Emitter } from "beeai-framework/emitter/emitter";
import { OllamaChatModel } from "beeai-framework/adapters/ollama/backend/chat";

// Set up logging
Logger.defaults.pretty = true;

const logger = Logger.root.child({
  level: "trace",
  name: "app",
});

// Log events emitted during agent execution
Emitter.root.match("*.*", (data, event) => {
  const logLevel = event.path.includes(".run.") ? "trace" : "info";
  logger[logLevel](`Event '${event.path}' triggered by '${event.creator.constructor.name}'`);
});

// Create and run an agent
const agent = new ReActAgent({
  llm: new OllamaChatModel("granite4:micro"),
  memory: new UnconstrainedMemory(),
  tools: [],
});

const response = await agent.run({ prompt: "Hello!" });
logger.info(response.result.text);

```
</CodeGroup>

---

## Examples

<CardGroup cols={2}>
  <Card title="Python" icon="python" href="https://github.com/i-am-bee/beeai-framework/tree/main/python/examples/logger">
    COMING SOON: Explore reference logger implementations in Python
  </Card>
  <Card title="TypeScript" icon="js" href="https://github.com/i-am-bee/beeai-framework/tree/main/typescript/examples/logger">
    COMING SOON: Explore reference logger implementations in TypeScript
  </Card>
</CardGroup>
