Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.6 KB
Raw Blame
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from typing import Any, Optional

import posthoganalytics
from temporalio import activity, workflow

from posthog.temporal.common.logger import get_logger

from products.tasks.backend.models import LogLevel
from products.tasks.backend.temporal.metrics import StepTimer

logger = get_logger(__name__)


@StepTimer("agent_log")
def emit_agent_log(run_id: str, level: LogLevel, message: str) -> None:
    """Emit a console-style agent event for user-facing logs.

    On activity retries (attempt > 1), debug logs are used regardless of the log level provided to avoid duplicate user-facing messages.
    """
    from products.tasks.backend.models import TaskRun

    effective_level = level
    if activity.in_activity():
        info = activity.info()
        if info.attempt > 1:
            effective_level = "debug"

    try:
        task_run = TaskRun.objects.get(id=run_id)
        task_run.emit_console_event(effective_level, message)
    except TaskRun.DoesNotExist:
        logger.warning("TaskRun not found for emit_agent_log", run_id=run_id)
    except Exception:
        logger.exception("Failed to emit agent log", run_id=run_id)


def emit_progress(
    run_id: str,
    step: str,
    status: str,
    label: str,
    group: str,
    detail: Optional[str] = None,
) -> None:
    """Emit a structured progress event consumed by the desktop client.

    Events sharing a `group` coalesce into one collapsible card on the client;
    pick a phase id (e.g. `"setup"`, `"pr_create"`) that matches how the work
    should be presented.
    """
    from products.tasks.backend.models import TaskRun

    try:
        task_run = TaskRun.objects.get(id=run_id)
        task_run.emit_progress_event(step, status, label, group, detail)
    except TaskRun.DoesNotExist:
        logger.warning("TaskRun not found for emit_progress", run_id=run_id)
    except Exception:
        logger.exception("Failed to emit progress", run_id=run_id)


def get_bound_logger(**context: Any):
    return logger.bind(**context)


def log_with_activity_context(message: str, **extra_context: Any) -> None:
    bound_logger = logger.bind(**extra_context)

    if activity.in_activity():
        info = activity.info()
        bound_logger = bound_logger.bind(
            activity_id=info.activity_id,
            activity_type=info.activity_type,
            attempt=info.attempt,
        )

    bound_logger.info(message)


def log_with_workflow_context(message: str, **extra_context: Any) -> None:
    bound_logger = logger.bind(**extra_context)

    if workflow.in_workflow():
        info = workflow.info()
        bound_logger = bound_logger.bind(
            workflow_id=info.workflow_id,
            workflow_run_id=info.run_id,
            workflow_type=info.workflow_type,
        )

    bound_logger.info(message)


@contextmanager
def log_activity_execution(
    activity_name: str,
    distinct_id: Optional[str] = None,
    activity_failure: Callable[[], tuple[str, str] | None] | None = None,
    **context: Any,
) -> Iterator[None]:
    """Context manager for activity execution with automatic logging and analytics.

    Automatically tracks:
    - process_task_activity_started
    - process_task_activity_completed
    - process_task_activity_failed

    Usage:
        async with log_activity_execution(
            "clone_repository",
            distinct_id=f"user_{user_id}",
            task_id=task_id,
            repository=repo
        ):
            result = await do_work()
            return result
    """
    bound_logger = logger.bind(**context)

    for key in (
        "run_id",
        "task_id",
        "origin_product",
        "environment",
        "mode",
        "run_source",
        "runtime_adapter",
        "provider",
        "runtime",
        "sandbox_backend",
        "boot_path",
        "used_snapshot",
    ):
        if key in context:
            posthoganalytics.tag("run_environment" if key == "environment" else key, context[key])

    if activity.in_activity():
        info = activity.info()
        bound_logger = bound_logger.bind(
            activity_id=info.activity_id,
            activity_type=info.activity_type,
            attempt=info.attempt,
        )

    bound_logger.info(f"{activity_name} started")

    if distinct_id:
        track_event(
            "process_task_activity_started",
            distinct_id=distinct_id,
            properties={"activity_name": activity_name, **context},
        )

    try:
        yield
        failure = activity_failure() if activity_failure else None
        if failure:
            error_type, error_message = failure
            bound_logger.warning(
                f"{activity_name} completed unsuccessfully",
                error_type=error_type,
                error_message=error_message,
            )

            if distinct_id:
                track_event(
                    "process_task_activity_failed",
                    distinct_id=distinct_id,
                    properties={
                        "activity_name": activity_name,
                        "error_type": error_type,
                        "error_message": error_message[:500],
                        **context,
                    },
                )
            return

        bound_logger.info(f"{activity_name} completed successfully")

        if distinct_id:
            track_event(
                "process_task_activity_completed",
                distinct_id=distinct_id,
                properties={"activity_name": activity_name, **context},
            )
    except Exception as e:
        bound_logger.exception(
            f"{activity_name} failed",
            error_type=type(e).__name__,
            error_message=str(e),
        )

        if distinct_id:
            track_event(
                "process_task_activity_failed",
                distinct_id=distinct_id,
                properties={
                    "activity_name": activity_name,
                    "error_type": type(e).__name__,
                    "error_message": str(e)[:500],
                    **context,
                },
            )

        raise


def track_event(
    event_name: str,
    distinct_id: str,
    properties: Optional[dict[str, Any]] = None,
    groups: Optional[dict[str, str]] = None,
) -> None:
    try:
        enriched_properties = {**(properties or {})}

        if activity.in_activity():
            activity_info = activity.info()
            enriched_properties.update(
                {
                    "temporal_activity_id": activity_info.activity_id,
                    "temporal_activity_type": activity_info.activity_type,
                    "temporal_workflow_id": activity_info.workflow_id,
                    "temporal_workflow_run_id": activity_info.workflow_run_id,
                    "temporal_attempt": activity_info.attempt,
                }
            )
        elif workflow.in_workflow() and not workflow.unsafe.is_replaying():
            workflow_info = workflow.info()
            enriched_properties.update(
                {
                    "temporal_workflow_id": workflow_info.workflow_id,
                    "temporal_workflow_run_id": workflow_info.run_id,
                    "temporal_workflow_type": workflow_info.workflow_type,
                }
            )

        posthoganalytics.capture(
            distinct_id=distinct_id,
            event=event_name,
            properties=enriched_properties,
            groups=groups or {},
        )

        logger.debug(f"Tracked event: {event_name}", **enriched_properties)

    except Exception as e:
        logger.warning(f"Failed to track event {event_name}", exc_info=e)