Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

simplify error logging and fix timeouts

Nick Sweeting9e9cce40f6b9
diff --git a/browser_use/__init__.py b/browser_use/__init__.py
index b9132d069..1635b1e79 100644
--- a/browser_use/__init__.py
+++ b/browser_use/__init__.py
@@ -1,6 +1,14 @@
+import os
+
from browser_use.logging_config import setup_logging
-logger = setup_logging()
+# Only set up logging if not in MCP mode or if explicitly requested
+if os.environ.get('BROWSER_USE_SETUP_LOGGING', 'true').lower() != 'false':
+ logger = setup_logging()
+else:
+ import logging
+
+ logger = logging.getLogger('browser_use')
# Monkeypatch BaseSubprocessTransport.__del__ to handle closed event loops gracefully
from asyncio import base_subprocess
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 8922ff545..b3d3b9637 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -852,12 +852,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
prefix = f'❌ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n '
self.state.consecutive_failures += 1
- from browser_use.agent.views import ActionNotFoundError
-
- if isinstance(error, ActionNotFoundError):
- # For ActionNotFoundError, the message is already clear and complete
- self.logger.error(f'{prefix}{error_msg}')
- elif isinstance(error, (ValidationError, ValueError)):
+ if isinstance(error, (ValidationError, ValueError)):
self.logger.error(f'{prefix}{error_msg}')
if 'Max token limit reached' in error_msg:
# cut tokens from history
@@ -956,29 +951,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self._log_next_action_summary(parsed)
return parsed
except ValidationError as e:
- # Extract available actions from the registry
- available_actions = list(self.controller.registry.registry.actions.keys())
-
- # Try to extract the action that was attempted from the error
- attempted_action = None
- error_str = str(e)
-
- # Look for patterns like {"action_name": {...}} in the error
- import re
-
- action_pattern = r'\{["\']?(\w+)["\']?\s*:'
- matches = re.findall(action_pattern, error_str)
- if matches:
- # Get the first non-standard field name that might be an action
- for match in matches:
- if match not in ['thinking', 'evaluation_previous_goal', 'memory', 'next_goal', 'action']:
- attempted_action = match
- break
-
- # Raise our custom error
- from browser_use.agent.views import ActionNotFoundError
-
- raise ActionNotFoundError(attempted_action, available_actions) from e
+ # Just re-raise - Pydantic's validation errors are already descriptive
+ raise
def _log_agent_run(self) -> None:
"""Log the agent run"""
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 9843f16d4..379dc7486 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -494,21 +494,6 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):
return None
-class ActionNotFoundError(ValueError):
- """Raised when an unknown action is attempted"""
-
- def __init__(self, attempted_action: str | None, available_actions: list[str]):
- self.attempted_action = attempted_action
- self.available_actions = sorted(available_actions)
-
- if attempted_action:
- message = f"Unknown action '{attempted_action}' in model response. Available actions are: {', '.join(self.available_actions)}"
- else:
- message = f'Failed to parse action from model response. Available actions are: {", ".join(self.available_actions)}'
-
- super().__init__(message)
-
-
class AgentError:
"""Container for agent error handling"""
@@ -520,9 +505,6 @@ class AgentError:
def format_error(error: Exception, include_trace: bool = False) -> str:
"""Format error message based on error type and optionally include trace"""
message = ''
- if isinstance(error, ActionNotFoundError):
- # For ActionNotFoundError, use the message as-is
- return str(error)
if isinstance(error, ValidationError):
return f'{AgentError.VALIDATION_ERROR}\nDetails: {str(error)}'
if isinstance(error, RateLimitError):
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 764480f8d..07c720304 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1750,7 +1750,7 @@ class BrowserSession(BaseModel):
if self.browser_profile.downloads_path:
try:
# Try short-timeout expect_download to detect a file download has been been triggered
- async with page.expect_download(timeout=5000) as download_info:
+ async with page.expect_download(timeout=5_000) as download_info:
await click_func()
download = await download_info.value
# Determine file path
@@ -1787,7 +1787,7 @@ class BrowserSession(BaseModel):
await self._check_and_handle_navigation(page)
try:
- return await perform_click(lambda: element_handle and element_handle.click(timeout=1500))
+ return await perform_click(lambda: element_handle and element_handle.click(timeout=1_500))
except URLNotAllowedError as e:
raise e
except Exception as e:
@@ -1800,7 +1800,7 @@ class BrowserSession(BaseModel):
raise Exception(f'Element no longer exists in DOM after context loss: {repr(element_node)}')
# Try click again with fresh element
try:
- return await perform_click(lambda: element_handle.click(timeout=1500))
+ return await perform_click(lambda: element_handle.click(timeout=1_500))
except Exception:
# Fall back to JavaScript click
return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
@@ -1903,7 +1903,7 @@ class BrowserSession(BaseModel):
except Exception as e:
if 'timeout' in str(e).lower():
self.logger.warning(
- f"⚠️ Loading {_log_pretty_url(normalized_url)} didn't finish after {(self.browser_profile.default_navigation_timeout or 30000) / 1000}s, continuing anyway..."
+ f"⚠️ Loading {_log_pretty_url(normalized_url)} didn't finish after {(self.browser_profile.default_navigation_timeout or 30_000) / 1000}s, continuing anyway..."
)
# Don't re-raise timeout errors - the page is likely still usable and will continue to load in the background
else:
@@ -2462,7 +2462,7 @@ class BrowserSession(BaseModel):
try:
# 10 ms timeout
page = await self.get_current_page()
- await page.go_back(timeout=10, wait_until='domcontentloaded')
+ await page.go_back(timeout=10_000, wait_until='domcontentloaded')
# await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
except Exception as e:
@@ -2473,7 +2473,7 @@ class BrowserSession(BaseModel):
"""Navigate the agent's tab forward in browser history"""
try:
page = await self.get_current_page()
- await page.go_forward(timeout=10, wait_until='domcontentloaded')
+ await page.go_forward(timeout=10_000, wait_until='domcontentloaded')
except Exception as e:
# Continue even if its not fully loaded, because we wait later for the page to load
self.logger.debug(f'⏭️ Error during go_forward: {type(e).__name__}: {e}')
@@ -2821,7 +2821,7 @@ class BrowserSession(BaseModel):
page = await self.get_current_page()
try:
- await page.wait_for_load_state(timeout=5000)
+ await page.wait_for_load_state(timeout=5_000)
except Exception:
pass
@@ -3269,10 +3269,10 @@ class BrowserSession(BaseModel):
# Ensure element is ready for input
try:
- await element_handle.wait_for_element_state('stable', timeout=1000)
+ await element_handle.wait_for_element_state('stable', timeout=1_000)
is_visible = await self._is_visible(element_handle)
if is_visible:
- await element_handle.scroll_into_view_if_needed(timeout=1000)
+ await element_handle.scroll_into_view_if_needed(timeout=1_000)
except Exception:
pass
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index ae1a90fe3..d0e8e73f6 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -59,18 +59,25 @@ def addLoggingLevel(levelName, levelNum, methodName=None):
setattr(logging, methodName, logToRoot)
-def setup_logging():
+def setup_logging(stream=None, log_level=None, force_setup=False):
+ """Setup logging configuration for browser-use.
+
+ Args:
+ stream: Output stream for logs (default: sys.stdout). Can be sys.stderr for MCP mode.
+ log_level: Override log level (default: uses CONFIG.BROWSER_USE_LOGGING_LEVEL)
+ force_setup: Force reconfiguration even if handlers already exist
+ """
# Try to add RESULT level, but ignore if it already exists
try:
addLoggingLevel('RESULT', 35) # This allows ERROR, FATAL and CRITICAL
except AttributeError:
pass # Level already exists, which is fine
- log_type = CONFIG.BROWSER_USE_LOGGING_LEVEL
+ log_type = log_level or CONFIG.BROWSER_USE_LOGGING_LEVEL
# Check if handlers are already set up
- if logging.getLogger().hasHandlers():
- return
+ if logging.getLogger().hasHandlers() and not force_setup:
+ return logging.getLogger('browser_use')
# Clear existing handlers
root = logging.getLogger()
@@ -83,7 +90,7 @@ def setup_logging():
return super().format(record)
# Setup single handler for all loggers
- console = logging.StreamHandler(sys.stdout)
+ console = logging.StreamHandler(stream or sys.stdout)
# adittional setLevel here to filter logs
if log_type == 'result':
diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.py
index 76fd97513..9ea17f99e 100644
--- a/browser_use/mcp/server.py
+++ b/browser_use/mcp/server.py
@@ -31,27 +31,36 @@ import sys
from pathlib import Path
from typing import Any, Literal
+# Set environment to suppress browser-use logging during import
+os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'error'
+os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false' # Prevent automatic logging setup
+
# Add browser-use to path if running from source
sys.path.insert(0, str(Path(__file__).parent.parent))
-# Override browser-use's logging BEFORE importing it
-# This prevents it from setting up stdout logging
-logging.basicConfig(
- level=logging.ERROR, # Only show errors to avoid interference
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- stream=sys.stderr,
- force=True, # Force reconfiguration
-)
+# Import and configure logging to use stderr before other imports
+from browser_use.logging_config import setup_logging
-# Clear any existing handlers on root logger
-root_logger = logging.getLogger()
-root_logger.handlers = []
+# Configure logging to stderr for MCP mode
+setup_logging(stream=sys.stderr, log_level='error', force_setup=True)
-# Add our stderr handler
+# Also configure the root logger and all existing loggers to use stderr
+logging.root.handlers = []
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
-root_logger.addHandler(stderr_handler)
+logging.root.addHandler(stderr_handler)
+logging.root.setLevel(logging.ERROR)
+
+# Configure all existing loggers to use stderr
+for name in list(logging.root.manager.loggerDict.keys()):
+ logger = logging.getLogger(name)
+ logger.handlers = []
+ logger.addHandler(stderr_handler)
+ logger.setLevel(logging.ERROR)
+ logger.propagate = False
+
+# Import browser_use modules
from browser_use import ActionModel, Agent
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.config import get_default_llm, get_default_profile, load_browser_use_config
@@ -59,14 +68,38 @@ from browser_use.controller.service import Controller
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.openai.chat import ChatOpenAI
-# After import, ensure browser_use logger doesn't output to stdout
-browser_use_logger = logging.getLogger('browser_use')
-browser_use_logger.handlers = []
-browser_use_logger.addHandler(stderr_handler)
-browser_use_logger.setLevel(logging.ERROR)
-
logger = logging.getLogger(__name__)
+
+def _ensure_all_loggers_use_stderr():
+ """Ensure ALL loggers only output to stderr, not stdout."""
+ # Get the stderr handler
+ stderr_handler = None
+ for handler in logging.root.handlers:
+ if hasattr(handler, 'stream') and handler.stream == sys.stderr: # type: ignore
+ stderr_handler = handler
+ break
+
+ if not stderr_handler:
+ stderr_handler = logging.StreamHandler(sys.stderr)
+ stderr_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
+
+ # Configure root logger
+ logging.root.handlers = [stderr_handler]
+ logging.root.setLevel(logging.ERROR)
+
+ # Configure all existing loggers
+ for name in list(logging.root.manager.loggerDict.keys()):
+ logger_obj = logging.getLogger(name)
+ logger_obj.handlers = [stderr_handler]
+ logger_obj.setLevel(logging.ERROR)
+ logger_obj.propagate = False
+
+
+# Ensure stderr logging after all imports
+_ensure_all_loggers_use_stderr()
+
+
# Try to import MCP SDK
try:
import mcp.server.stdio
@@ -75,6 +108,13 @@ try:
from mcp.server.models import InitializationOptions
MCP_AVAILABLE = True
+
+ # Configure MCP SDK logging to stderr as well
+ mcp_logger = logging.getLogger('mcp')
+ mcp_logger.handlers = []
+ mcp_logger.addHandler(logging.root.handlers[0] if logging.root.handlers else logging.StreamHandler(sys.stderr))
+ mcp_logger.setLevel(logging.ERROR)
+ mcp_logger.propagate = False
except ImportError:
MCP_AVAILABLE = False
logger.error('MCP SDK not installed. Install with: pip install mcp')
@@ -85,6 +125,9 @@ class BrowserUseServer:
"""MCP Server for browser-use capabilities."""
def __init__(self):
+ # Ensure all logging goes to stderr
+ _ensure_all_loggers_use_stderr()
+
self.server = Server('browser-use')
self.config = load_browser_use_config()
self.agent: Agent | None = None
@@ -337,7 +380,10 @@ class BrowserUseServer:
if self.browser_session:
return
- logger.info('Initializing browser session...')
+ # Ensure all logging goes to stderr before browser initialization
+ _ensure_all_loggers_use_stderr()
+
+ logger.debug('Initializing browser session...')
# Get profile config
profile_config = get_default_profile(self.config)
@@ -387,7 +433,7 @@ class BrowserUseServer:
file_system_path = profile_config.get('file_system_path', '~/.browser-use-mcp')
self.file_system = FileSystem(base_dir=Path(file_system_path).expanduser())
- logger.info('Browser session initialized')
+ logger.debug('Browser session initialized')
async def _retry_with_browser_use_agent(
self,
@@ -398,7 +444,7 @@ class BrowserUseServer:
use_vision: bool = True,
) -> str:
"""Run an autonomous agent task."""
- logger.info(f'Running agent task: {task}')
+ logger.debug(f'Running agent task: {task}')
# Get LLM config
llm_config = get_default_llm(self.config)
diff --git a/browser_use/observability.py b/browser_use/observability.py
index 2c3c9d358..20b6f5fe7 100644
--- a/browser_use/observability.py
+++ b/browser_use/observability.py
@@ -39,7 +39,9 @@ def _is_debug_mode() -> bool:
return False
-logger.info(f'Debug mode is {_is_debug_mode()}')
+# Only log debug mode status if explicitly requested
+if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true':
+ logger.info(f'Debug mode is {_is_debug_mode()}')
# Try to import lmnr observe
_LMNR_AVAILABLE = False
@@ -48,10 +50,12 @@ _lmnr_observe = None
try:
from lmnr import observe as _lmnr_observe # type: ignore
- logger.info('Lmnr is available for observability')
+ if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true':
+ logger.info('Lmnr is available for observability')
_LMNR_AVAILABLE = True
except ImportError:
- logger.info('Lmnr is not available for observability')
+ if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true':
+ logger.info('Lmnr is not available for observability')
_LMNR_AVAILABLE = False