Python
Explore reference logger implementations in Python
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.
To use the logger in your application:
from beeai_framework.logger import Logger
# Configure logger with default log level from the BEEAI_LOG_LEVEL variablelogger = Logger("app")
# Log at different levelslogger.trace("Trace!")logger.debug("Debug!")logger.info("Info!")logger.warning("Warning!")logger.error("Error!")logger.fatal("Fatal!")import { Logger, LoggerLevel } from "beeai-framework/logger/logger";
// Configure logger defaultsLogger.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 appconst logger = Logger.root.child({ name: "app" });
// Log at different levelslogger.trace("Trace!");logger.debug("Debug!");logger.info("Info!");logger.warn("Warning!");logger.error("Error!");logger.fatal("Fatal!");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.
The logger adds a TRACE level below DEBUG for extremely detailed logging:
# Configure a logger with a specific levellogger = Logger("app", level="TRACE") # Or use logging constants like logging.DEBUG
# Log with the custom TRACE levellogger.trace("This is a very low-level trace message")The logger uses a custom formatter that distinguishes between regular log messages and event messages:
{timestamp} | {level} | {module}:{function}:{line} - {message}{timestamp} | {level} | {message}When logging agent interactions, the logger automatically adds visual icons:
This makes logs easier to read and understand when reviewing conversational agent flows.
The logger integrates with BeeAI framework’s error handling system through the LoggerError class.
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.
import asyncioimport sysimport traceback
from beeai_framework.agents.react import ReActAgentfrom beeai_framework.backend import ChatModelfrom beeai_framework.errors import FrameworkErrorfrom beeai_framework.logger import Loggerfrom 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())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 loggingLogger.defaults.pretty = true;
const logger = Logger.root.child({ level: "trace", name: "app",});
// Log events emitted during agent executionEmitter.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 agentconst agent = new ReActAgent({ llm: new OllamaChatModel("granite4:micro"), memory: new UnconstrainedMemory(), tools: [],});
const response = await agent.run({ prompt: "Hello!" });logger.info(response.result.text);