Skip to content

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

tweak logging to use target id everywhere consistently instead of python id of page obj

Nick Sweeting720635f8f529
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 197e0477c..2507d062d 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -323,7 +323,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
logger.debug(
f'{" +vision" if self.settings.use_vision else ""}'
f' extraction_model={self.settings.page_extraction_llm.model if self.settings.page_extraction_llm else "Unknown"}'
- # Note: No longer logging planner_model (deprecated)
f'{" +file_system" if self.file_system else ""}'
)
@@ -466,13 +465,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):
def logger(self) -> logging.Logger:
"""Get instance-specific logger with task ID in the name"""
- _browser_session_id = self.browser_session.id if self.browser_session else self.id
+ _browser_session_id = self.browser_session.id if self.browser_session else '----'
_current_target_id = (
- self.browser_session.agent_focus.target_id[-4:]
+ self.browser_session.agent_focus.target_id[-2:]
if self.browser_session and self.browser_session.agent_focus and self.browser_session.agent_focus.target_id
else '--'
)
- return logging.getLogger(f'browser_use.Agent🅰 {self.task_id[-4:]} on 🆂 {_browser_session_id[-4:]} 🅟 {_current_target_id}')
+ return logging.getLogger(f'browser_use.Agent🅰 {self.task_id[-4:]} ⇢ 🅑 {_browser_session_id[-4:]} 🅣 {_current_target_id}')
@property
def browser_profile(self) -> BrowserProfile:
@@ -1274,7 +1273,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self._log_agent_run()
self.logger.debug(
- f'🔧 Agent setup: Task ID {self.task_id[-4:]}, Session ID {self.session_id[-4:]}, Browser Session ID {self.browser_session.id[-4:] if self.browser_session else "None"}'
+ f'🔧 Agent setup: Agent Session ID {self.session_id[-4:]}, Task ID {self.task_id[-4:]}, Browser Session ID {self.browser_session.id[-4:] if self.browser_session else "None"} {"(connecting via CDP)" if (self.browser_session and self.browser_session.cdp_url) else "(launching local browser)"}'
)
# Initialize timing for session and task
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index ae5a983d4..632b729b5 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -2,6 +2,7 @@
import asyncio
import logging
+from functools import cached_property
from typing import Any, Self, cast
import httpx
@@ -44,6 +45,10 @@ DEFAULT_BROWSER_PROFILE = BrowserProfile()
MAX_SCREENSHOT_HEIGHT = 2000
MAX_SCREENSHOT_WIDTH = 1920
+_LOGGED_UNIQUE_SESSION_IDS = set() # track unique session IDs that have been logged to make sure we always assign a unique enough id to new sessions and avoid ambiguity in logs
+red = '\033[91m'
+reset = '\033[0m'
+
class CDPSession(BaseModel):
"""Info about a single CDP session bound to a specific target.
@@ -88,7 +93,7 @@ class CDPSession(BaseModel):
import logging
logger = logging.getLogger(f'browser_use.CDPSession.{target_id[-4:]}')
- logger.debug(f'🔌 Creating dedicated WebSocket connection for target {target_id}')
+ logger.debug(f'🔌 Creating new dedicated WebSocket connection for target 🅣 {target_id}')
target_cdp_client = CDPClient(cdp_url)
await target_cdp_client.start()
@@ -148,7 +153,7 @@ class CDPSession(BaseModel):
# if 'Debugger' not in domains:
# await self.cdp_client.send.Debugger.disable()
# await cdp_session.cdp_client.send.EventBreakpoints.disable(session_id=cdp_session.session_id)
- except Exception as e:
+ except Exception:
# self.logger.warning(f'Failed to disable page JS breakpoints: {e}')
pass
@@ -240,14 +245,28 @@ class BrowserSession(BaseModel):
# self._logger = logging.getLogger(f'browser_use.{self}')
return logging.getLogger(f'browser_use.{self}')
+ @cached_property
+ def _id_for_logs(self) -> str:
+ """Get human-friendly semi-unique identifier for differentiating different BrowserSession instances in logs"""
+ str_id = self.id[-4:] # default to last 4 chars of truly random uuid, less helpful than cdp port but always unique enough
+ port_number = (self.cdp_url or 'no-cdp').rsplit(':', 1)[-1].split('/', 1)[0].strip()
+ port_is_random = not port_number.startswith('922')
+ port_is_unique_enough = port_number not in _LOGGED_UNIQUE_SESSION_IDS
+ if port_number and port_number.isdigit() and port_is_random and port_is_unique_enough:
+ # if cdp port is random/unique enough to identify this session, use it as our id in logs
+ _LOGGED_UNIQUE_SESSION_IDS.add(port_number)
+ str_id = port_number
+ return str_id
+
+ @property
+ def _tab_id_for_logs(self) -> str:
+ return self.agent_focus.target_id[-2:] if self.agent_focus and self.agent_focus.target_id else f'{red}--{reset}'
+
def __repr__(self) -> str:
- port_number = (self.cdp_url or 'no-cdp').rsplit(':', 1)[-1].split('/', 1)[0]
- return f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]} (cdp_url={self.cdp_url}, profile={self.browser_profile})'
+ return f'BrowserSession🅑 {self._id_for_logs} 🅣 {self._tab_id_for_logs} (cdp_url={self.cdp_url}, profile={self.browser_profile})'
def __str__(self) -> str:
- # Note: _original_browser_session tracking moved to Agent class
- port_number = (self.cdp_url or 'no-cdp').rsplit(':', 1)[-1].split('/', 1)[0]
- return f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.cdp_session.target_id))[-2:]}'
+ return f'BrowserSession🅑 {self._id_for_logs} 🅣 {self._tab_id_for_logs}'
async def reset(self) -> None:
"""Clear all cached CDP sessions with proper cleanup."""
diff --git a/browser_use/browser/watchdogs/local_browser_watchdog.py b/browser_use/browser/watchdogs/local_browser_watchdog.py
index c76a1b3dd..18cd3f5e5 100644
--- a/browser_use/browser/watchdogs/local_browser_watchdog.py
+++ b/browser_use/browser/watchdogs/local_browser_watchdog.py
@@ -47,16 +47,14 @@ class LocalBrowserWatchdog(BaseWatchdog):
try:
self.logger.debug(
- f'[LocalBrowserWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}, launching local browser'
+ '[LocalBrowserWatchdog] Received BrowserLaunchEvent, launching local browser...'
)
- self.logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')
+ # self.logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')
process, cdp_url = await self._launch_browser()
- self.logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')
-
self._subprocess = process
+ # self.logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')
- self.logger.debug(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')
return BrowserLaunchResult(cdp_url=cdp_url)
except Exception as e:
self.logger.error(f'[LocalBrowserWatchdog] Exception in on_BrowserLaunchEvent: {e}', exc_info=True)
@@ -145,7 +143,7 @@ class LocalBrowserWatchdog(BaseWatchdog):
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
- self.logger.debug(f'[LocalBrowserWatchdog] 🎭 Browser subprocess launched with browser_pid= {subprocess.pid}')
+ self.logger.debug(f'[LocalBrowserWatchdog] 🎭 Browser running with browser_pid= {subprocess.pid} 🔗 listening on CDP port :{debug_port}')
# Convert to psutil.Process
process = psutil.Process(subprocess.pid)
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 65662b691..73d8ac627 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -94,9 +94,9 @@ def setup_logging(stream=None, log_level=None, force_setup=False):
# Only clean up names in INFO mode, keep everything in DEBUG mode
if self.log_level > logging.DEBUG and isinstance(record.name, str) and record.name.startswith('browser_use.'):
# Extract clean component names from logger names
- if 'Agent🅰' in record.name:
+ if 'Agent' in record.name:
record.name = 'Agent'
- elif 'BrowserSession🆂' in record.name:
+ elif 'BrowserSession' in record.name:
record.name = 'BrowserSession'
elif 'controller' in record.name:
record.name = 'controller'