Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions agentops/logging/instrument_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,47 @@
import logging
import os
import atexit
from datetime import datetime
from typing import Any, TextIO
from agents import Span
from typing import Any

_original_print = builtins.print

LOGFILE_NAME = "agentops-tmp.log"

## Instrument loggers and print function to log to a file
# Instrument loggers and print function to log to a file


def setup_print_logger() -> None:
"""
~Monkeypatches~ *Instruments the built-in print function and configures logging to also log to a file.
Preserves existing logging configuration and console output behavior.
"""
log_file = os.path.join(os.getcwd(), LOGFILE_NAME)

file_logger = logging.getLogger('agentops_file_logger')
file_logger.setLevel(logging.DEBUG)

file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
file_handler.setLevel(logging.DEBUG)
file_logger.addHandler(file_handler)

# Ensure the new logger doesn't propagate to root
file_logger.propagate = False

def print_logger(*args: Any, **kwargs: Any) -> None:
"""
Custom print function that logs to file and console.

Args:
*args: Arguments to print
**kwargs: Keyword arguments to print
"""
message = " ".join(str(arg) for arg in args)
file_logger.info(message)

# print to console using original print
_original_print(*args, **kwargs)

# replace the built-in print with ours
builtins.print = print_logger

Expand All @@ -56,15 +56,15 @@ def cleanup():
for handler in file_logger.handlers[:]:
handler.close()
file_logger.removeHandler(handler)

# Restore the original print function
builtins.print = _original_print
except Exception as e:
# If something goes wrong during cleanup, just print the error
_original_print(f"Error during cleanup: {e}")

# Register the cleanup function to run when the process exits
atexit.register(cleanup)
atexit.register(cleanup)


def upload_logfile(trace_id: int) -> None:
Expand All @@ -83,4 +83,3 @@ def upload_logfile(trace_id: int) -> None:
client.api.v4.upload_logfile(log_content, trace_id)

os.remove(log_file)

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "agentops"
version = "0.4.7"
version = "0.4.8"
authors = [
{ name="Alex Reibman", email="[email protected]" },
{ name="Shawn Qiu", email="[email protected]" },
Expand Down
Loading