Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions codeflash/telemetry/posthog_cf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,24 @@
_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.
"""
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")


Expand All @@ -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
Loading