Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Update info logger to debug
Magnus Müller8c1b4bf79476
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 077847592..8da711911 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -84,7 +84,7 @@ def log_response(response: AgentOutput, registry=None, logger=None) -> None:# Only log thinking if it's presentif response.current_state.thinking:- logger.info(f'💡 Thinking:\n{response.current_state.thinking}')+ logger.debug(f'💡 Thinking:\n{response.current_state.thinking}')# Only log evaluation if it's not emptyeval_goal = response.current_state.evaluation_previous_goal@@ -99,7 +99,7 @@ def log_response(response: AgentOutput, registry=None, logger=None) -> None:# Always log memory if presentif response.current_state.memory:- logger.info(f'🧠 Memory: {response.current_state.memory}')+ logger.debug(f'🧠 Memory: {response.current_state.memory}')# Only log next goal if it's not emptynext_goal = response.current_state.next_goal@@ -312,8 +312,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.settings.use_vision = False# Note: No longer checking planner_llm for XAI models (deprecated)- self.logger.info(- f'🧠 Starting a browser-use agent {self.version} with base_model={self.llm.model}'+ self.logger.info(f'🧠 Starting a browser-use version {self.version} with model={self.llm.model}')+ 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)@@ -450,7 +450,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.has_downloads_path = self.browser_session.browser_profile.downloads_path is not Noneif self.has_downloads_path:self._last_known_downloads: list[str] = []- self.logger.info('📁 Initialized download tracking for agent')+ self.logger.debug('📁 Initialized download tracking for agent')self._external_pause_event = asyncio.Event()self._external_pause_event.set()@@ -546,7 +546,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Save file system state to agent stateself.state.file_system_state = self.file_system.get_state()- logger.info(f'💾 File system path: {self.file_system_path}')+ logger.debug(f'💾 File system path: {self.file_system_path}')def _set_screenshot_service(self) -> None:"""Initialize screenshot service using agent directory"""@@ -554,7 +554,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):from browser_use.screenshots.service import ScreenshotServiceself.screenshot_service = ScreenshotService(self.agent_directory)- logger.info(f'📸 Screenshot service initialized in: {self.agent_directory}/screenshots')+ logger.debug(f'📸 Screenshot service initialized in: {self.agent_directory}/screenshots')except Exception as e:logger.error(f'📸 Failed to initialize screenshot service: {e}.')raise e@@ -1046,7 +1046,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):def _log_agent_run(self) -> None:"""Log the agent run"""- self.logger.info(f'🚀 Starting task: {self.task}')+ self.logger.info(f'🚀 Task: {self.task}')self.logger.debug(f'🤖 Browser-Use Library Version {self.version} ({self.source})')@@ -1055,9 +1055,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):url = browser_state_summary.url if browser_state_summary else ''url_short = url[:50] + '...' if len(url) > 50 else urlinteractive_count = len(browser_state_summary.dom_state.selector_map) if browser_state_summary else 0- self.logger.info(- f'📍 Step {self.state.n_steps}: Evaluating page with {interactive_count} interactive elements on: {url_short}'- )+ self.logger.info('')+ self.logger.info(f'📍 Step {self.state.n_steps}:')+ self.logger.debug(f'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)"""@@ -1120,7 +1120,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):status_parts = [part for part in [success_indicator, failure_indicator] if part]status_str = ' | '.join(status_parts) if status_parts else '✅ 0'- self.logger.info(f'📍 Step {self.state.n_steps}: Ran {action_count} actions in {step_duration:.2f}s: {status_str}')+ self.logger.debug(+ f'📍 Step {self.state.n_steps}: Ran {action_count} action{"" if action_count == 1 else "s"} in {step_duration:.2f}s: {status_str}'+ )def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:"""Sent the agent event for this run to telemetry"""@@ -1606,16 +1608,20 @@ class Agent(Generic[Context, AgentStructuredOutput]):time_elapsed = time_end - time_startresults.append(result)- self.logger.info(- f'☑️ Executed action {i + 1}/{total_actions}: {green}{action_name}({action_params}){reset} in {time_elapsed:.2f}s'- )+ if self.logger.isEnabledFor(logging.INFO):+ self.logger.info(f'☑️ Action: {green}{action_params}{reset}')+ else:+ self.logger.debug(+ f'☑️ Executed action {i + 1}/{total_actions}: {green}{action_params}{reset} in {time_elapsed:.2f}s'+ )+if results[-1].is_done or results[-1].error or i == total_actions - 1:breakexcept Exception as e:# Handle any exceptions during action executionself.logger.error(- f'❌ Executing action {i + 1} failed in {time_elapsed:.2f}s {red}{action_name}({action_params}) -> {type(e).__name__}: {e}{reset}'+ f'❌ Executing action {i + 1} failed in {time_elapsed:.2f}s {red}({action_params}) -> {type(e).__name__}: {e}{reset}')raise ediff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex 5421b11bc..5c0e24b8b 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -178,7 +178,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Try to scroll the element's containersuccess = await self._scroll_element_container(element_node, pixels)if success:- self.logger.info(+ self.logger.debug(f'📜 Scrolled element {index_for_logging} container {event.direction} by {event.amount} pixels')@@ -213,7 +213,7 @@ class DefaultActionWatchdog(BaseWatchdog):self.browser_session._dom_watchdog.clear_cache()# Log success- self.logger.info(f'📜 Scrolled {event.direction} by {event.amount} pixels')+ self.logger.debug(f'📜 Scrolled {event.direction} by {event.amount} pixels')return Noneexcept Exception as e:raise@@ -1340,7 +1340,7 @@ class DefaultActionWatchdog(BaseWatchdog):await cdp_client.send.DOM.scrollIntoViewIfNeeded(params={'nodeId': node_id}, session_id=session_id)found = True- self.logger.info(f'📜 Scrolled to text: "{event.text}"')+ self.logger.debug(f'📜 Scrolled to text: "{event.text}"')break# Clean up search@@ -1376,7 +1376,7 @@ class DefaultActionWatchdog(BaseWatchdog):)if js_result.get('result', {}).get('value'):- self.logger.info(f'📜 Scrolled to text: "{event.text}" (via JS)')+ self.logger.debug(f'📜 Scrolled to text: "{event.text}" (via JS)')return Noneelse:self.logger.warning(f'⚠️ Text not found: "{event.text}"')diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex dc0992715..54210b7a9 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -190,7 +190,7 @@ class DOMWatchdog(BaseWatchdog):# Fast path for empty pagesif not_a_meaningful_website:self.logger.debug(f'⚡ Skipping BuildDOMTree for empty target: {page_url}')- self.logger.info(f'📸 Not taking screenshot for empty page: {page_url} (non-http/https URL)')+ self.logger.debug(f'📸 Not taking screenshot for empty page: {page_url} (non-http/https URL)')# Create minimal DOM statecontent = SerializedDOMState(_root=None, selector_map={})diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pyindex eda203801..38fdda3ba 100644--- a/browser_use/browser/local_browser_watchdog.py+++ b/browser_use/browser/local_browser_watchdog.py@@ -46,7 +46,7 @@ class LocalBrowserWatchdog(BaseWatchdog):"""Launch a local browser process."""try:- self.logger.info(+ self.logger.debug(f'[LocalBrowserWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}, launching local browser')@@ -56,7 +56,7 @@ class LocalBrowserWatchdog(BaseWatchdog):self._subprocess = process- self.logger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')+ 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)@@ -64,7 +64,7 @@ class LocalBrowserWatchdog(BaseWatchdog):async def on_BrowserKillEvent(self, event: BrowserKillEvent) -> None:"""Kill the local browser subprocess."""- self.logger.info('[LocalBrowserWatchdog] Killing local browser process')+ self.logger.debug('[LocalBrowserWatchdog] Killing local browser process')if self._subprocess:await self._cleanup_process(self._subprocess)@@ -80,12 +80,12 @@ class LocalBrowserWatchdog(BaseWatchdog):self.browser_session.browser_profile.user_data_dir = self._original_user_data_dirself._original_user_data_dir = None- self.logger.info('[LocalBrowserWatchdog] Browser cleanup completed')+ self.logger.debug('[LocalBrowserWatchdog] Browser cleanup completed')async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:"""Listen for BrowserStopEvent and dispatch BrowserKillEvent without awaiting it."""if self.browser_session.is_local and self._subprocess:- self.logger.info('[LocalBrowserWatchdog] BrowserStopEvent received, dispatching BrowserKillEvent')+ self.logger.debug('[LocalBrowserWatchdog] BrowserStopEvent received, dispatching BrowserKillEvent')# Dispatch BrowserKillEvent without awaiting so it gets processed after all BrowserStopEvent handlersself.event_bus.dispatch(BrowserKillEvent())@@ -145,7 +145,7 @@ class LocalBrowserWatchdog(BaseWatchdog):stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)- self.logger.info(f'[LocalBrowserWatchdog] 🎭 Browser subprocess launched with browser_pid= {subprocess.pid}')+ self.logger.debug(f'[LocalBrowserWatchdog] 🎭 Browser subprocess launched with browser_pid= {subprocess.pid}')# Convert to psutil.Processprocess = psutil.Process(subprocess.pid)diff --git a/browser_use/browser/permissions_watchdog.py b/browser_use/browser/permissions_watchdog.pyindex 9f4694d47..7c926b484 100644--- a/browser_use/browser/permissions_watchdog.py+++ b/browser_use/browser/permissions_watchdog.py@@ -28,7 +28,7 @@ class PermissionsWatchdog(BaseWatchdog):self.logger.debug('No permissions to grant')return- self.logger.info(f'🔓 Granting browser permissions: {permissions}')+ self.logger.debug(f'🔓 Granting browser permissions: {permissions}')try:# Grant permissions using CDP Browser.grantPermissionsdiff --git a/browser_use/browser/popups_watchdog.py b/browser_use/browser/popups_watchdog.pyindex fd89c5a77..f517838a2 100644--- a/browser_use/browser/popups_watchdog.py+++ b/browser_use/browser/popups_watchdog.py@@ -22,19 +22,19 @@ class PopupsWatchdog(BaseWatchdog):def __init__(self, **kwargs):super().__init__(**kwargs)- self.logger.info(f'🚀 PopupsWatchdog initialized with browser_session={self.browser_session}, ID={id(self)}')+ self.logger.debug(f'🚀 PopupsWatchdog initialized with browser_session={self.browser_session}, ID={id(self)}')async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Set up JavaScript dialog handling when a new tab is created."""target_id = event.target_id- self.logger.info(f'🎯 PopupsWatchdog received TabCreatedEvent for target {target_id}')+ self.logger.debug(f'🎯 PopupsWatchdog received TabCreatedEvent for target {target_id}')# Skip if we've already registered for this targetif target_id in self._dialog_listeners_registered:self.logger.debug(f'Already registered dialog handlers for target {target_id}')return- self.logger.info(f'📌 Starting dialog handler setup for target {target_id}')+ self.logger.debug(f'📌 Starting dialog handler setup for target {target_id}')try:cdp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False@@ -43,14 +43,14 @@ class PopupsWatchdog(BaseWatchdog):# Set up async handler for JavaScript dialogs - now we can handle them immediately!async def handle_dialog(event_data, session_id: str | None = None):"""Handle JavaScript dialog events - accept immediately and dispatch event."""- self.logger.info(f'🚨 DIALOG EVENT RECEIVED: {event_data}, session_id={session_id}')+ self.logger.debug(f'🚨 DIALOG EVENT RECEIVED: {event_data}, session_id={session_id}')dialog_type = event_data.get('type', 'alert')message = event_data.get('message', '')url = event_data.get('url')frame_id = event_data.get('frameId')- self.logger.info(f"🔔 JavaScript {dialog_type} dialog detected: '{message[:50]}...' - accepting immediately")+ self.logger.debug(f"🔔 JavaScript {dialog_type} dialog detected: '{message[:50]}...' - accepting immediately")# Dispatch the event first so tests can observe itevent = self.browser_session.event_bus.dispatch(@@ -66,7 +66,7 @@ class PopupsWatchdog(BaseWatchdog):# Accept the dialog immediately to unblock the browsertry:if self.browser_session._cdp_client_root and session_id:- self.logger.info('🔄 Sending handleJavaScriptDialog command')+ self.logger.debug('🔄 Sending handleJavaScriptDialog command')await self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(params={'accept': True},session_id=session_id,@@ -78,21 +78,23 @@ class PopupsWatchdog(BaseWatchdog):self.logger.error(f'Failed to accept dialog: {e}')cdp_session.cdp_client.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]- self.logger.info(- f'✅ Successfully registered Page.javascriptDialogOpening handler for session {cdp_session.session_id}'+ self.logger.debug(+ f'Successfully registered Page.javascriptDialogOpening handler for session {cdp_session.session_id}')# Mark this target as having dialog handling set upself._dialog_listeners_registered.add(target_id)- self.logger.info(f'✅ Set up JavaScript dialog handling for tab {target_id}')+ self.logger.debug(f'Set up JavaScript dialog handling for tab {target_id}')except Exception as e:self.logger.warning(f'Failed to set up dialog handling for tab {target_id}: {e}')async def on_DialogOpenedEvent(self, event: DialogOpenedEvent) -> None:"""Handle the async closing of JavaScript dialogs."""- self.logger.info(f'📋 on_DialogOpenedEvent called with frame_id={event.frame_id} url={event.url} message={event.message}')+ self.logger.debug(+ f'📋 on_DialogOpenedEvent called with frame_id={event.frame_id} url={event.url} message={event.message}'+ )assert self.browser_session.agent_focus is not None, 'Agent focus not set when handling DialogOpenedEvent'diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 78747141f..c40625ae3 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -86,7 +86,7 @@ class CDPSession(BaseModel):import logginglogger = logging.getLogger(f'browser_use.CDPSession.{target_id[-4:]}')- logger.info(f'🔌 Creating dedicated WebSocket connection for target {target_id}')+ logger.debug(f'🔌 Creating dedicated WebSocket connection for target {target_id}')target_cdp_client = CDPClient(cdp_url)await target_cdp_client.start()@@ -403,7 +403,7 @@ class BrowserSession(BaseModel):async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:"""Handle navigation requests - core browser functionality."""- self.logger.info(f'[on_NavigateToUrlEvent] Received NavigateToUrlEvent: url={event.url}, new_tab={event.new_tab}')+ self.logger.debug(f'[on_NavigateToUrlEvent] Received NavigateToUrlEvent: url={event.url}, new_tab={event.new_tab}')if not self.agent_focus:self.logger.warning('Cannot navigate - browser not connected')return@@ -421,13 +421,13 @@ class BrowserSession(BaseModel):try:# Find or create target for navigation- self.logger.info(f'[on_NavigateToUrlEvent] Processing new_tab={event.new_tab}')+ self.logger.debug(f'[on_NavigateToUrlEvent] Processing new_tab={event.new_tab}')if event.new_tab:# Look for existing about:blank tab that's not the current onetargets = await self._cdp_get_all_pages()- self.logger.info(f'[on_NavigateToUrlEvent] Found {len(targets)} existing tabs')+ self.logger.debug(f'[on_NavigateToUrlEvent] Found {len(targets)} existing tabs')current_target_id = self.agent_focus.target_id if self.agent_focus else None- self.logger.info(f'[on_NavigateToUrlEvent] Current target_id: {current_target_id}')+ self.logger.debug(f'[on_NavigateToUrlEvent] Current target_id: {current_target_id}')for idx, target in enumerate(targets):self.logger.debug(@@ -440,10 +440,10 @@ class BrowserSession(BaseModel):# Create new tab if no reusable one foundif not target_id:- self.logger.info('[on_NavigateToUrlEvent] No reusable about:blank tab found, creating new tab...')+ self.logger.debug('[on_NavigateToUrlEvent] No reusable about:blank tab found, creating new tab...')try:target_id = await self._cdp_create_new_page('about:blank')- self.logger.info(f'[on_NavigateToUrlEvent] Created new page with target_id: {target_id}')+ self.logger.debug(f'[on_NavigateToUrlEvent] Created new page with target_id: {target_id}')targets = await self._cdp_get_all_pages()self.logger.info(f'Created new tab #{target_id[-4:]}')@@ -815,7 +815,7 @@ class BrowserSession(BaseModel):# self.event_bus.on(NavigationCompleteEvent, self._downloads_watchdog.on_NavigationCompleteEvent)self._downloads_watchdog.attach_to_session()if self.browser_profile.auto_download_pdfs:- self.logger.info('📄 PDF auto-download enabled for this session')+ self.logger.debug('📄 PDF auto-download enabled for this session')# # Initialize StorageStateWatchdog# StorageStateWatchdog.model_rebuild()@@ -920,7 +920,7 @@ class BrowserSession(BaseModel):assert self.cdp_url is not Nonebrowser_location = 'local browser' if self.is_local else 'remote browser'- self.logger.info(f'🌎 Connecting to existing chromium-based browser via CDP: {self.cdp_url} -> ({browser_location})')+ self.logger.debug(f'🌎 Connecting to existing chromium-based browser via CDP: {self.cdp_url} -> ({browser_location})')try:# Import cdp-use client@@ -934,7 +934,7 @@ class BrowserSession(BaseModel):await self._cdp_client_root.send.Target.setAutoAttach(params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True})- self.logger.info('✅ CDP client connected successfully')+ self.logger.debug('CDP client connected successfully')# Get browser targets to find available contexts/pagestargets = await self._cdp_client_root.send.Target.getTargets()@@ -960,7 +960,7 @@ class BrowserSession(BaseModel):if is_new_tab_page(target_url) and target_url != 'about:blank':# Redirect chrome://newtab to about:blank to avoid JS issues preventing driving chrome://newtabtarget_id = target['targetId']- self.logger.info(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')+ self.logger.debug(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')try:# Create a CDP session for redirection (minimal domains to avoid duplicate event handlers)# Only enable Page domain for navigation, avoid duplicate event handlers@@ -980,7 +980,7 @@ class BrowserSession(BaseModel):# Log summary of redirectionsif redirected_targets:- self.logger.info(f'✅ Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')+ self.logger.info(f'Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')if not page_targets:# No pages found, create a new one@@ -990,7 +990,7 @@ class BrowserSession(BaseModel):else:# Use the first available pagetarget_id = [page for page in page_targets if page.get('type') == 'page'][0]['targetId']- self.logger.info(f'📄 Using existing page with target ID: {target_id}')+ self.logger.debug(f'📄 Using existing page with target ID: {target_id}')# Store the current page target ID and add to pool# Reuse redirect session if available, otherwise create new one@@ -1024,7 +1024,7 @@ class BrowserSession(BaseModel):if page_targets:initial_url = page_targets[0].get('url', '')self.event_bus.dispatch(AgentFocusChangedEvent(target_id=page_targets[0]['targetId'], url=initial_url))- self.logger.info(f'Initial agent focus set to tab 0: {initial_url}')+ self.logger.debug(f'Initial agent focus set to tab 0: {initial_url}')except Exception as e:# Fatal error - browser is not usable without CDP connectiondiff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.pyindex 5418d06e8..2eca9a708 100644--- a/browser_use/tokens/service.py+++ b/browser_use/tokens/service.py@@ -227,7 +227,7 @@ class TokenCost:# C_CYAN = '\033[96m'# C_RESET = '\033[0m'- # cost_logger.info(f'🧠 llm : {C_CYAN}{llm.model}{C_RESET} (no usage found)')+ # cost_logger.debug(f'🧠 llm : {C_CYAN}{llm.model}{C_RESET} (no usage found)')async def _log_usage(self, model: str, usage: TokenUsageEntry) -> None:"""Log usage to the logger"""@@ -475,13 +475,13 @@ class TokenCost:completion_cost_part = ''if len(summary.by_model) > 1:- cost_logger.info(+ cost_logger.debug(f'💲 {C_BOLD}Total Usage Summary{C_RESET}: {C_BLUE}{total_tokens_fmt} tokens{C_RESET}{total_cost_part} | 'f'⬅️ {C_YELLOW}{prompt_tokens_fmt}{prompt_cost_part}{C_RESET} | ➡️ {C_GREEN}{completion_tokens_fmt}{completion_cost_part}{C_RESET}')# Log per-model breakdown- cost_logger.info(f'📊 {C_BOLD}Per-Model Usage Breakdown{C_RESET}:')+ cost_logger.debug(f'📊 {C_BOLD}Per-Model Usage Breakdown{C_RESET}:')for model, stats in summary.by_model.items():# Format tokens@@ -520,7 +520,7 @@ class TokenCost:prompt_part = f'{C_YELLOW}{model_prompt_fmt}{C_RESET}'completion_part = f'{C_GREEN}{model_completion_fmt}{C_RESET}'- cost_logger.info(+ cost_logger.debug(f' 🤖 {C_CYAN}{model}{C_RESET}: {C_BLUE}{model_total_fmt} tokens{C_RESET}{cost_part} | 'f'⬅️ {prompt_part} | ➡️ {completion_part} | 'f'📞 {stats.invocations} calls | 📈 {avg_tokens_fmt}/call'