Skip to content

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

add better logging with reference ids for each object

Nick Sweeting9a08e3b03146
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 032988824..42c58f2c4 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -99,6 +99,9 @@ AgentHookFunc = Callable[['Agent'], Awaitable[None]]
class Agent(Generic[Context]):
+ browser_session: BrowserSession | None = None
+ _logger: logging.Logger | None = None
+
@time_execution_sync('--init')
def __init__(
self,
@@ -167,16 +170,14 @@ class Agent(Generic[Context]):
enable_memory: bool = True,
memory_config: MemoryConfig | None = None,
source: str | None = None,
+ task_id: str | None = None,
):
if page_extraction_llm is None:
page_extraction_llm = llm
- # Generate unique IDs for this agent session and task early
+ self.id = task_id or uuid7str()
+ self.task_id: str = self.id
self.session_id: str = uuid7str()
- self.task_id: str = uuid7str()
-
- # Create instance-specific logger
- self._logger = logging.getLogger(f'browser_use.Agent[{self.task_id[-4:]}]')
# Core components
self.task = task
@@ -338,6 +339,7 @@ class Agent(Generic[Context]):
browser=browser,
browser_context=browser_context,
page=page,
+ id=uuid7str()[:-4] + self.id[-4:], # re-use the same 4-char suffix so they show up together in logs
)
if self.sensitive_data:
@@ -422,7 +424,10 @@ class Agent(Generic[Context]):
@property
def logger(self) -> logging.Logger:
"""Get instance-specific logger with task ID in the name"""
- return self._logger
+
+ _browser_session_id = self.browser_session.id if self.browser_session else self.id
+ _current_page_id = str(id(self.browser_session and self.browser_session.agent_current_page))[-2:]
+ return logging.getLogger(f'browser_use.Agent✻{self.task_id[-4:]} on ⛶{_browser_session_id[-4:]}.{_current_page_id}')
@property
def browser(self) -> Browser:
@@ -1147,7 +1152,7 @@ class Agent(Generic[Context]):
"""Log the agent run"""
self.logger.info(f'🚀 Starting task: {self.task}')
- self.logger.debug(f'🤖 Browser-Use Version: v{self.version} ({self.source})')
+ self.logger.debug(f'🤖 Browser-Use Library Version {self.version} ({self.source})')
def _log_step_context(self, current_page, browser_state_summary) -> None:
"""Log step context information"""
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index 6a90c7f1a..bd9e89cc6 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -617,10 +617,10 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
def __repr__(self) -> str:
short_dir = _log_pretty_path(self.user_data_dir) if self.user_data_dir else '<incognito>'
- return f'BrowserProfile[{self.id[-4:]}](user_data_dir= {short_dir}, headless={self.headless})'
+ return f'BrowserProfile#{self.id[-4:]}(user_data_dir= {short_dir}, headless={self.headless})'
def __str__(self) -> str:
- return f'BrowserProfile[{self.id[-4:]}]'
+ return f'BrowserProfile#{self.id[-4:]}'
@model_validator(mode='after')
def copy_old_config_names_to_new(self) -> Self:
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 4022f2534..03e08320c 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -249,14 +249,14 @@ class BrowserSession(BaseModel):
"""Get instance-specific logger with session ID in the name"""
if self._logger is None:
# Create a child logger with the session ID
- self._logger = logging.getLogger(f'browser_use.BrowserSession[{self.id[-4:]}]')
+ self._logger = logging.getLogger(f'browser_use.BrowserSession⛶{self.id[-4:]}.{str(id(self.agent_current_page))[-2:]}')
return self._logger
def __repr__(self) -> str:
- return f'BrowserSession[{self.id[-4:]}](profile={self.browser_profile}, {self._connection_str})'
+ return f'BrowserSession#{self.id[-4:]}(profile={self.browser_profile}, {self._connection_str})'
def __str__(self) -> str:
- return f'BrowserSession[{self.id[-4:]}]'
+ return f'BrowserSession#{self.id[-4:]}'
# def __getattr__(self, key: str) -> Any:
# """
@@ -466,12 +466,12 @@ class BrowserSession(BaseModel):
profile = getattr(self, 'browser_profile', None)
keep_alive = getattr(profile, 'keep_alive', None)
user_data_dir = getattr(profile, 'user_data_dir', None)
- self.logger.debug(
- f'🛑 Stopping (garbage collected) keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'
- )
+ if self.initialized:
+ self.logger.debug(
+ f'🛑 Stopping (garbage collected BrowserSession ⛶{self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} ref #{str(id(self))[-4:]}) keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'
+ )
self._kill_child_processes()
-
except BaseException:
# Never let __del__ raise exceptions
pass
@@ -870,7 +870,7 @@ class BrowserSession(BaseModel):
if pages:
foreground_page = pages[0]
self.logger.debug(
- f'👁️‍🗨️ Found {len(pages)} existing tabs in browser, agent will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
+ f'👁️‍🗨️ Found {len(pages)} existing tabs in browser, agent session {self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
)
else:
foreground_page = await self.browser_context.new_page()
@@ -1454,7 +1454,7 @@ class BrowserSession(BaseModel):
if not (path or self.browser_profile.storage_state or self.browser_profile.cookies_file):
return
-
+
storage_state = await self.browser_context.storage_state()
cookies = storage_state['cookies']
@@ -2612,14 +2612,17 @@ class BrowserSession(BaseModel):
self.agent_current_page = page
# in order for a human watching to be able to follow along with what the agent is doing
- # bring the agent's active tab to the foreground
+ # update the human's active tab to match the agent's
if self.human_current_page != page:
# TODO: figure out how to do this without bringing the entire window to the foreground and stealing foreground app focus
await page.bring_to_front()
self.human_current_page = page
- await page.wait_for_load_state()
+ try:
+ await page.wait_for_load_state()
+ except Exception as e:
+ self.logger.warning(f'⚠️ New page failed to fully load: {type(e).__name__}: {e}')
# Set the viewport size for the tab
if self.browser_profile.viewport: