Skip to content

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

Update info logger to debug and clean up logs

Magnus Müller13dce77c98d9
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 8da711911..c3d456e32 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -507,7 +507,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
for file_path in new_files:
self.logger.info(f'📄 New file available: {file_path}')
else:
- self.logger.info(f'📁 No new downloads detected (tracking {len(current_files)} files)')
+ self.logger.debug(f'📁 No new downloads detected (tracking {len(current_files)} files)')
def _set_file_system(self, file_system_path: str | None = None) -> None:
# Check for conflicting parameters
@@ -524,7 +524,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.file_system = FileSystem.from_state(self.state.file_system_state)
# The parent directory of base_dir is the original file_system_path
self.file_system_path = str(self.file_system.base_dir)
- logger.info(f'💾 File system restored from state to: {self.file_system_path}')
+ logger.debug(f'💾 File system restored from state to: {self.file_system_path}')
return
except Exception as e:
logger.error(f'💾 Failed to restore file system from state: {e}')
@@ -898,7 +898,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
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.'
- self.logger.info('Last step finishing up')
+ self.logger.debug('Last step finishing up')
self._message_manager._add_context_message(UserMessage(content=msg))
self.AgentOutput = self.DoneAgentOutput
@@ -1421,7 +1421,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
except KeyboardInterrupt:
# Already handled by our signal handler, but catch any direct KeyboardInterrupt as well
- self.logger.info('Got KeyboardInterrupt during execution, returning current history')
+ self.logger.debug('Got KeyboardInterrupt during execution, returning current history')
agent_run_error = 'KeyboardInterrupt'
self.history.usage = await self.token_cost_service.get_usage_summary()
@@ -1447,7 +1447,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.logger.error(f'Failed to log telemetry event: {log_e}', exc_info=True)
else:
# ADDED: Info message when custom telemetry for SIGINT was already logged
- self.logger.info('Telemetry for force exit (SIGINT) was logged by custom exit callback.')
+ self.logger.debug('Telemetry for force exit (SIGINT) was logged by custom exit callback.')
# NOTE: CreateAgentSessionEvent and CreateAgentTaskEvent are now emitted at the START of run()
# to match backend requirements for CREATE events to be fired when entities are created,
@@ -1479,7 +1479,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Wait up to 1 second for auth to start and print URL
await asyncio.wait_for(self.cloud_sync.auth_task, timeout=1.0)
except TimeoutError:
- logger.info('Cloud authentication started - continuing in background')
+ logger.debug('Cloud authentication started - continuing in background')
except Exception as e:
logger.debug(f'Cloud authentication error: {e}')
@@ -1524,7 +1524,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# ONLY ALLOW TO CALL `done` IF IT IS A SINGLE ACTION
if action.model_dump(exclude_unset=True).get('done') is not None:
msg = f'Done action is allowed only as a single action - stopped after action {i} / {total_actions}.'
- logger.info(msg)
+ self.logger.debug(msg)
break
# DOM synchronization check - verify element indexes are still valid AFTER first action
@@ -1544,7 +1544,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
new_target_hash = new_target.parent_branch_hash() if new_target else None
if orig_target_hash != new_target_hash:
- msg = f'Element index changed after action {i} / {total_actions}, because page changed.'
+ msg = f'Page changed after action {i} / {total_actions}'
logger.info(msg)
results.append(
ActionResult(
@@ -1559,7 +1559,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
new_element_hashes = {e.parent_branch_hash() for e in new_selector_map.values()}
if check_for_new_elements and not new_element_hashes.issubset(cached_element_hashes):
# next action requires index but there are new elements on the page
- msg = f'Something new appeared after action {i} / {total_actions}, following actions are NOT executed and should be retried.'
+ msg = f'Something new appeared after action {i} / {total_actions}'
logger.info(msg)
results.append(
ActionResult(
@@ -1608,12 +1608,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):
time_elapsed = time_end - time_start
results.append(result)
- 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'
- )
+ 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:
break
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index 343fbc231..3d950ab8f 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -70,7 +70,7 @@ class AboutBlankWatchdog(BaseWatchdog):
# Use _cdp_get_all_pages for quick check without fetching titles
page_targets = await self.browser_session._cdp_get_all_pages()
if len(page_targets) <= 1:
- self.logger.info(
+ self.logger.debug(
'[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser'
)
# Create the animation tab since no tabs should remain
@@ -95,7 +95,7 @@ class AboutBlankWatchdog(BaseWatchdog):
# If no tabs exist at all, create one to keep browser alive
if len(page_targets) == 0:
# Only create a new tab if there are no tabs at all
- self.logger.info('[AboutBlankWatchdog] No tabs exist, creating new about:blank DVD screensaver tab')
+ self.logger.debug('[AboutBlankWatchdog] No tabs exist, creating new about:blank DVD screensaver tab')
navigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await navigate_event
# Show DVD screensaver on the new tab
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index 6f5372507..c0e096082 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -171,7 +171,7 @@ class CrashWatchdog(BaseWatchdog):
# Remove crashed session from pool
if session := self.browser_session._cdp_session_pool.pop(target_id, None):
await session.disconnect()
- self.logger.info(f'[CrashWatchdog] Removed crashed session from pool: {target_id}')
+ self.logger.debug(f'[CrashWatchdog] Removed crashed session from pool: {target_id}')
# Get target info
cdp_client = self.browser_session.cdp_client
@@ -330,7 +330,7 @@ class CrashWatchdog(BaseWatchdog):
if self.browser_session.agent_focus and (target_id := self.browser_session.agent_focus.target_id):
if session := self.browser_session._cdp_session_pool.pop(target_id, None):
await session.disconnect()
- self.logger.info(f'[CrashWatchdog] Removed crashed session from pool: {target_id}')
+ self.logger.debug(f'[CrashWatchdog] Removed crashed session from pool: {target_id}')
self.browser_session.agent_focus.target_id = None # type: ignore
# Check browser process if we have PID
@@ -342,7 +342,7 @@ class CrashWatchdog(BaseWatchdog):
for session in self.browser_session._cdp_session_pool.values():
await session.disconnect()
self.browser_session._cdp_session_pool.clear()
- self.logger.info('[CrashWatchdog] Cleared all sessions from pool due to browser crash')
+ self.logger.debug('[CrashWatchdog] Cleared all sessions from pool due to browser crash')
self.event_bus.dispatch(
BrowserErrorEvent(
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index 5c0e24b8b..50868f0ea 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -1828,7 +1828,7 @@ class DefaultActionWatchdog(BaseWatchdog):
if selection_result.get('success'):
msg = selection_result.get('message', f'Selected option: {target_text}')
- self.logger.info(f'✅ {msg}')
+ self.logger.debug(f'{msg}')
# Return the result as a dict
return {
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 7903a895b..209e8df48 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -162,7 +162,7 @@ class DownloadsWatchdog(BaseWatchdog):
# Register download event handlers
async def download_will_begin_handler(event: DownloadWillBeginEvent, session_id: SessionID | None):
- self.logger.info(f'[DownloadsWatchdog] Download will begin: {event}')
+ self.logger.debug(f'[DownloadsWatchdog] Download will begin: {event}')
# Create and track the task
task = asyncio.create_task(self._handle_cdp_download(event, target_id, session_id))
self._cdp_event_tasks.add(task)
@@ -174,7 +174,7 @@ class DownloadsWatchdog(BaseWatchdog):
if event.get('state') == 'completed':
file_path = event.get('filePath')
if file_path:
- self.logger.info(f'[DownloadsWatchdog] Download completed: {file_path}')
+ self.logger.debug(f'[DownloadsWatchdog] Download completed: {file_path}')
# Track the download
self._track_download(file_path)
@@ -202,7 +202,7 @@ class DownloadsWatchdog(BaseWatchdog):
path = Path(file_path)
if path.exists():
file_size = path.stat().st_size
- self.logger.info(f'[DownloadsWatchdog] Tracked download: {path.name} ({file_size} bytes)')
+ self.logger.debug(f'[DownloadsWatchdog] Tracked download: {path.name} ({file_size} bytes)')
# Dispatch download event
from browser_use.browser.events import FileDownloadedEvent
@@ -233,7 +233,7 @@ class DownloadsWatchdog(BaseWatchdog):
suggested_filename = event.get('suggestedFilename', 'download')
guid = event.get('guid', '')
- self.logger.info(f'[DownloadsWatchdog] ⬇️ File download starting: {suggested_filename} from {download_url[:100]}...')
+ self.logger.debug(f'[DownloadsWatchdog] ⬇️ File download starting: {suggested_filename} from {download_url[:100]}...')
self.logger.debug(f'[DownloadsWatchdog] Full CDP event: {event}')
# Since Browser.setDownloadBehavior is already configured, the browser will download the file
@@ -304,7 +304,7 @@ class DownloadsWatchdog(BaseWatchdog):
async with await anyio.open_file(final_path, 'wb') as f:
await f.write(file_data)
- self.logger.info(f'[DownloadsWatchdog] ✅ Downloaded and saved file: {final_path} ({file_size} bytes)')
+ self.logger.debug(f'[DownloadsWatchdog] ✅ Downloaded and saved file: {final_path} ({file_size} bytes)')
expected_path = final_path
else:
self.logger.error('[DownloadsWatchdog] ❌ No data received from fetch')
@@ -332,7 +332,7 @@ class DownloadsWatchdog(BaseWatchdog):
)
)
- self.logger.info(
+ self.logger.debug(
f'[DownloadsWatchdog] ✅ File download completed via CDP: {suggested_filename} ({file_size} bytes) saved to {expected_path}'
)
# Success - return early
@@ -342,7 +342,7 @@ class DownloadsWatchdog(BaseWatchdog):
# If we reach here, the fetch method failed, so wait for native download
# Poll the downloads directory for new files
- self.logger.info(f'[DownloadsWatchdog] Checking if browser auto-download saved the file for us: {suggested_filename}')
+ self.logger.debug(f'[DownloadsWatchdog] Checking if browser auto-download saved the file for us: {suggested_filename}')
# Get initial list of files in downloads directory
initial_files = set()
@@ -367,7 +367,9 @@ class DownloadsWatchdog(BaseWatchdog):
file_size = file_path.stat().st_size
if file_size > 4:
# Found a new download!
- self.logger.info(f'[DownloadsWatchdog] ✅ Found downloaded file: {file_path} ({file_size} bytes)')
+ self.logger.debug(
+ f'[DownloadsWatchdog] ✅ Found downloaded file: {file_path} ({file_size} bytes)'
+ )
# Track the download
self.browser_session._downloaded_files.append(str(file_path))
@@ -483,7 +485,7 @@ class DownloadsWatchdog(BaseWatchdog):
)
)
- self.logger.info(
+ self.logger.debug(
f'[DownloadsWatchdog] ✅ Download completed: {suggested_filename} ({file_size} bytes) saved to {download_path}'
)
@@ -760,7 +762,7 @@ class DownloadsWatchdog(BaseWatchdog):
# Log cache information
cache_status = 'from cache' if download_result.get('fromCache') else 'from network'
response_size = download_result.get('responseSize', 0)
- self.logger.info(
+ self.logger.debug(
f'[DownloadsWatchdog] ✅ Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}'
)
diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.py
index 38fdda3ba..c76a1b3dd 100644
--- a/browser_use/browser/local_browser_watchdog.py
+++ b/browser_use/browser/local_browser_watchdog.py
@@ -176,7 +176,7 @@ class LocalBrowserWatchdog(BaseWatchdog):
# Update profile to use temp directory
profile.user_data_dir = str(tmp_dir)
- self.logger.info(f'Retrying with temporary user_data_dir: {tmp_dir}')
+ self.logger.debug(f'Retrying with temporary user_data_dir: {tmp_dir}')
# Small delay before retry
await asyncio.sleep(0.5)
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index c40625ae3..574df8988 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -435,7 +435,7 @@ class BrowserSession(BaseModel):
)
if target.get('url') == 'about:blank' and target['targetId'] != current_target_id:
target_id = target['targetId']
- self.logger.info(f'Reusing existing about:blank tab #{target_id[-4:]}')
+ self.logger.debug(f'Reusing existing about:blank tab #{target_id[-4:]}')
break
# Create new tab if no reusable one found
@@ -446,7 +446,7 @@ class BrowserSession(BaseModel):
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:]}')
+ self.logger.debug(f'Created new tab #{target_id[-4:]}')
# Dispatch TabCreatedEvent for new tab
await self.event_bus.dispatch(TabCreatedEvent(target_id=target_id, url='about:blank'))
except Exception as e:
@@ -980,13 +980,13 @@ class BrowserSession(BaseModel):
# Log summary of redirections
if redirected_targets:
- self.logger.info(f'Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')
+ self.logger.debug(f'Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')
if not page_targets:
# No pages found, create a new one
new_target = await self._cdp_client_root.send.Target.createTarget(params={'url': 'about:blank'})
target_id = new_target['targetId']
- self.logger.info(f'📄 Created new blank page with target ID: {target_id}')
+ self.logger.debug(f'📄 Created new blank page with target ID: {target_id}')
else:
# Use the first available page
target_id = [page for page in page_targets if page.get('type') == 'page'][0]['targetId']
diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.py
index b5b04b001..6f256efce 100644
--- a/browser_use/browser/storage_state_watchdog.py
+++ b/browser_use/browser/storage_state_watchdog.py
@@ -45,7 +45,7 @@ class StorageStateWatchdog(BaseWatchdog):
async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:
"""Start monitoring when browser starts."""
- self.logger.info('[StorageStateWatchdog] 🍪 Initializing auth/cookies sync <-> with storage_state.json file')
+ self.logger.debug('[StorageStateWatchdog] 🍪 Initializing auth/cookies sync <-> with storage_state.json file')
# Start monitoring
await self._start_monitoring()
@@ -85,7 +85,7 @@ class StorageStateWatchdog(BaseWatchdog):
assert self.browser_session.cdp_client is not None
self._monitoring_task = asyncio.create_task(self._monitor_storage_changes())
- # self.logger.info('[StorageStateWatchdog] Started storage monitoring task')
+ # self.logger'[StorageStateWatchdog] Started storage monitoring task')
async def _stop_monitoring(self) -> None:
"""Stop the monitoring task."""
@@ -123,7 +123,7 @@ class StorageStateWatchdog(BaseWatchdog):
# Check if cookies have changed
if await self._have_cookies_changed():
- self.logger.info('[StorageStateWatchdog] Detected changes to sync with storage_state.json')
+ self.logger'[StorageStateWatchdog] Detected changes to sync with storage_state.json')
await self._save_storage_state()
except asyncio.CancelledError:
@@ -211,7 +211,7 @@ class StorageStateWatchdog(BaseWatchdog):
)
)
- self.logger.info(
+ self.logger
f'[StorageStateWatchdog] Saved storage state to {json_path} '
f'({len(merged_state.get("cookies", []))} cookies, '
f'{len(merged_state.get("origins", []))} origins)'
@@ -241,7 +241,7 @@ class StorageStateWatchdog(BaseWatchdog):
if 'cookies' in storage and storage['cookies']:
await self.browser_session._cdp_set_cookies(storage['cookies'])
self._last_cookie_state = storage['cookies'].copy()
- self.logger.info(f'[StorageStateWatchdog] Added {len(storage["cookies"])} cookies from storage state')
+ self.loggerf'[StorageStateWatchdog] Added {len(storage["cookies"])} cookies from storage state')
# Apply origins (localStorage/sessionStorage) if present
if 'origins' in storage and storage['origins']:
@@ -258,7 +258,7 @@ class StorageStateWatchdog(BaseWatchdog):
window.sessionStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});
"""
await self.browser_session._cdp_add_init_script(script)
- self.logger.info(
+ self.logger
f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins'
)
@@ -270,7 +270,7 @@ class StorageStateWatchdog(BaseWatchdog):
)
)
- self.logger.info(f'[StorageStateWatchdog] Loaded storage state from: {load_path}')
+ self.loggerf'[StorageStateWatchdog] Loaded storage state from: {load_path}')
except Exception as e:
self.logger.error(f'[StorageStateWatchdog] Failed to load storage state: {e}')
@@ -323,6 +323,6 @@ class StorageStateWatchdog(BaseWatchdog):
cookie_objects = [Cookie(**cookie_dict) if isinstance(cookie_dict, dict) else cookie_dict for cookie_dict in cookies]
# Set cookies using CDP
await self.browser_session._cdp_set_cookies(cookie_objects)
- self.logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')
+ self.loggerf'[StorageStateWatchdog] Added {len(cookies)} cookies')
except Exception as e:
self.logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')
diff --git a/browser_use/cli.py b/browser_use/cli.py
index 053ba7d6f..2d8fc3814 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -695,7 +695,7 @@ class BrowserUseApp(App):
# Hide intro panels if they're visible and show info panels + three-column view
if logo_panel.display:
- logging.info('Hiding intro panels and showing info panels + three-column view')
+ logging.debug('Hiding intro panels and showing info panels + three-column view')
logo_panel.display = False
links_panel.display = False
@@ -708,7 +708,7 @@ class BrowserUseApp(App):
# Start updating info panels
self.update_info_panels()
- logging.info('Info panels and three-column view should now be visible')
+ logging.debug('Info panels and three-column view should now be visible')
except Exception as e:
logging.error(f'Error in hide_intro_panels: {str(e)}')
diff --git a/browser_use/config.py b/browser_use/config.py
index 82ad3b60e..5a75e1da0 100644
--- a/browser_use/config.py
+++ b/browser_use/config.py
@@ -261,7 +261,7 @@ class DBStyleConfigJSON(BaseModel):
def create_default_config() -> DBStyleConfigJSON:
"""Create a fresh default configuration."""
- logger.info('Creating fresh default config.json')
+ logger.debug('Creating fresh default config.json')
new_config = DBStyleConfigJSON()
@@ -306,14 +306,14 @@ def load_and_migrate_config(config_path: Path) -> DBStyleConfigJSON:
return DBStyleConfigJSON(**data)
# Old format detected - delete it and create fresh config
- logger.info(f'Old config format detected at {config_path}, creating fresh config')
+ logger.debug(f'Old config format detected at {config_path}, creating fresh config')
new_config = create_default_config()
# Overwrite with new config
with open(config_path, 'w') as f:
json.dump(new_config.model_dump(), f, indent=2)
- logger.info(f'Created fresh config.json at {config_path}')
+ logger.debug(f'Created fresh config.json at {config_path}')
return new_config
except Exception as e:
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 8bef6855b..6c4504786 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -187,7 +187,7 @@ def setup_logging(stream=None, log_level=None, force_setup=False):
cdp_logger.propagate = False
logger = logging.getLogger('browser_use')
- # logger.info('BrowserUse logging setup complete with level %s', log_type)
+ # logger.debug('BrowserUse logging setup complete with level %s', log_type)
# Silence third-party loggers (but not CDP ones which we configured above)
third_party_loggers = [
diff --git a/browser_use/observability.py b/browser_use/observability.py
index 334af9fa8..737bca401 100644
--- a/browser_use/observability.py
+++ b/browser_use/observability.py
@@ -47,11 +47,11 @@ try:
from lmnr import observe as _lmnr_observe # type: ignore
if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true':
- logger.info('Lmnr is available for observability')
+ logger.debug('Lmnr is available for observability')
_LMNR_AVAILABLE = True
except ImportError:
if os.environ.get('BROWSER_USE_VERBOSE_OBSERVABILITY', 'false').lower() == 'true':
- logger.info('Lmnr is not available for observability')
+ logger.debug('Lmnr is not available for observability')
_LMNR_AVAILABLE = False
diff --git a/browser_use/telemetry/service.py b/browser_use/telemetry/service.py
index ebba180a8..2cc5bcf5d 100644
--- a/browser_use/telemetry/service.py
+++ b/browser_use/telemetry/service.py
@@ -42,9 +42,7 @@ class ProductTelemetry:
if telemetry_disabled:
self._posthog_client = None
else:
- logger.info(
- 'Anonymized telemetry enabled. See https://docs.browser-use.com/development/telemetry for more information.'
- )
+ logger.info('Using anonymized telemetry, see https://docs.browser-use.com/development/telemetry.')
self._posthog_client = Posthog(
project_api_key=self.PROJECT_API_KEY,
host=self.HOST,