Skip to content

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

pass logger object down the chain to sub-objects for re-use

Nick Sweeting023c702f4d11
diff --git a/browser_use/agent/memory/service.py b/browser_use/agent/memory/service.py
index dfb0bdbcf..4c12dc92f 100644
--- a/browser_use/agent/memory/service.py
+++ b/browser_use/agent/memory/service.py
@@ -16,8 +16,6 @@ from browser_use.agent.message_manager.service import MessageManager
from browser_use.agent.message_manager.views import ManagedMessage, MessageMetadata
from browser_use.utils import time_execution_sync
-logger = logging.getLogger(__name__)
-
class Memory:
"""
@@ -34,9 +32,11 @@ class Memory:
message_manager: MessageManager,
llm: BaseChatModel,
config: MemoryConfig | None = None,
+ logger: logging.Logger | None = None,
):
self.message_manager = message_manager
self.llm = llm
+ self.logger = logger or logging.getLogger(__name__)
# Initialize configuration with defaults based on the LLM if not provided
if config is None:
@@ -73,7 +73,7 @@ class Memory:
if self.config.embedder_provider == 'huggingface':
try:
# check that required package is installed if huggingface is used
- from sentence_transformers import SentenceTransformer # noqa: F401
+ from sentence_transformers import SentenceTransformer # noqa: F401 # type: ignore
except ImportError:
raise ImportError(
'sentence_transformers is required when enable_memory=True and embedder_provider="huggingface". Please install it with `pip install sentence-transformers`.'
@@ -90,7 +90,7 @@ class Memory:
import tempfile
import uuid
- logger.warning(
+ self.logger.warning(
f'⚠️ Mem0 SQLite migration error detected in {self.config.full_config_dict}. Using a temporary database to avoid conflicts.\n{type(e).__name__}: {e}'
)
# Create a unique temporary database path
@@ -116,7 +116,7 @@ class Memory:
Args:
current_step: The current step number of the agent
"""
- logger.debug(f'Creating procedural memory at step {current_step}')
+ self.logger.debug(f'📜 Creating procedural memory at step {current_step}')
# Get all messages
all_messages = self.message_manager.state.history.messages
@@ -135,13 +135,13 @@ class Memory:
# Need at least 2 messages to create a meaningful summary
if len(messages_to_process) <= 1:
- logger.debug('Not enough non-memory messages to summarize')
+ self.logger.debug('📜 Not enough non-memory messages to summarize')
return
# Create a procedural memory
memory_content = self._create([m.message for m in messages_to_process], current_step)
if not memory_content:
- logger.warning('Failed to create procedural memory')
+ self.logger.warning('📜 Failed to create procedural memory')
return
# Replace the processed messages with the consolidated memory
@@ -159,7 +159,7 @@ class Memory:
self.message_manager.state.history.messages = new_messages
self.message_manager.state.history.current_tokens -= removed_tokens
self.message_manager.state.history.current_tokens += memory_tokens
- logger.info(f'Messages consolidated: {len(messages_to_process)} messages converted to procedural memory')
+ self.logger.info(f'📜 History consolidated: {len(messages_to_process)} steps converted to long-term memory')
def _create(self, messages: list[BaseMessage], current_step: int) -> str | None:
parsed_messages = convert_to_openai_messages(messages)
@@ -174,5 +174,5 @@ class Memory:
return results.get('results', [])[0].get('memory')
return None
except Exception as e:
- logger.error(f'Error creating procedural memory: {e}')
+ self.logger.error(f'📜 Error creating procedural memory: {e}')
return None
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 5921af3d1..a63b023f6 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -62,8 +62,6 @@ FrameLocatorInstance = InstanceOf[PatchrightFrameLocator] | InstanceOf[Playwrigh
# Check if running in Docker
IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'
-logger = logging.getLogger('browser_use.browser.session')
-
_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times
@@ -71,7 +69,7 @@ GLOBAL_PLAYWRIGHT_API_OBJECT = None # never instantiate the playwright API obje
GLOBAL_PATCHRIGHT_API_OBJECT = None # never instantiate the patchright API object more than once per thread
-def _log_glob_warning(domain: str, glob: str):
+def _log_glob_warning(domain: str, glob: str, logger: logging.Logger):
global _GLOB_WARNING_SHOWN
if not _GLOB_WARNING_SHOWN:
logger.warning(
@@ -1842,7 +1840,7 @@ class BrowserSession(BaseModel):
if '*' in allowed_domain:
parsed_url = urlparse(url)
domain = parsed_url.hostname.lower() if parsed_url.hostname else ''
- _log_glob_warning(domain, allowed_domain)
+ _log_glob_warning(domain, allowed_domain, self.logger)
return True
except AssertionError:
# This would only happen if about:blank is passed to match_url_with_domain_pattern,
@@ -2063,7 +2061,7 @@ class BrowserSession(BaseModel):
try:
await self.remove_highlights()
- dom_service = DomService(page)
+ dom_service = DomService(page, logger=self.logger)
content = await dom_service.get_clickable_elements(
focus_element=focus_element,
viewport_expansion=self.browser_profile.viewport_expansion,
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index a38cb5fce..31b2244d9 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -16,8 +16,6 @@ from browser_use.dom.views import (
)
from browser_use.utils import time_execution_async
-logger = logging.getLogger(__name__)
-
@dataclass
class ViewportInfo:
@@ -26,9 +24,12 @@ class ViewportInfo:
class DomService:
- def __init__(self, page: 'Page'):
+ logger: logging.Logger
+
+ def __init__(self, page: 'Page', logger: logging.Logger | None = None):
self.page = page
self.xpath_cache = {}
+ self.logger = logger or logging.getLogger(__name__)
self.js_code = resources.files('browser_use.dom').joinpath('buildDomTree.js').read_text()
@@ -88,7 +89,7 @@ class DomService:
# NOTE: We execute JS code in the browser to extract important DOM information.
# The returned hash map contains information about the DOM tree and the
# relationship between the DOM elements.
- debug_mode = logger.getEffectiveLevel() == logging.DEBUG
+ debug_mode = self.logger.getEffectiveLevel() == logging.DEBUG
args = {
'doHighlightElements': highlight_elements,
'focusHighlightIndex': focus_element,
@@ -99,7 +100,7 @@ class DomService:
try:
eval_page: dict = await self.page.evaluate(self.js_code, args)
except Exception as e:
- logger.error('Error evaluating JavaScript: %s', e)
+ self.logger.error('Error evaluating JavaScript: %s', e)
raise
# Only log performance metrics in debug mode
@@ -119,7 +120,7 @@ class DomService:
# Create concise summary
url_short = self.page.url[:50] + '...' if len(self.page.url) > 50 else self.page.url
- logger.debug(
+ self.logger.debug(
'🔎 Ran buildDOMTree.js interactive element detection on: %s interactive=%d/%d\n',
url_short,
interactive_count,