diff --git a/codeflash/telemetry/posthog_cf.py b/codeflash/telemetry/posthog_cf.py index 106817771..ed166ff44 100644 --- a/codeflash/telemetry/posthog_cf.py +++ b/codeflash/telemetry/posthog_cf.py @@ -12,7 +12,7 @@ _posthog = None -def initialize_posthog(enabled: bool = True) -> None: # noqa: FBT001, FBT002 +def initialize_posthog(enabled: bool = True) -> None: """Enable or disable PostHog. :param enabled: Whether to enable PostHog. @@ -20,9 +20,16 @@ def initialize_posthog(enabled: bool = True) -> None: # noqa: FBT001, FBT002 if not enabled: return - global _posthog # noqa: PLW0603 + global _posthog, _user_id # noqa: PLW0603 + if _posthog is not None: + return # Fast re-init path + _posthog = Posthog(project_api_key="phc_aUO790jHd7z1SXwsYCz8dRApxueplZlZWeDSpKc5hol", host="https://us.posthog.com") # type: ignore[no-untyped-call] _posthog.log.setLevel(logging.CRITICAL) # Suppress PostHog logging + + # Pre-fetch user_id for this session and cache it + _user_id = get_user_id() + ph("cli-telemetry-enabled") @@ -35,12 +42,20 @@ def ph(event: str, properties: dict[str, Any] | None = None) -> None: if _posthog is None: return - properties = properties or {} - properties.update({"cli_version": __version__}) + # Build the property dict only once per call + props = {} if properties is None else dict(properties) + props["cli_version"] = __version__ - user_id = get_user_id() + # Use cached user_id if available, else fetch and memoize once per process run + global _user_id # noqa: PLW0603 + if _user_id is None: + _user_id = get_user_id() + user_id = _user_id if user_id: - _posthog.capture(distinct_id=user_id, event=event, properties=properties) # type: ignore[no-untyped-call] + _posthog.capture(distinct_id=user_id, event=event, properties=props) # type: ignore[no-untyped-call] else: logger.debug("Failed to log event to PostHog: User ID could not be retrieved.") + + +_user_id = None