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
4 changes: 3 additions & 1 deletion openevolve/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,9 @@ async def main_async() -> int:

# Override log level if specified
if args.log_level:
logging.getLogger().setLevel(getattr(logging, args.log_level))
log_level = getattr(logging, args.log_level)
logging.getLogger().setLevel(log_level)
logging.getLogger("openevolve").setLevel(log_level)

# Run evolution
best_program = await openevolve.run(
Expand Down
104 changes: 95 additions & 9 deletions openevolve/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@
from openevolve.selection import IslandSelector
from openevolve.utils.code_utils import extract_code_language
from openevolve.utils.format_utils import format_improvement_safe, format_metrics_safe
from openevolve.utils.logging_utils import LoggerPrefixFilter
from openevolve.utils.logging_utils import (
LoggerPrefixFilter,
RunIsolationFilter,
current_run_id,
)

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -69,8 +73,17 @@ def __init__(
)
os.makedirs(self.output_dir, exist_ok=True)

# Set up logging
self._setup_logging()
# Generate unique run ID to isolate log handlers for concurrent or sequential runs (#295)
self.run_id = uuid.uuid4().hex[:8]
self._log_handlers: List[logging.Handler] = []
self._log_file: Optional[str] = None

# Set up logging within this run's context so startup logs are captured by this run
token = current_run_id.set(self.run_id)
try:
self._setup_logging()
finally:
current_run_id.reset(token)

# Manual mode queue lives in <openevolve_output>/manual_tasks_queue
self._setup_manual_mode_queue()
Expand Down Expand Up @@ -201,13 +214,25 @@ def __init__(
self.parallel_controller = None

def _setup_logging(self) -> None:
"""Set up logging"""
"""Set up per-run logging attached to the 'openevolve' package logger.

Attaching handlers to the 'openevolve' package logger with propagate=False
rather than the global root logger prevents polluting the host application's
logging namespace. A RunIsolationFilter ensures that each handler only
processes log records generated within this instance's execution context,
preventing duplicate console output and cross-written log files when multiple
OpenEvolve instances run in parallel (GitHub issue #295).
"""
log_dir = self.config.log_dir or os.path.join(self.output_dir, "logs")
os.makedirs(log_dir, exist_ok=True)

# Set up root logger
root_logger = logging.getLogger()
root_logger.setLevel(getattr(logging, self.config.log_level))
# Target the 'openevolve' package logger rather than the root logger (#295)
pkg_logger = logging.getLogger("openevolve")
pkg_logger.setLevel(getattr(logging, self.config.log_level))
pkg_logger.propagate = False

# Per-run isolation filter matching this controller instance's run_id
run_filter = RunIsolationFilter(self.run_id)

# Optional prefix for all logger names (issue #290): rewriting
# record.name at the handler level means every downstream module
Expand All @@ -218,13 +243,16 @@ def _setup_logging(self) -> None:

# Add file handler
log_file = os.path.join(log_dir, f"openevolve_{time.strftime('%Y%m%d_%H%M%S')}.log")
self._log_file = log_file
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
file_handler.addFilter(run_filter)
if prefix_filter is not None:
file_handler.addFilter(prefix_filter)
root_logger.addHandler(file_handler)
pkg_logger.addHandler(file_handler)
self._log_handlers.append(file_handler)

# Add console handler
console_handler = logging.StreamHandler()
Expand All @@ -235,10 +263,43 @@ def _setup_logging(self) -> None:
console_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
console_handler.addFilter(prefix_filter)
console_handler.setFormatter(logging.Formatter(console_format))
root_logger.addHandler(console_handler)
console_handler.addFilter(run_filter)
pkg_logger.addHandler(console_handler)
self._log_handlers.append(console_handler)

logger.info(f"Logging to {log_file}")

def _cleanup_logging(self) -> None:
"""Remove and close all logging handlers registered for this instance.

Detaches handlers from the 'openevolve' package logger and closes their
underlying file streams, releasing resources and avoiding file locking contention (#295).
"""
pkg_logger = logging.getLogger("openevolve")
for handler in list(getattr(self, "_log_handlers", [])):
try:
pkg_logger.removeHandler(handler)
handler.close()
except Exception:
pass
self._log_handlers = []

def close(self) -> None:
"""Release resources including evolution tracer and logging handlers."""
if hasattr(self, "evolution_tracer") and self.evolution_tracer:
try:
self.evolution_tracer.close()
except Exception:
pass
self._cleanup_logging()

def __del__(self) -> None:
"""Ensure logging handlers are closed if instance is garbage collected."""
try:
self._cleanup_logging()
except Exception:
pass

def _setup_manual_mode_queue(self) -> None:
"""
Set up manual task queue directory if llm.manual_mode is enabled
Expand Down Expand Up @@ -325,6 +386,31 @@ async def run(
Raises:
EvolutionFailedError: If iterations ran but none produced a candidate program
"""
# Ensure run_id exists even if instance was created without __init__ (e.g. in tests)
if not hasattr(self, "run_id") or not self.run_id:
self.run_id = uuid.uuid4().hex[:8]
if not hasattr(self, "_log_handlers"):
self._log_handlers = []

# If handlers were cleaned up or never initialized, set up logging for this run
if not self._log_handlers:
self._setup_logging()

# Activate this instance's run ID in context so downstream logs are routed to our handlers
token = current_run_id.set(self.run_id)
try:
return await self._run_evolution(iterations, target_score, checkpoint_path)
finally:
current_run_id.reset(token)
self._cleanup_logging()

async def _run_evolution(
self,
iterations: Optional[int] = None,
target_score: Optional[float] = None,
checkpoint_path: Optional[str] = None,
) -> Optional[Program]:
"""Internal evolution loop execution under active run context."""
max_iterations = self.config.max_iterations if iterations is None else iterations
# Determine starting iteration
start_iteration = 0
Expand Down
118 changes: 109 additions & 9 deletions openevolve/utils/logging_utils.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,93 @@
"""Logging helpers shared across OpenEvolve.

Provides :class:`LoggerPrefixFilter`, a handler-level filter that rewrites
``record.name`` so every downstream module logger appears under a common
prefix. This lets users tell apart log output coming from multiple concurrent
``OpenEvolve`` runs (GitHub issue #290).
Provides:
- :data:`current_run_id`: Context variable tracking the currently active OpenEvolve run ID.
- :class:`RunIsolationFilter`: A handler-level filter that isolates log messages to their
respective run context, preventing cross-writing and duplicate log emissions when multiple
runs execute in parallel within the same Python process (GitHub issue #295).
- :class:`LoggerPrefixFilter`: A handler-level filter that rewrites ``record.name`` so every
downstream module logger appears under a common prefix (GitHub issue #290).
"""

import contextvars
import logging
from typing import Optional

# Context variable holding the unique run ID for the currently executing OpenEvolve instance.
# In asynchronous (asyncio) or threaded workflows, context variables are copied per-task,
# allowing multiple concurrent runs in the same process to maintain their own isolated run ID.
current_run_id: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
"openevolve_current_run_id", default=None
)


def get_current_run_id() -> Optional[str]:
"""Retrieve the currently active OpenEvolve run ID, or None if outside a run context."""
return current_run_id.get()


def set_current_run_id(run_id: Optional[str]) -> contextvars.Token:
"""Set the active OpenEvolve run ID for the current execution context.

Args:
run_id: Unique string identifier for the run, or None to clear.

Returns:
A contextvars.Token that can be passed to reset_current_run_id.
"""
return current_run_id.set(run_id)


def reset_current_run_id(token: contextvars.Token) -> None:
"""Reset the active OpenEvolve run ID using the provided context token.

Args:
token: The token returned by a prior set_current_run_id call.
"""
current_run_id.reset(token)


class RunIsolationFilter(logging.Filter):
"""Filter log records so handlers only process records from their matching run.

When multiple OpenEvolve instances run concurrently in the same process
(e.g., parallel runs in the same event loop or thread pool), they attach
handlers to the shared ``openevolve`` package logger. Without filtering,
each instance's handlers would receive log records from all other runs,
leading to duplicated console output and cross-written log files (GitHub issue #295).

This filter ensures that a handler only emits records produced while its
associated run context is active. If no run context is active (e.g.,
standalone logging during setup or in test suites outside ``run()``),
the record is permitted through so information is not lost.
"""

def __init__(self, run_id: str) -> None:
"""Initialize the filter for a specific run ID.

Args:
run_id: The unique identifier of the OpenEvolve run instance.
"""
super().__init__()
self.run_id = run_id

def filter(self, record: logging.LogRecord) -> bool:
"""Filter log records by matching against the active run context.

Args:
record: The log record to inspect.

Returns:
True if the record belongs to this run or if no active run context is set;
False if another run context is currently active.
"""
active_run = current_run_id.get()
# If an active run is configured in context, only allow records matching this run ID
if active_run is not None:
return active_run == self.run_id
# If no active run is set (e.g., un-scoped calls or direct utility usage), allow through
return True


class LoggerPrefixFilter(logging.Filter):
"""Rewrite ``record.name`` to live under a configured prefix.
Expand All @@ -19,16 +98,37 @@ class LoggerPrefixFilter(logging.Filter):
then show the prefixed name, which makes concurrent runs distinguishable
and greppable in shared log output.

The filter is idempotent: names that already carry the prefix are left
untouched, so a record flowing through several handlers that share the
same filter instance is only prefixed once.
The filter is idempotent and avoids prefix stacking across multiple
handlers: the original un-prefixed name is saved so that applying filters
with different prefixes does not create nested prefixes like
``run2.run1.openevolve.controller``.
"""

def __init__(self, prefix: Optional[str] = None) -> None:
"""Initialize the prefix filter.

Args:
prefix: Optional prefix string to prepend to record logger names.
"""
super().__init__()
self.prefix = prefix or ""

def filter(self, record: logging.LogRecord) -> bool:
if self.prefix and not record.name.startswith(self.prefix + "."):
record.name = f"{self.prefix}.{record.name}"
"""Prepend prefix to record name without stacking multiple prefixes.

Args:
record: The log record to format.

Returns:
Always True (does not suppress records, only alters record.name).
"""
# Store original logger name so multiple handlers or filters do not stack prefixes
if not hasattr(record, "_openevolve_orig_name"):
record._openevolve_orig_name = record.name

orig_name = record._openevolve_orig_name
if self.prefix:
record.name = f"{self.prefix}.{orig_name}"
else:
record.name = orig_name
return True
Loading
Loading