Skip to content

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

use dedicated per-object logger for Agent and BrowserSession

Nick Sweeting8f057d9a127c
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 2656bb0de..573f842a5 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -16,6 +16,7 @@ from typing import Any, Generic, TypeVar
from dotenv import load_dotenv
from browser_use.browser.session import DEFAULT_BROWSER_PROFILE
+from browser_use.eventbus.models import UUIDStr
load_dotenv()
@@ -27,6 +28,7 @@ from langchain_core.messages import (
)
from playwright.async_api import Browser, BrowserContext, Page
from pydantic import BaseModel, ValidationError
+from uuid_extensions import uuid7str
from browser_use.agent.gif import create_history_gif
from browser_use.agent.memory import Memory, MemoryConfig
@@ -73,9 +75,13 @@ logger = logging.getLogger(__name__)
SKIP_LLM_API_KEY_VERIFICATION = os.environ.get('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[0] in 'ty1'
-def log_response(response: AgentOutput, registry=None) -> None:
+def log_response(response: AgentOutput, registry=None, logger=None) -> None:
"""Utility function to log the model's response."""
+ # Use module logger if no logger provided
+ if logger is None:
+ logger = logging.getLogger(__name__)
+
if 'Success' in response.current_state.evaluation_previous_goal:
emoji = '๐Ÿ‘'
elif 'Failed' in response.current_state.evaluation_previous_goal:
@@ -101,13 +107,13 @@ class Agent(Generic[Context]):
llm: BaseChatModel,
# Optional parameters
page: Page | None = None,
- browser: Browser | None = None,
+ browser: Browser | BrowserSession | None = None,
browser_context: BrowserContext | None = None,
browser_profile: BrowserProfile | None = None,
browser_session: BrowserSession | None = None,
controller: Controller[Context] = Controller(),
# Initial agent run parameters
- sensitive_data: dict[str, str | dict[str, str]] | None = None,
+ sensitive_data: dict[str, str] | dict[str, dict[str, str]] | None = None,
initial_actions: list[dict[str, dict[str, Any]]] | None = None,
# Cloud Callbacks
register_new_step_callback: (
@@ -166,6 +172,13 @@ class Agent(Generic[Context]):
if page_extraction_llm is None:
page_extraction_llm = llm
+ # Generate unique IDs for this agent session and task early
+ self.session_id: UUIDStr = uuid7str()
+ self.task_id: UUIDStr = uuid7str()
+
+ # Create instance-specific logger
+ self._logger = logging.getLogger(f'browser_use.Agent[{self.task_id[-3:]}]')
+
# Core components
self.task = task
self.llm = llm
@@ -216,22 +229,24 @@ class Agent(Generic[Context]):
# Handle users trying to use use_vision=True with DeepSeek models
if 'deepseek' in self.model_name.lower():
- logger.warning('โš ๏ธ DeepSeek models do not support use_vision=True yet. Setting use_vision=False for now...')
+ self.logger.warning('โš ๏ธ DeepSeek models do not support use_vision=True yet. Setting use_vision=False for now...')
self.settings.use_vision = False
if 'deepseek' in (self.planner_model_name or '').lower():
- logger.warning(
+ self.logger.warning(
'โš ๏ธ DeepSeek models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...'
)
self.settings.use_vision_for_planner = False
# Handle users trying to use use_vision=True with XAI models
if 'grok' in self.model_name.lower():
- logger.warning('โš ๏ธ XAI models do not support use_vision=True yet. Setting use_vision=False for now...')
+ self.logger.warning('โš ๏ธ XAI models do not support use_vision=True yet. Setting use_vision=False for now...')
self.settings.use_vision = False
if 'grok' in (self.planner_model_name or '').lower():
- logger.warning('โš ๏ธ XAI models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...')
+ self.logger.warning(
+ 'โš ๏ธ XAI models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...'
+ )
self.settings.use_vision_for_planner = False
- logger.info(
+ self.logger.info(
f'๐Ÿง  Starting a browser-use agent {self.version} with base_model={self.model_name}'
f'{" +tools" if self.tool_calling_method == "function_calling" else ""}'
f'{" +rawtools" if self.tool_calling_method == "raw" else ""}'
@@ -278,7 +293,7 @@ class Agent(Generic[Context]):
config=self.memory_config,
)
except ImportError:
- logger.warning(
+ self.logger.warning(
'โš ๏ธ Agent(enable_memory=True) is set but missing some required packages, install and re-run to use memory features: pip install browser-use[memory]'
)
self.memory = None
@@ -317,7 +332,7 @@ class Agent(Generic[Context]):
# If no allowed_domains are configured, show a security warning
if not self.browser_profile.allowed_domains:
- logger.error(
+ self.logger.error(
'โš ๏ธโš ๏ธโš ๏ธ Agent(sensitive_data=โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข) was provided but BrowserSession(allowed_domains=[...]) is not locked down! โš ๏ธโš ๏ธโš ๏ธ\n'
' โ˜ ๏ธ If the agent visits a malicious website and encounters a prompt-injection attack, your sensitive_data may be exposed!\n\n'
' https://docs.browser-use.com/customize/browser-settings#restrict-urls\n'
@@ -333,7 +348,9 @@ class Agent(Generic[Context]):
sys.exit(0)
else:
pass # no point waiting if we're not in an interactive shell
- logger.warning('โ€ผ๏ธ Continuing with insecure settings for now... but this will become a hard error in the future!')
+ self.logger.warning(
+ 'โ€ผ๏ธ Continuing with insecure settings for now... but this will become a hard error in the future!'
+ )
# If we're using domain-specific credentials, validate domain patterns
elif has_domain_specific_credentials:
@@ -367,7 +384,7 @@ class Agent(Generic[Context]):
break
if not is_allowed:
- logger.warning(
+ self.logger.warning(
f'โš ๏ธ Domain pattern "{domain_pattern}" in sensitive_data is not covered by any pattern in allowed_domains={self.browser_profile.allowed_domains}\n'
f' This may be a security risk as credentials could be used on unintended domains.'
)
@@ -384,10 +401,15 @@ class Agent(Generic[Context]):
self.telemetry = ProductTelemetry()
if self.settings.save_conversation_path:
- logger.info(f'Saving conversation to {self.settings.save_conversation_path}')
+ self.logger.info(f'Saving conversation to {self.settings.save_conversation_path}')
self._external_pause_event = asyncio.Event()
self._external_pause_event.set()
+ @property
+ def logger(self) -> logging.Logger:
+ """Get instance-specific logger with task ID in the name"""
+ return self._logger
+
@property
def browser(self) -> Browser:
return self.browser_session.browser
@@ -423,12 +445,12 @@ class Agent(Generic[Context]):
else:
source = 'pip'
except Exception as e:
- logger.debug(f'Error determining source: {e}')
+ self.logger.debug(f'Error determining source: {e}')
source = 'unknown'
if source_override is not None:
source = source_override
- logger.debug(f'Version: {version}, Source: {source}')
+ self.logger.debug(f'Version: {version}, Source: {source}')
self.version = version
self.source = source
@@ -480,7 +502,7 @@ class Agent(Generic[Context]):
Cleans and validates a raw JSON response string against an expected answer.
"""
content = getattr(response, 'content', '').strip()
- # logger.debug(f'Raw response content: {content}')
+ # self.logger.debug(f'Raw response content: {content}')
# Remove surrounding markdown code blocks if present
if content.startswith('```json') and content.endswith('```'):
@@ -494,13 +516,13 @@ class Agent(Generic[Context]):
answer = str(result.get('answer', '')).strip().lower().strip(' .')
if expected_answer.lower() not in answer:
- logger.debug(f"๐Ÿ› ๏ธ Tool calling method {method} failed: expected '{expected_answer}', got '{answer}'")
+ self.logger.debug(f"๐Ÿ› ๏ธ Tool calling method {method} failed: expected '{expected_answer}', got '{answer}'")
return False
return True
except (json.JSONDecodeError, AttributeError, TypeError) as e:
- logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: Failed to parse JSON content: {e}')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: Failed to parse JSON content: {e}')
return False
if method == 'raw' or method == 'json_mode':
@@ -522,7 +544,7 @@ class Agent(Generic[Context]):
response = structured_llm.invoke([HumanMessage(content=CAPITAL_QUESTION)])
if not response:
- logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: empty response')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: empty response')
return False
def extract_parsed(response: Any) -> CapitalResponse | None:
@@ -533,16 +555,16 @@ class Agent(Generic[Context]):
parsed = extract_parsed(response)
if not isinstance(parsed, CapitalResponse):
- logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: LLM responded with invalid JSON')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: LLM responded with invalid JSON')
return False
if EXPECTED_ANSWER not in parsed.answer.lower():
- logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: LLM failed to answer test question correctly')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tool calling method {method} failed: LLM failed to answer test question correctly')
return False
return True
except Exception as e:
- logger.debug(f"๐Ÿ› ๏ธ Tool calling method '{method}' test failed: {type(e).__name__}: {str(e)}")
+ self.logger.debug(f"๐Ÿ› ๏ธ Tool calling method '{method}' test failed: {type(e).__name__}: {str(e)}")
return False
async def _test_tool_calling_method_async(self, method: str) -> tuple[str, bool]:
@@ -607,11 +629,11 @@ class Agent(Generic[Context]):
self.llm._verified_api_keys = True
self.llm._verified_tool_calling_method = method # Cache on LLM instance
elapsed = time.time() - start_time
- logger.debug(f'๐Ÿ› ๏ธ Tested LLM in parallel and chose tool calling method: [{method}] in {elapsed:.2f}s')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tested LLM in parallel and chose tool calling method: [{method}] in {elapsed:.2f}s')
return method
except Exception as e:
- logger.debug(f'Parallel testing failed: {e}, falling back to sequential')
+ self.logger.debug(f'Parallel testing failed: {e}, falling back to sequential')
# Fall back to sequential testing
for method in methods_to_try:
if self._test_tool_calling_method(method):
@@ -619,7 +641,7 @@ class Agent(Generic[Context]):
self.llm._verified_api_keys = True
self.llm._verified_tool_calling_method = method # Cache on LLM instance
elapsed = time.time() - start_time
- logger.debug(f'๐Ÿ› ๏ธ Tested LLM and chose tool calling method: [{method}] in {elapsed:.2f}s')
+ self.logger.debug(f'๐Ÿ› ๏ธ Tested LLM and chose tool calling method: [{method}] in {elapsed:.2f}s')
return method
# If we get here, no methods worked
@@ -700,7 +722,7 @@ class Agent(Generic[Context]):
# Check if we already have a cached method on this LLM instance
if hasattr(self.llm, '_verified_tool_calling_method'):
- logger.debug(
+ self.logger.debug(
f'๐Ÿ› ๏ธ Using cached tool calling method for {self.chat_model_library}/{self.model_name}: [{self.llm._verified_tool_calling_method}]'
)
return self.llm._verified_tool_calling_method
@@ -712,7 +734,7 @@ class Agent(Generic[Context]):
if getattr(self.llm, '_verified_api_keys', None) is True or SKIP_LLM_API_KEY_VERIFICATION:
self.llm._verified_api_keys = True
self.llm._verified_tool_calling_method = known_method # Cache on LLM instance
- logger.debug(
+ self.logger.debug(
f'๐Ÿ› ๏ธ Using known tool calling method for {self.chat_model_library}/{self.model_name}: [{known_method}] (skipped test)'
)
return known_method
@@ -723,12 +745,12 @@ class Agent(Generic[Context]):
self.llm._verified_api_keys = True
self.llm._verified_tool_calling_method = known_method # Cache on LLM instance
elapsed = time.time() - start_time
- logger.debug(
+ self.logger.debug(
f'๐Ÿ› ๏ธ Using known tool calling method for {self.chat_model_library}/{self.model_name}: [{known_method}] in {elapsed:.2f}s'
)
return known_method
# If known method fails, fall back to detection
- logger.debug(
+ self.logger.debug(
f'Known method {known_method} failed for {self.chat_model_library}/{self.model_name}, falling back to detection'
)
@@ -736,6 +758,10 @@ class Agent(Generic[Context]):
return self._detect_best_tool_calling_method()
def add_new_task(self, new_task: str) -> None:
+ """Add a new task to the agent, keeping the same task_id as tasks are continuous"""
+ # Simply delegate to message manager - no need for new task_id or events
+ # The task continues with new instructions, it doesn't end and start a new one
+ self.task = new_task
self._message_manager.add_new_task(new_task)
async def _raise_if_stopped_or_paused(self) -> None:
@@ -746,7 +772,7 @@ class Agent(Generic[Context]):
raise InterruptedError
if self.state.stopped or self.state.paused:
- # logger.debug('Agent paused after getting state')
+ # self.logger.debug('Agent paused after getting state')
raise InterruptedError
# @observe(name='agent.step', ignore_output=True, ignore_input=True)
@@ -821,7 +847,7 @@ class Agent(Generic[Context]):
msg += '\nIf the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed.'
msg += '\nIf the task is fully finished, set success in "done" to true.'
msg += '\nInclude everything you found out for the ultimate task in the done text.'
- logger.info('Last step finishing up')
+ self.logger.info('Last step finishing up')
self._message_manager._add_message_with_tokens(HumanMessage(content=msg))
self.AgentOutput = self.DoneAgentOutput
@@ -835,7 +861,7 @@ class Agent(Generic[Context]):
or not isinstance(model_output.action, list)
or all(action.model_dump() == {} for action in model_output.action)
):
- logger.warning('Model returned empty action. Retrying...')
+ self.logger.warning('Model returned empty action. Retrying...')
clarification_message = HumanMessage(
content='You forgot to return an action. Please respond only with a valid JSON action according to the expected format.'
@@ -845,7 +871,7 @@ class Agent(Generic[Context]):
model_output = await self.get_next_action(retry_messages)
if not model_output.action or all(action.model_dump() == {} for action in model_output.action):
- logger.warning('Model still returned empty after retry. Inserting safe noop action.')
+ self.logger.warning('Model still returned empty after retry. Inserting safe noop action.')
action_instance = self.ActionModel(
done={
'success': False,
@@ -892,12 +918,12 @@ class Agent(Generic[Context]):
self.state.last_result = result
if len(result) > 0 and result[-1].is_done:
- logger.info(f'๐Ÿ“„ Result: {result[-1].extracted_content}')
+ self.logger.info(f'๐Ÿ“„ Result: {result[-1].extracted_content}')
self.state.consecutive_failures = 0
except InterruptedError:
- # logger.debug('Agent paused')
+ # self.logger.debug('Agent paused')
self.state.last_result = [
ActionResult(
error='The agent was paused mid-step - the last action might need to be repeated', include_in_memory=False
@@ -906,7 +932,7 @@ class Agent(Generic[Context]):
return
except asyncio.CancelledError:
# Directly handle the case where the step is cancelled at a higher level
- # logger.debug('Task cancelled - agent was paused with Ctrl+C')
+ # self.logger.debug('Task cancelled - agent was paused with Ctrl+C')
self.state.last_result = [ActionResult(error='The agent was paused with Ctrl+C', include_in_memory=False)]
raise InterruptedError('Step cancelled by user')
except Exception as e:
@@ -933,21 +959,21 @@ class Agent(Generic[Context]):
@time_execution_async('--handle_step_error (agent)')
async def _handle_step_error(self, error: Exception) -> list[ActionResult]:
"""Handle all types of errors that can occur during a step"""
- include_trace = logger.isEnabledFor(logging.DEBUG)
+ include_trace = self.logger.isEnabledFor(logging.DEBUG)
error_msg = AgentError.format_error(error, include_trace=include_trace)
prefix = f'โŒ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n '
self.state.consecutive_failures += 1
if 'Browser closed' in error_msg:
- logger.error('โŒ Browser is closed or disconnected, unable to proceed')
+ self.logger.error('โŒ Browser is closed or disconnected, unable to proceed')
return [ActionResult(error='Browser closed or disconnected, unable to proceed', include_in_memory=False)]
if isinstance(error, (ValidationError, ValueError)):
- logger.error(f'{prefix}{error_msg}')
+ self.logger.error(f'{prefix}{error_msg}')
if 'Max token limit reached' in error_msg:
# cut tokens from history
self._message_manager.settings.max_input_tokens = self.settings.max_input_tokens - 500
- logger.info(
+ self.logger.info(
f'Cutting tokens from history - new max input tokens: {self._message_manager.settings.max_input_tokens}'
)
self._message_manager.cut_messages()
@@ -968,10 +994,10 @@ class Agent(Generic[Context]):
)
if isinstance(error, RATE_LIMIT_ERRORS):
- logger.warning(f'{prefix}{error_msg}')
+ self.logger.warning(f'{prefix}{error_msg}')
await asyncio.sleep(self.settings.retry_delay)
else:
- logger.error(f'{prefix}{error_msg}')
+ self.logger.error(f'{prefix}{error_msg}')
return [ActionResult(error=error_msg, include_in_memory=True)]
@@ -1030,7 +1056,7 @@ class Agent(Generic[Context]):
output = self.llm.invoke(input_messages)
response = {'raw': output, 'parsed': None}
except Exception as e:
- logger.error(f'Failed to invoke model: {str(e)}')
+ self.logger.error(f'Failed to invoke model: {str(e)}')
raise LLMException(401, 'LLM API call failed') from e
# TODO: currently invoke does not return reasoning_content, we should override invoke
output.content = self._remove_think_tags(str(output.content))
@@ -1039,7 +1065,7 @@ class Agent(Generic[Context]):
parsed = self.AgentOutput(**parsed_json)
response['parsed'] = parsed
except (ValueError, ValidationError) as e:
- logger.warning(f'Failed to parse model output: {output} {str(e)}')
+ self.logger.warning(f'Failed to parse model output: {output} {str(e)}')
raise ValueError('Could not parse response.')
elif self.tool_calling_method is None:
@@ -1049,7 +1075,7 @@ class Agent(Generic[Context]):
parsed: AgentOutput | None = response['parsed']
except Exception as e:
- logger.error(f'Failed to invoke model: {str(e)}')
+ self.logger.error(f'Failed to invoke model: {str(e)}')
raise LLMException(401, 'LLM API call failed') from e
else:
@@ -1090,7 +1116,7 @@ class Agent(Generic[Context]):
parsed_json = extract_json_from_model_output(response['raw'].content)
parsed = self.AgentOutput(**parsed_json)
except Exception as e:
- logger.warning(f'Failed to parse model output: {response["raw"].content} {str(e)}')
+ self.logger.warning(f'Failed to parse model output: {response["raw"].content} {str(e)}')
raise ValueError('Could not parse response.')
# cut the number of actions to max_actions_per_step if needed
@@ -1098,28 +1124,28 @@ class Agent(Generic[Context]):
parsed.action = parsed.action[: self.settings.max_actions_per_step]
if not (hasattr(self.state, 'paused') and (self.state.paused or self.state.stopped)):
- log_response(parsed, self.controller.registry.registry)
+ log_response(parsed, self.controller.registry.registry, self.logger)
self._log_next_action_summary(parsed)
return parsed
def _log_agent_run(self) -> None:
"""Log the agent run"""
- logger.info(f'๐Ÿš€ Starting task: {self.task}')
+ self.logger.info(f'๐Ÿš€ Starting task: {self.task}')
- logger.debug(f'Version: {self.version}, Source: {self.source}')
+ self.logger.debug(f'Version: {self.version}, Source: {self.source}')
def _log_step_context(self, current_page, browser_state_summary) -> None:
"""Log step context information"""
url_short = current_page.url[:50] + '...' if len(current_page.url) > 50 else current_page.url
interactive_count = len(browser_state_summary.selector_map) if browser_state_summary else 0
- logger.info(
+ self.logger.info(
f'๐Ÿ“ Step {self.state.n_steps}: Evaluating page with {interactive_count} interactive elements on: {url_short}'
)
def _log_next_action_summary(self, parsed: 'AgentOutput') -> None:
"""Log a comprehensive summary of the next action(s)"""
- if not (logger.isEnabledFor(logging.DEBUG) and parsed.action):
+ if not (self.logger.isEnabledFor(logging.DEBUG) and parsed.action):
return
action_count = len(parsed.action)
@@ -1152,12 +1178,12 @@ class Agent(Generic[Context]):
# Create summary based on single vs multi-action
if action_count == 1:
- logger.info(f'โšก๏ธ Decided next action: {action_name}{param_str}')
+ self.logger.info(f'โšก๏ธ Decided next action: {action_name}{param_str}')
else:
summary_lines = [f'โšก๏ธ Decided next {action_count} multi-actions:']
for i, detail in enumerate(action_details):
summary_lines.append(f' {i + 1}. {detail}')
- logger.info('\n'.join(summary_lines))
+ self.logger.info('\n'.join(summary_lines))
def _log_step_completion_summary(self, step_start_time: float, result: list[ActionResult]) -> None:
"""Log step completion summary with action count, timing, and success/failure stats"""
@@ -1177,7 +1203,7 @@ class Agent(Generic[Context]):
status_parts = [part for part in [success_indicator, failure_indicator] if part]
status_str = ' | '.join(status_parts) if status_parts else 'โœ… 0'
- logger.info(f'๐Ÿ“ Step {self.state.n_steps}: Ran {action_count} actions in {step_duration:.2f}s: {status_str}')
+ self.logger.info(f'๐Ÿ“ Step {self.state.n_steps}: Ran {action_count} actions in {step_duration:.2f}s: {status_str}')
def _log_llm_call_info(self, input_messages: list[BaseMessage], method: str) -> None:
"""Log comprehensive information about the LLM call being made"""
@@ -1207,7 +1233,7 @@ class Agent(Generic[Context]):
term_width = shutil.get_terminal_size((80, 20)).columns
print('=' * term_width)
- logger.info(
+ self.logger.info(
f'๐Ÿง  LLM call => {self.chat_model_library} [โœ‰๏ธ {message_count} msg, ~{current_tokens} tk, {total_chars} char{image_status}] {output_format}{tool_info}'
)
@@ -1326,13 +1352,13 @@ class Agent(Generic[Context]):
# Check if we should stop due to too many failures
if self.state.consecutive_failures >= self.settings.max_failures:
- logger.error(f'โŒ Stopping due to {self.settings.max_failures} consecutive failures')
+ self.logger.error(f'โŒ Stopping due to {self.settings.max_failures} consecutive failures')
agent_run_error = f'Stopped due to {self.settings.max_failures} consecutive failures'
break
# Check control flags before each step
if self.state.stopped:
- logger.info('๐Ÿ›‘ Agent stopped')
+ self.logger.info('๐Ÿ›‘ Agent stopped')
agent_run_error = 'Agent stopped programmatically'
break
@@ -1357,6 +1383,8 @@ class Agent(Generic[Context]):
continue
await self.log_completion()
+
+ # Task completed
break
else:
agent_run_error = 'Failed to complete task in maximum steps'
@@ -1376,18 +1404,18 @@ class Agent(Generic[Context]):
)
)
- logger.info(f'โŒ {agent_run_error}')
+ self.logger.info(f'โŒ {agent_run_error}')
return self.state.history
except KeyboardInterrupt:
# Already handled by our signal handler, but catch any direct KeyboardInterrupt as well
- logger.info('Got KeyboardInterrupt during execution, returning current history')
+ self.logger.info('Got KeyboardInterrupt during execution, returning current history')
agent_run_error = 'KeyboardInterrupt'
return self.state.history
except Exception as e:
- logger.error(f'Agent run failed with exception: {e}', exc_info=True)
+ self.logger.error(f'Agent run failed with exception: {e}', exc_info=True)
agent_run_error = str(e)
raise e
@@ -1440,7 +1468,7 @@ class Agent(Generic[Context]):
new_target_hash = new_target.hash.branch_path_hash if new_target else None
if orig_target_hash != new_target_hash:
msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'
- logger.info(msg)
+ self.logger.info(msg)
results.append(ActionResult(extracted_content=msg, include_in_memory=True))
break
@@ -1448,7 +1476,7 @@ class Agent(Generic[Context]):
if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):
# next action requires index but there are new elements on the page
msg = f'Something new appeared after action {i} / {len(actions)}'
- logger.info(msg)
+ self.logger.info(msg)
results.append(ActionResult(extracted_content=msg, include_in_memory=True))
break
@@ -1469,7 +1497,7 @@ class Agent(Generic[Context]):
# Get action name from the action model
action_data = action.model_dump(exclude_unset=True)
action_name = next(iter(action_data.keys())) if action_data else 'unknown'
- logger.info(f'โ˜‘๏ธ Executed action {i + 1}/{len(actions)}: {action_name}')
+ self.logger.info(f'โ˜‘๏ธ Executed action {i + 1}/{len(actions)}: {action_name}')
if results[-1].is_done or results[-1].error or i == len(actions) - 1:
break
@@ -1478,7 +1506,7 @@ class Agent(Generic[Context]):
except asyncio.CancelledError:
# Gracefully handle task cancellation
- logger.info(f'Action {i + 1} was cancelled due to Ctrl+C')
+ self.logger.info(f'Action {i + 1} was cancelled due to Ctrl+C')
if not results:
# Add a result for the cancelled action
results.append(ActionResult(error='The action was cancelled due to Ctrl+C', include_in_memory=True))
@@ -1525,22 +1553,22 @@ class Agent(Generic[Context]):
parsed: ValidationResult = response['parsed']
is_valid = parsed.is_valid
if not is_valid:
- logger.info(f'โŒ Validator decision: {parsed.reason}')
+ self.logger.info(f'โŒ Validator decision: {parsed.reason}')
msg = f'The output is not yet correct. {parsed.reason}.'
self.state.last_result = [ActionResult(extracted_content=msg, include_in_memory=True)]
else:
- logger.info(f'โœ… Validator decision: {parsed.reason}')
+ self.logger.info(f'โœ… Validator decision: {parsed.reason}')
return is_valid
async def log_completion(self) -> None:
"""Log the completion of the task"""
if self.state.history.is_successful():
- logger.info('โœ… Task completed successfully')
+ self.logger.info('โœ… Task completed successfully')
else:
- logger.info('โŒ Task completed without success')
+ self.logger.info('โŒ Task completed without success')
total_tokens = self.state.history.total_input_tokens()
- logger.debug(f'๐Ÿ“ Total input tokens used (approximate): {total_tokens}')
+ self.logger.debug(f'๐Ÿ“ Total input tokens used (approximate): {total_tokens}')
if self.register_done_callback:
if inspect.iscoroutinefunction(self.register_done_callback):
@@ -1576,14 +1604,14 @@ class Agent(Generic[Context]):
for i, history_item in enumerate(history.history):
goal = history_item.model_output.current_state.next_goal if history_item.model_output else ''
- logger.info(f'Replaying step {i + 1}/{len(history.history)}: goal: {goal}')
+ self.logger.info(f'Replaying step {i + 1}/{len(history.history)}: goal: {goal}')
if (
not history_item.model_output
or not history_item.model_output.action
or history_item.model_output.action == [None]
):
- logger.warning(f'Step {i + 1}: No action to replay, skipping')
+ self.logger.warning(f'Step {i + 1}: No action to replay, skipping')
results.append(ActionResult(error='No action to replay'))
continue
@@ -1598,12 +1626,12 @@ class Agent(Generic[Context]):
retry_count += 1
if retry_count == max_retries:
error_msg = f'Step {i + 1} failed after {max_retries} attempts: {str(e)}'
- logger.error(error_msg)
+ self.logger.error(error_msg)
if not skip_failures:
results.append(ActionResult(error=error_msg))
raise RuntimeError(error_msg)
else:
- logger.warning(f'Step {i + 1} failed (attempt {retry_count}/{max_retries}), retrying...')
+ self.logger.warning(f'Step {i + 1} failed (attempt {retry_count}/{max_retries}), retrying...')
await asyncio.sleep(delay_between_actions)
return results
@@ -1653,7 +1681,7 @@ class Agent(Generic[Context]):
old_index = action.get_index()
if old_index != current_element.highlight_index:
action.set_index(current_element.highlight_index)
- logger.info(f'Element moved in DOM, updated index from {old_index} to {current_element.highlight_index}')
+ self.logger.info(f'Element moved in DOM, updated index from {old_index} to {current_element.highlight_index}')
return action
@@ -1687,6 +1715,8 @@ class Agent(Generic[Context]):
self.state.paused = True
self._external_pause_event.clear()
+ # Task paused
+
# The signal handler will handle the asyncio pause logic for us
# No need to duplicate the code here
@@ -1697,22 +1727,26 @@ class Agent(Generic[Context]):
self.state.paused = False
self._external_pause_event.set()
+ # Task resumed
+
# The signal handler should have already reset the flags
# through its reset() method when called from run()
# playwright browser is always immediately killed by the first Ctrl+C (no way to stop that)
# so we need to restart the browser if user wants to continue
if self.browser:
- logger.info('๐ŸŒŽ Restarting/reconnecting to browser...')
+ self.logger.info('๐ŸŒŽ Restarting/reconnecting to browser...')
loop = asyncio.get_event_loop()
loop.create_task(self.browser._init())
loop.create_task(asyncio.sleep(5))
def stop(self) -> None:
"""Stop the agent"""
- logger.info('โน๏ธ Agent stopping')
+ self.logger.info('โน๏ธ Agent stopping')
self.state.stopped = True
+ # Task stopped
+
def _convert_initial_actions(self, actions: list[dict[str, dict[str, Any]]]) -> list[ActionModel]:
"""Convert dictionary-based actions to ActionModel instances"""
converted_actions = []
@@ -1795,7 +1829,7 @@ class Agent(Generic[Context]):
try:
response = await self.settings.planner_llm.ainvoke(planner_messages)
except Exception as e:
- logger.error(f'Failed to invoke planner: {str(e)}')
+ self.logger.error(f'Failed to invoke planner: {str(e)}')
raise LLMException(401, 'LLM API call failed') from e
plan = str(response.content)
@@ -1806,12 +1840,12 @@ class Agent(Generic[Context]):
plan = self._remove_think_tags(plan)
try:
plan_json = json.loads(plan)
- logger.info(f'Planning Analysis:\n{json.dumps(plan_json, indent=4)}')
+ self.logger.info(f'Planning Analysis:\n{json.dumps(plan_json, indent=4)}')
except json.JSONDecodeError:
- logger.info(f'Planning Analysis:\n{plan}')
+ self.logger.info(f'Planning Analysis:\n{plan}')
except Exception as e:
- logger.debug(f'Error parsing planning analysis: {e}')
- logger.info(f'Plan: {plan}')
+ self.logger.debug(f'Error parsing planning analysis: {e}')
+ self.logger.info(f'Plan: {plan}')
return plan
@@ -1829,7 +1863,7 @@ class Agent(Generic[Context]):
gc.collect()
except Exception as e:
- logger.error(f'Error during cleanup: {e}')
+ self.logger.error(f'Error during cleanup: {e}')
async def _update_action_models_for_page(self, page) -> None:
"""Update action models with page-specific actions"""
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 2cccc810b..5721eb860 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -106,7 +106,7 @@ def require_initialization(func):
except Exception as e:
# Check if this is a TargetClosedError or similar connection error
if 'TargetClosedError' in str(type(e)) or 'context or browser has been closed' in str(e):
- logger.debug(f'Detected closed browser connection in {func.__name__}, resetting connection state')
+ self.logger.debug(f'Detected closed browser connection in {func.__name__}, resetting connection state')
self._reset_connection_state()
# Re-raise the error so the caller can handle it appropriately
raise
@@ -215,6 +215,7 @@ class BrowserSession(BaseModel):
_cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)
_start_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
_tab_visibility_callback: Any = PrivateAttr(default=None)
+ _logger: logging.Logger | None = PrivateAttr(default=None)
@model_validator(mode='after')
def apply_session_overrides_to_profile(self) -> Self:
@@ -238,6 +239,14 @@ class BrowserSession(BaseModel):
return self
+ @property
+ def logger(self) -> logging.Logger:
+ """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[-3:]}]')
+ return self._logger
+
def __repr__(self) -> str:
return f'BrowserSession[{self.id[-3:]}](profile={self.browser_profile}, {self._connection_str})'
@@ -272,12 +281,12 @@ class BrowserSession(BaseModel):
if self.is_connected():
return self
else:
- connection_str = (
- f'by re-connecting to {self._connection_str}'
+ next_step = (
+ 'attempting to re-connect'
if self.cdp_url or self.wss_url or self.browser_pid
- else 'by launching a new browser (previous one was closed)'
+ else 'launching a new browser'
)
- logger.info(f'โ™ป๏ธ {self} Re-starting stale session {connection_str}')
+ self.logger.warning(f'โ™ป๏ธ Browser {self._connection_str} has gone away, {next_step}...')
# only reset connection state if we expected to be already connected but we're not
# avoid calling this on *first* start() as it just immediately clears many
# of the params passed in to BrowserSession(...) init, which the .setup_...() methods below expect
@@ -310,7 +319,7 @@ class BrowserSession(BaseModel):
self.initialized = False
raise
- # logger.debug(f'๐ŸŽญ {self} started successfully')
+ # self.logger.debug(f'๐ŸŽญ started successfully')
return self
@@ -351,24 +360,25 @@ class BrowserSession(BaseModel):
try:
await self.save_storage_state()
except Exception as e:
- logger.debug(f'{self} Failed to save storage state before stopping: {type(e).__name__}: {e}')
+ self.logger.debug(f'Failed to save storage state before stopping: {type(e).__name__}: {e}')
if self.browser_profile.keep_alive:
- logger.info(
+ self.logger.info(
f'๐Ÿ•Š๏ธ {self}.stop() called but keep_alive=True, leaving the browser running. Use .kill() to force close.'
)
return # nothing to do if keep_alive=True, leave the browser running
if self.browser_context or self.browser:
try:
- logger.info(
- f'๐Ÿ›‘ {self} Stopping {self._connection_str} channel={self.browser_profile.channel.name.lower()} '
+ self.logger.info(
+ f'๐Ÿ›‘ Closing {self._connection_str} {self.browser_profile.channel.name.lower()} context with '
f'user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"}'
+ f'storage_state= {_log_pretty_path(self.browser_profile.storage_state_path or self.browser_profile.cookies_file) or "<none>"}'
)
- await (self.browser_context or self.browser).close()
+ await (self.browser or self.browser_context.browser).close()
except Exception as e:
- logger.debug(
- f'โŒ {self} Error closing playwright browser_context={self.browser_context}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โŒ Error closing playwright browser_context={self.browser_context}: {type(e).__name__}: {e}'
)
finally:
# Always clear references to ensure a fresh start next time
@@ -379,14 +389,14 @@ class BrowserSession(BaseModel):
if self.browser_pid:
try:
proc = psutil.Process(pid=self.browser_pid)
- cmd = proc.cmdline()[0]
+ executable_path = proc.cmdline()[0]
proc.terminate()
- logger.info(f' โ†ณ {self} Killed browser subprocess with browser_pid={self.browser_pid} {cmd}')
+ self.logger.info(f' โ†ณ Killed browser_pid={self.browser_pid} {_log_pretty_path(executable_path)}')
self.browser_pid = None
except Exception as e:
if 'NoSuchProcess' not in type(e).__name__:
- logger.debug(
- f'โŒ {self} Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โŒ Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}'
)
# Close playwright if we own it
@@ -395,15 +405,15 @@ class BrowserSession(BaseModel):
# await self.playwright.stop()
# self.playwright = None
# except Exception as e:
- # logger.debug(f'{self} Error stopping playwright: {type(e).__name__}: {e}')
+ # self.logger.debug(f'Error stopping playwright: {type(e).__name__}: {e}')
self._reset_connection_state()
async def close(self) -> None:
"""Deprecated: Provides backwards-compatibility with old class method Browser().close()"""
- # logger.debug(
- # f'โน๏ธ Stopping {self} gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (close() called)'
- # )
+ self.logger.debug(
+ f'โน๏ธ Stopping gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (close() called)'
+ )
await self.stop()
async def new_context(self, **kwargs):
@@ -415,25 +425,23 @@ class BrowserSession(BaseModel):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
- # logger.debug(
- # f'โน๏ธ Stopping {self} gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (context manager exit)'
+ # self.logger.debug(
+ # f'โน๏ธ Stopping gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (context manager exit)'
# )
await self.stop()
def __del__(self):
# Avoid keeping references in __del__ that might prevent garbage collection
try:
- browser_pid = getattr(self, 'browser_pid', None)
profile = getattr(self, 'browser_profile', None)
- if profile and (getattr(self, 'initialized', None) or getattr(self, 'browser_context', None) or browser_pid):
- keep_alive = getattr(profile, 'keep_alive', None)
- user_data_dir = getattr(profile, 'user_data_dir', None)
- logger.info(
- f'๐Ÿ›‘ {self} Stopping (went out of scope) {self._connection_str} keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'
- )
+ 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>"}'
+ )
except BaseException:
# Never let __del__ raise exceptions
- pass
+ raise
async def setup_playwright(self) -> None:
"""
@@ -444,17 +452,15 @@ class BrowserSession(BaseModel):
# use patchright instead of playwright
self.playwright = self.playwright or (await async_patchright().start())
self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROME
- logger.info(
- f'๐Ÿ•ถ๏ธ {self} Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...'
- )
+ self.logger.info(f'๐Ÿ•ถ๏ธ Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...')
# check for stealth best-practices
if self.browser_profile.channel and self.browser_profile.channel != BrowserChannel.CHROME:
- logger.info(f' ๐Ÿช„ For maximum stealth, {self}(...) should be passed channel=None or BrowserChannel.CHROME')
+ self.logger.info(' ๐Ÿช„ For maximum stealth, (...) should be passed channel=None or BrowserChannel.CHROME')
if not self.browser_profile.user_data_dir:
- logger.info(f' ๐Ÿช„ For maximum stealth, {self}(...) should be passed a persistent user_data_dir=...')
+ self.logger.info(' ๐Ÿช„ For maximum stealth, (...) should be passed a persistent user_data_dir=...')
if self.browser_profile.headless or not self.browser_profile.no_viewport:
- logger.info(f' ๐Ÿช„ For maximum stealth, {self}(...) should be passed headless=False & viewport=None')
+ self.logger.info(' ๐Ÿช„ For maximum stealth, (...) should be passed headless=False & viewport=None')
else:
# default is standard playwright chromium (headful, or headless=new)
self.playwright = self.playwright or (await async_playwright().start())
@@ -492,7 +498,7 @@ class BrowserSession(BaseModel):
self.browser = browser_from_context
if self.browser or self.browser_context:
- logger.info(f'๐ŸŽญ {self} Connected to existing user-provided browser: {self.browser_context}')
+ self.logger.info(f'๐ŸŽญ Connected to existing user-provided browser: {self.browser_context}')
self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
async def setup_browser_via_browser_pid(self) -> None:
@@ -512,7 +518,7 @@ class BrowserSession(BaseModel):
)
# we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
- logger.info(f'๐ŸŒŽ {self} Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
+ self.logger.info(f'๐ŸŒŽ Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
self.cdp_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -527,7 +533,7 @@ class BrowserSession(BaseModel):
if not self.wss_url:
return # no wss_url provided, nothing to do
- logger.info(f'๐ŸŒŽ {self} Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
+ self.logger.info(f'๐ŸŒŽ Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
self.browser = self.browser or await self.playwright.chromium.connect(
self.wss_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -542,7 +548,7 @@ class BrowserSession(BaseModel):
if not self.cdp_url:
return # no cdp_url provided, nothing to do
- logger.info(f'๐ŸŒŽ {self} Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
+ self.logger.info(f'๐ŸŒŽ Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
self.cdp_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -558,7 +564,7 @@ class BrowserSession(BaseModel):
if self.browser and not self.browser_context:
if self.browser.contexts:
self.browser_context = self.browser.contexts[0]
- logger.info(f'๐ŸŒŽ {self} Using first browser_context available in existing browser: {self.browser_context}')
+ self.logger.info(f'๐ŸŒŽ Using first browser_context available in existing browser: {self.browser_context}')
else:
self.browser_context = await self.browser.new_context(
**self.browser_profile.kwargs_for_new_context().model_dump()
@@ -568,28 +574,28 @@ class BrowserSession(BaseModel):
if self.browser_profile.storage_state
else ''
)
- logger.info(
- f'๐ŸŒŽ {self} Created new empty browser_context in existing browser{storage_info}: {self.browser_context}'
+ self.logger.info(
+ f'๐ŸŒŽ Created new empty browser_context in existing browser{storage_info}: {self.browser_context}'
)
# if we still have no browser_context by now, launch a new local one using launch_persistent_context()
if not self.browser_context:
- logger.info(
- f'๐ŸŒŽ {self} Launching new local browser '
+ self.logger.info(
+ f'๐ŸŒŽ Launching new local browser '
f'{str(type(self.playwright).__module__).split(".")[0]}:{self.browser_profile.channel.name.lower()} keep_alive={self.browser_profile.keep_alive or False} '
f'user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"}'
)
if not self.browser_profile.user_data_dir:
- # logger.debug('๐ŸŒŽ Launching local browser in incognito mode')
+ # self.logger.debug('๐ŸŒŽ Launching local browser in incognito mode')
# if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir
self.browser = self.browser or await self.playwright.chromium.launch(
**self.browser_profile.kwargs_for_launch().model_dump()
)
- # logger.debug('๐ŸŒŽ Launching new incognito context in browser')
+ # self.logger.debug('๐ŸŒŽ Launching new incognito context in browser')
self.browser_context = await self.browser.new_context(
**self.browser_profile.kwargs_for_new_context().model_dump()
)
- # logger.debug('๐ŸŒŽ Created new incognito context in browser')
+ # self.logger.debug('๐ŸŒŽ Created new incognito context in browser')
else:
# user data dir was provided, prepare it for use
self.browser_profile.prepare_user_data_dir()
@@ -597,8 +603,8 @@ class BrowserSession(BaseModel):
# search for potentially conflicting local processes running on the same user_data_dir
for proc in psutil.process_iter(['pid', 'cmdline']):
if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
- logger.error(
- f'๐Ÿšจ {self} Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
+ self.logger.error(
+ f'๐Ÿšจ Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
f'already running with the same user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)}'
)
break
@@ -633,8 +639,8 @@ class BrowserSession(BaseModel):
if self.browser_profile.executable_path
else (self.browser_profile.channel or BROWSERUSE_DEFAULT_CHANNEL).name.lower()
)
- logger.error(
- f'โŒ {self} Launching new local browser {driver}:{browser_channel} (v{test_browser_version}) failed!'
+ self.logger.error(
+ f'โŒ Launching new local browser {driver}:{browser_channel} (v{test_browser_version}) failed!'
f'\n\tFailed {reason} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)} (created with v{user_data_dir_chrome_version})'
'\n\tTry using a different browser version/channel or delete the user_data_dir to start over with a fresh profile.'
'\n\t(can happen if different versions of Chrome/Chromium/Brave/etc. tried to share one dir)'
@@ -656,30 +662,28 @@ class BrowserSession(BaseModel):
new_child_procs = [psutil.Process(pid) for pid in new_child_pids]
new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']
except Exception as e:
- logger.debug(
- f'โŒ {self} Error trying to find child chrome processes after launching new browser: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โŒ Error trying to find child chrome processes after launching new browser: {type(e).__name__}: {e}'
)
new_chrome_procs = []
if new_chrome_procs and not self.browser_pid:
self.browser_pid = new_chrome_procs[0].pid
- logger.info(
- f' โ†ณ {self} Spawned browser subprocess with browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}'
- )
- logger.debug(' '.join(new_chrome_procs[0].cmdline())) # print the entire launch command for debugging
+ self.logger.info(f' โ†ณ Spawned browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}')
+ self.logger.debug(' '.join(new_chrome_procs[0].cmdline())) # print the entire launch command for debugging
self._set_browser_keep_alive(False) # close the browser at the end because we launched it
if self.browser:
assert self.browser.is_connected(), (
f'Browser is not connected, did the browser process crash or get killed? (connection method: {self._connection_str})'
)
- logger.debug(f'๐ŸŒŽ {self} browser connected: v{self.browser.version} {self._connection_str}')
+ self.logger.debug(f'๐ŸŒŽ browser connected: v{self.browser.version} {self._connection_str}')
assert self.browser_context, (
f'{self} Failed to create a playwright BrowserContext {self.browser_context} for browser={self.browser}'
)
- # logger.debug('Setting up init scripts in browser')
+ # self.logger.debug('Setting up init scripts in browser')
init_script = """
// check to make sure we're not inside the PDF viewer
@@ -735,7 +739,7 @@ class BrowserSession(BaseModel):
await self.browser_context.add_init_script(init_script)
if self.browser_profile.stealth and not isinstance(self.playwright, Patchright):
- logger.warning(f'โš ๏ธ {self} Failed to set up stealth mode. {self}(...) got normal playwright objects as input.')
+ self.logger.warning('โš ๏ธ Failed to set up stealth mode. (...) got normal playwright objects as input.')
# async def _fork_locked_user_data_dir(self) -> None:
# """Fork an in-use user_data_dir by cloning it to a new location to allow a second browser to use it"""
@@ -784,17 +788,17 @@ class BrowserSession(BaseModel):
foreground_page = None
if pages:
foreground_page = pages[0]
- logger.debug(
- f'๐Ÿ“œ {self} Found {len(pages)} existing tabs in browser, agent will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
+ self.logger.debug(
+ f'๐Ÿ“œ Found {len(pages)} existing tabs in browser, agent will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
)
else:
foreground_page = await self.browser_context.new_page()
pages = [foreground_page]
- logger.debug('โž• {self} Opened new tab in empty browser context...')
+ self.logger.debug('โž• Opened new tab in empty browser context...')
self.agent_current_page = self.agent_current_page or foreground_page
self.human_current_page = self.human_current_page or foreground_page
- # logger.debug('About to define _BrowserUseonTabVisibilityChange callback')
+ # self.logger.debug('About to define _BrowserUseonTabVisibilityChange callback')
def _BrowserUseonTabVisibilityChange(source: dict[str, str]):
"""hook callback fired when init script injected into a page detects a focus event"""
@@ -814,8 +818,8 @@ class BrowserSession(BaseModel):
agent_url = self.agent_current_page and self.agent_current_page.url or 'about:blank'
agent_tab_idx = self.browser_context.pages.index(self.agent_current_page)
if old_url != new_url:
- logger.info(
- f'๐Ÿ‘๏ธ {self} Foregound tab changed by human from [{old_tab_idx}]{_log_pretty_url(old_url)} '
+ self.logger.info(
+ f'๐Ÿ‘๏ธ Foregound tab changed by human from [{old_tab_idx}]{_log_pretty_url(old_url)} '
f'โžก๏ธ [{new_tab_idx}]{_log_pretty_url(new_url)} '
f'(agent will stay on [{agent_tab_idx}]{_log_pretty_url(agent_url)})'
)
@@ -823,14 +827,14 @@ class BrowserSession(BaseModel):
# Store the callback so we can potentially clean it up later
self._tab_visibility_callback = _BrowserUseonTabVisibilityChange
- # logger.info('About to call expose_binding')
+ # self.logger.info('About to call expose_binding')
try:
await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
- logger.debug('expose_binding completed successfully')
+ # self.logger.debug('window._BrowserUseonTabVisibilityChange binding attached via browser_context')
except Exception as e:
if 'Function "_BrowserUseonTabVisibilityChange" has been already registered' in str(e):
- logger.debug(
- f'โš ๏ธ {self} Function "_BrowserUseonTabVisibilityChange" has been already registered, '
+ self.logger.debug(
+ 'โš ๏ธ Function "_BrowserUseonTabVisibilityChange" has been already registered, '
'this is likely because the browser was already started with an existing BrowserSession()'
)
@@ -867,23 +871,23 @@ class BrowserSession(BaseModel):
try:
await self.browser_context.add_init_script(update_tab_focus_script)
except Exception as e:
- logger.debug(f'โš ๏ธ {self} Failed to register init script for tab focus detection: {e}')
+ self.logger.debug(f'โš ๏ธ Failed to register init script for tab focus detection: {e}')
# Set up visibility listeners for all existing tabs
- # logger.info(f'Setting up visibility listeners for {len(self.browser_context.pages)} pages')
+ # self.logger.info(f'Setting up visibility listeners for {len(self.browser_context.pages)} pages')
for page in self.browser_context.pages:
- # logger.info(f'Processing page with URL: {repr(page.url)}')
+ # self.logger.info(f'Processing page with URL: {repr(page.url)}')
# Skip about:blank pages as they can hang when evaluating scripts
if page.url == 'about:blank':
continue
try:
await page.evaluate(update_tab_focus_script)
- # logger.debug(f'๐Ÿ‘๏ธ {self} Added visibility listener to existing tab: {page.url}')
+ # self.logger.debug(f'๐Ÿ‘๏ธ Added visibility listener to existing tab: {page.url}')
except Exception as e:
page_idx = self.browser_context.pages.index(page)
- logger.debug(
- f'โš ๏ธ {self} Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โš ๏ธ Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
)
async def _setup_viewports(self) -> None:
@@ -891,8 +895,8 @@ class BrowserSession(BaseModel):
# log the viewport settings to terminal
viewport = self.browser_profile.viewport
- logger.debug(
- '๐Ÿ“ {self} Setting up viewport: '
+ self.logger.debug(
+ '๐Ÿ“ Setting up viewport: '
+ f'headless={self.browser_profile.headless} '
+ (
f'window={self.browser_profile.window_size["width"]}x{self.browser_profile.window_size["height"]}px '
@@ -920,8 +924,8 @@ class BrowserSession(BaseModel):
try:
await self.browser_context.grant_permissions(self.browser_profile.permissions)
except Exception as e:
- logger.warning(
- f'โš ๏ธ {self} Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โš ๏ธ Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'
)
try:
if self.browser_profile.default_timeout:
@@ -929,8 +933,8 @@ class BrowserSession(BaseModel):
if self.browser_profile.default_navigation_timeout:
await self.browser_context.set_default_navigation_timeout(self.browser_profile.default_navigation_timeout)
except Exception as e:
- logger.warning(
- f'โš ๏ธ {self} Failed to set playwright timeout settings '
+ self.logger.warning(
+ f'โš ๏ธ Failed to set playwright timeout settings '
f'cdp_api={self.browser_profile.default_timeout} '
f'navigation={self.browser_profile.default_navigation_timeout}: {type(e).__name__}: {e}'
)
@@ -938,16 +942,16 @@ class BrowserSession(BaseModel):
if self.browser_profile.extra_http_headers:
await self.browser_context.set_extra_http_headers(self.browser_profile.extra_http_headers)
except Exception as e:
- logger.warning(
- f'โš ๏ธ {self} Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โš ๏ธ Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}'
) # dont print the secret header contents in the logs!
try:
if self.browser_profile.geolocation:
await self.browser_context.set_geolocation(self.browser_profile.geolocation)
except Exception as e:
- logger.warning(
- f'โš ๏ธ {self} Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โš ๏ธ Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}'
)
await self.load_storage_state()
@@ -995,8 +999,8 @@ class BrowserSession(BaseModel):
except Exception as e:
pass
- logger.warning(
- f'โš ๏ธ {self} Failed to resize browser window to {_log_size(self.browser_profile.window_size)} using CDP setWindowBounds: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โš ๏ธ Failed to resize browser window to {_log_size(self.browser_profile.window_size)} using CDP setWindowBounds: {type(e).__name__}: {e}'
)
def _set_browser_keep_alive(self, keep_alive: bool | None) -> None:
@@ -1055,9 +1059,7 @@ class BrowserSession(BaseModel):
proc_is_alive = proc.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
assert proc_is_alive and '--remote-debugging-port' in ' '.join(proc.cmdline())
except Exception:
- logger.info(
- f'๐Ÿ‘‹ {self} Browser process browser_pid={self.browser_pid} has gone away or crashed, will be re-launched'
- )
+ self.logger.info(f'โšฐ๏ธ Browser browser_pid={self.browser_pid} has gone away or crashed')
# process has gone away or crashed, pid is no longer valid so we clear it
self.browser_pid = None
@@ -1154,7 +1156,7 @@ class BrowserSession(BaseModel):
"""
)
except Exception as e:
- logger.debug(f'โš ๏ธ {self} Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')
+ self.logger.debug(f'โš ๏ธ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')
# Don't raise the error since this is not critical functionality
@require_initialization
@@ -1197,11 +1199,11 @@ class BrowserSession(BaseModel):
unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, suggested_filename)
download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
await download.save_as(download_path)
- logger.debug(f'โฌ‡๏ธ {self} Download triggered. Saved file to: {download_path}')
+ self.logger.debug(f'โฌ‡๏ธ Download triggered. Saved file to: {download_path}')
return download_path
except Exception:
# If no download is triggered, treat as normal click
- logger.debug(f'{self} No download triggered within timeout. Checking navigation...')
+ self.logger.debug('No download triggered within timeout. Checking navigation...')
await page.wait_for_load_state()
await self._check_and_handle_navigation(page)
else:
@@ -1239,7 +1241,7 @@ class BrowserSession(BaseModel):
except TimeoutError:
# page.title() can hang forever on tabs that are crashed/disappeared/about:blank
# we dont want to try automating those tabs because they will hang the whole script
- logger.debug(f'โš ๏ธ {self} Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
+ self.logger.debug(f'โš ๏ธ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
tabs_info.append(tab_info)
@@ -1310,10 +1312,10 @@ class BrowserSession(BaseModel):
pass
temp_path.replace(cookies_file_path)
- logger.info(f'๐Ÿช {self} Saved {len(cookies)} cookies to cookies_file= {_log_pretty_path(cookies_file_path)}')
+ self.logger.info(f'๐Ÿช Saved {len(cookies)} cookies to cookies_file= {_log_pretty_path(cookies_file_path)}')
except Exception as e:
- logger.warning(
- f'โŒ {self} Failed to save cookies to cookies_file= {_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โŒ Failed to save cookies to cookies_file= {_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
)
async def _save_storage_state_to_file(self, path: Path, storage_state: dict[str, Any] | None) -> None:
@@ -1329,8 +1331,8 @@ class BrowserSession(BaseModel):
existing_storage_state = json.loads(json_path.read_text())
merged_storage_state = merge_dicts(existing_storage_state, storage_state)
except Exception as e:
- logger.error(
- f'โŒ {self} Failed to merge cookie changes with existing storage_state= {_log_pretty_path(json_path)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'โŒ Failed to merge cookie changes with existing storage_state= {_log_pretty_path(json_path)}: {type(e).__name__}: {e}'
)
return
@@ -1343,13 +1345,9 @@ class BrowserSession(BaseModel):
pass
temp_path.replace(json_path)
- logger.info(
- f'๐Ÿช {self} Saved {len(storage_state["cookies"])} cookies to storage_state= {_log_pretty_path(json_path)}'
- )
+ self.logger.info(f'๐Ÿช Saved {len(storage_state["cookies"])} cookies to storage_state= {_log_pretty_path(json_path)}')
except Exception as e:
- logger.warning(
- f'โŒ {self} Failed to save cookies to storage_state= {_log_pretty_path(path)}: {type(e).__name__}: {e}'
- )
+ self.logger.warning(f'โŒ Failed to save cookies to storage_state= {_log_pretty_path(path)}: {type(e).__name__}: {e}')
@require_initialization
async def save_storage_state(self, path: Path | None = None) -> None:
@@ -1370,7 +1368,7 @@ class BrowserSession(BaseModel):
await self._save_cookies_to_file(path, cookies)
await self._save_storage_state_to_file(path.parent / 'storage_state.json', storage_state)
new_path = path.parent / 'storage_state.json'
- logger.warning(
+ self.logger.warning(
'โš ๏ธ cookies_file is deprecated and will be removed in a future version. '
f'Please use storage_state="{_log_pretty_path(new_path)}" instead for persisting cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1383,7 +1381,7 @@ class BrowserSession(BaseModel):
await self._save_cookies_to_file(path or self.browser_profile.cookies_file, cookies)
await self._save_storage_state_to_file(path.parent / 'storage_state.json', storage_state)
new_path = path.parent / 'storage_state.json'
- logger.warning(
+ self.logger.warning(
'โš ๏ธ cookies_file is deprecated and will be removed in a future version. '
f'Please use storage_state="{_log_pretty_path(new_path)}" instead for persisting cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1398,8 +1396,8 @@ class BrowserSession(BaseModel):
# if your cookies are frozen in time and don't update, they'll block you as a bot almost immediately
# if they pass a dict in it means they have to get the updated cookies manually with browser_context.cookies()
# and persist them manually on every change. most people don't realize they have to do that, so show a warning
- logger.warning(
- f'โš ๏ธ {self} storage_state was set as a {type(self.browser_profile.storage_state)} and will not be updated with any cookie changes, use a json file path instead to persist changes'
+ self.logger.warning(
+ f'โš ๏ธ storage_state was set as a {type(self.browser_profile.storage_state)} and will not be updated with any cookie changes, use a json file path instead to persist changes'
)
return
@@ -1417,7 +1415,7 @@ class BrowserSession(BaseModel):
if self.browser_profile.cookies_file:
# Show deprecation warning
- logger.warning(
+ self.logger.warning(
'โš ๏ธ cookies_file is deprecated and will be removed in a future version. '
'Please use storage_state instead for loading cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1431,12 +1429,10 @@ class BrowserSession(BaseModel):
cookies_data = json.loads(cookies_path.read_text())
if cookies_data:
await self.browser_context.add_cookies(cookies_data)
- logger.info(
- f'๐Ÿช {self} Loaded {len(cookies_data)} cookies from cookies_file= {_log_pretty_path(cookies_path)}'
- )
+ self.logger.info(f'๐Ÿช Loaded {len(cookies_data)} cookies from cookies_file= {_log_pretty_path(cookies_path)}')
except Exception as e:
- logger.warning(
- f'โŒ {self} Failed to load cookies from cookies_file= {_log_pretty_path(cookies_path)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โŒ Failed to load cookies from cookies_file= {_log_pretty_path(cookies_path)}: {type(e).__name__}: {e}'
)
if self.browser_profile.storage_state:
@@ -1446,8 +1442,8 @@ class BrowserSession(BaseModel):
storage_state_text = await anyio.Path(storage_state).read_text()
storage_state = json.loads(storage_state_text)
except Exception as e:
- logger.warning(
- f'โŒ {self} Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โŒ Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
)
return
@@ -1458,12 +1454,12 @@ class BrowserSession(BaseModel):
# playwright doesn't provide an API for setting these before launch
# https://playwright.dev/python/docs/auth#session-storage
# await self.browser_context.add_local_storage(storage_state['localStorage'])
- logger.info(
- f'๐Ÿช {self} Loaded {len(storage_state["cookies"])} cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}'
+ self.logger.info(
+ f'๐Ÿช Loaded {len(storage_state["cookies"])} cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}'
)
except Exception as e:
- logger.warning(
- f'โŒ {self} Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'โŒ Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
)
return
@@ -1586,7 +1582,7 @@ class BrowserSession(BaseModel):
nonlocal last_activity
pending_requests.add(request)
last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request started: {request.url} ({request.resource_type})')
+ # self.logger.debug(f'Request started: {request.url} ({request.resource_type})')
async def on_response(response):
request = response.request
@@ -1627,7 +1623,7 @@ class BrowserSession(BaseModel):
nonlocal last_activity
pending_requests.remove(request)
last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request resolved: {request.url} ({content_type})')
+ # self.logger.debug(f'Request resolved: {request.url} ({content_type})')
# Attach event listeners
page.on('request', on_request)
@@ -1646,7 +1642,7 @@ class BrowserSession(BaseModel):
):
break
if now - start_time > self.browser_profile.maximum_wait_page_load_time:
- logger.debug(
+ self.logger.debug(
f'{self} Network timeout after {self.browser_profile.maximum_wait_page_load_time}s with {len(pending_requests)} '
f'pending requests: {[r.url for r in pending_requests]}'
)
@@ -1659,7 +1655,7 @@ class BrowserSession(BaseModel):
elapsed = now - start_time
if elapsed > 1:
- logger.debug(f'๐Ÿ’ค Page network traffic calmed down after {now - start_time:.2f} seconds')
+ self.logger.debug(f'๐Ÿ’ค Page network traffic calmed down after {now - start_time:.2f} seconds')
async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
"""
@@ -1680,8 +1676,8 @@ class BrowserSession(BaseModel):
except URLNotAllowedError as e:
raise e
except Exception as e:
- logger.warning(
- f'โš ๏ธ {self} Page load for {_log_pretty_url(page.url)} failed due to {type(e).__name__}, continuing anyway...'
+ self.logger.warning(
+ f'โš ๏ธ Page load for {_log_pretty_url(page.url)} failed due to {type(e).__name__}, continuing anyway...'
)
# Calculate remaining time to meet minimum WAIT_TIME
@@ -1707,12 +1703,12 @@ class BrowserSession(BaseModel):
tab_idx = self.tabs.index(page)
if bytes_used is not None:
- logger.debug(
- f'โžก๏ธ {self} Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} used {bytes_used / 1024:.1f} KB in {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
+ self.logger.debug(
+ f'โžก๏ธ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} used {bytes_used / 1024:.1f} KB in {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
)
else:
- logger.debug(
- f'โžก๏ธ {self} Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} took {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
+ self.logger.debug(
+ f'โžก๏ธ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} took {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
)
# Sleep remaining time if needed
@@ -1756,11 +1752,11 @@ class BrowserSession(BaseModel):
async def _check_and_handle_navigation(self, page: Page) -> None:
"""Check if current page URL is allowed and handle if not."""
if not self._is_url_allowed(page.url):
- logger.warning(f'โ›”๏ธ {self} Navigation to non-allowed URL detected: {page.url}')
+ self.logger.warning(f'โ›”๏ธ Navigation to non-allowed URL detected: {page.url}')
try:
await self.go_back()
except Exception as e:
- logger.error(f'โ›”๏ธ {self} Failed to go back after detecting non-allowed URL: {type(e).__name__}: {e}')
+ self.logger.error(f'โ›”๏ธ Failed to go back after detecting non-allowed URL: {type(e).__name__}: {e}')
raise URLNotAllowedError(f'Navigation to non-allowed URL: {page.url}')
async def navigate_to(self, url: str):
@@ -1789,7 +1785,7 @@ class BrowserSession(BaseModel):
# await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
except Exception as e:
# Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'โฎ๏ธ {self} Error during go_back: {type(e).__name__}: {e}')
+ self.logger.debug(f'โฎ๏ธ Error during go_back: {type(e).__name__}: {e}')
async def go_forward(self):
"""Navigate the agent's tab forward in browser history"""
@@ -1798,7 +1794,7 @@ class BrowserSession(BaseModel):
await page.go_forward(timeout=10, wait_until='domcontentloaded')
except Exception as e:
# Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'โญ๏ธ {self} Error during go_forward: {type(e).__name__}: {e}')
+ self.logger.debug(f'โญ๏ธ Error during go_forward: {type(e).__name__}: {e}')
async def close_current_tab(self):
"""Close the current tab that the agent is working with.
@@ -1817,7 +1813,7 @@ class BrowserSession(BaseModel):
try:
await self.agent_current_page.close()
except Exception as e:
- logger.debug(f'โ›”๏ธ {self} Error during close_current_tab: {type(e).__name__}: {e}')
+ self.logger.debug(f'โ›”๏ธ Error during close_current_tab: {type(e).__name__}: {e}')
# Clear agent's reference to the closed tab
self.agent_current_page = None
@@ -1964,7 +1960,7 @@ class BrowserSession(BaseModel):
# Test if page is still accessible
await page.evaluate('1')
except Exception as e:
- logger.debug(f'๐Ÿ‘‹ {self} Current page is no longer accessible: {type(e).__name__}: {e}')
+ self.logger.debug(f'๐Ÿ‘‹ Current page is no longer accessible: {type(e).__name__}: {e}')
raise BrowserError('Browser closed: no valid pages available')
try:
@@ -1988,7 +1984,7 @@ class BrowserSession(BaseModel):
# if url in [tab.url for tab in tabs_info]:
# continue # skip if the iframe if we already have it open in a tab
# new_page_id = tabs_info[-1].page_id + 1
- # logger.debug(f'Opening cross-origin iframe in new tab #{new_page_id}: {url}')
+ # self.logger.debug(f'Opening cross-origin iframe in new tab #{new_page_id}: {url}')
# await self.create_new_tab(url)
# tabs_info.append(
# TabInfo(
@@ -2015,7 +2011,7 @@ class BrowserSession(BaseModel):
return self.browser_state_summary
except Exception as e:
- logger.error(f'โŒ {self} Failed to update browser_state_summary: {type(e).__name__}: {e}')
+ self.logger.error(f'โŒ Failed to update browser_state_summary: {type(e).__name__}: {e}')
# Return last known good state if available
if hasattr(self, 'browser_state_summary'):
return self.browser_state_summary
@@ -2048,8 +2044,8 @@ class BrowserSession(BaseModel):
screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
return screenshot_b64
except Exception as e:
- logger.error(
- f'โŒ {self} Failed to take full-page screenshot: {type(e).__name__}: {e} falling back to viewport-only screenshot'
+ self.logger.error(
+ f'โŒ Failed to take full-page screenshot: {type(e).__name__}: {e} falling back to viewport-only screenshot'
)
# Fallback method: manually expand the viewport and take a screenshot of the entire viewport
@@ -2339,8 +2335,8 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(
- f'โŒ {self} Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'โŒ Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None
@@ -2362,7 +2358,7 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(f'โŒ {self} Failed to locate xpath {xpath} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}')
+ self.logger.error(f'โŒ Failed to locate xpath {xpath} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}')
return None
@require_initialization
@@ -2383,8 +2379,8 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(
- f'โŒ {self} Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'โŒ Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None
@@ -2407,15 +2403,15 @@ class BrowserSession(BaseModel):
elements = [el for el in elements if await self._is_visible(el)]
if not elements:
- logger.error(f"โŒ {self} No visible element with text '{text}' found on page {_log_pretty_url(page.url)}.")
+ self.logger.error(f"โŒ No visible element with text '{text}' found on page {_log_pretty_url(page.url)}.")
return None
if nth is not None:
if 0 <= nth < len(elements):
element_handle = elements[nth]
else:
- logger.error(
- f"โŒ {self} Visible element with text '{text}' not found at index #{nth} on page {_log_pretty_url(page.url)}."
+ self.logger.error(
+ f"โŒ Visible element with text '{text}' not found at index #{nth} on page {_log_pretty_url(page.url)}."
)
return None
else:
@@ -2426,8 +2422,8 @@ class BrowserSession(BaseModel):
await element_handle.scroll_into_view_if_needed()
return element_handle
except Exception as e:
- logger.error(
- f"โŒ {self} Failed to locate element by text '{text}' on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}"
+ self.logger.error(
+ f"โŒ Failed to locate element by text '{text}' on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}"
)
return None
@@ -2484,8 +2480,8 @@ class BrowserSession(BaseModel):
await page.keyboard.type(text)
except Exception as e:
- logger.debug(
- f'โŒ {self} Failed to input text into element: {repr(element_node)} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โŒ Failed to input text into element: {repr(element_node)} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
@@ -2546,7 +2542,7 @@ class BrowserSession(BaseModel):
await new_page.goto(url, wait_until='domcontentloaded')
await self._wait_for_page_and_frames_load(timeout_overwrite=1)
except Exception as e:
- logger.error(f'โŒ {self} Error navigating to {url}: {type(e).__name__}: {e}')
+ self.logger.error(f'โŒ Error navigating to {url}: {type(e).__name__}: {e}')
assert self.human_current_page is not None
assert self.agent_current_page is not None
@@ -2668,8 +2664,8 @@ class BrowserSession(BaseModel):
except Exception as e:
page = await self.get_current_page()
- logger.debug(
- f'โŒ {self} Error in find_file_upload_element_by_index(index={index}) on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'โŒ Error in find_file_upload_element_by_index(index={index}) on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None