> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # PosthogExporter 將 Tracing 資料傳送至 PostHog,以進行 AI 可觀測性分析與資料分析。 ## 建構函式 ```typescript new PosthogExporter(config: PosthogExporterConfig) ``` ## `PosthogExporterConfig` ```typescript interface PosthogExporterConfig extends BaseExporterConfig { apiKey?: string host?: string flushAt?: number flushInterval?: number serverless?: boolean defaultDistinctId?: string enablePrivacyMode?: boolean } ``` 擴充 `BaseExporterConfig`,其中包括: - `logger?: IMastraLogger` - Logger 執行個體 - `logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error'` - Log 層級(預設:INFO) ## 方法 ### `exportTracingEvent` ```typescript async exportTracingEvent(event: TracingEvent): Promise ``` 將 tracing 事件匯出至 PostHog。 ### `onFeedbackEvent` ```typescript async onFeedbackEvent(event: FeedbackEvent): Promise ``` 將回饋事件匯出至 PostHog。請參閱[回饋匯出](#feedback-export)。 ### flush ```typescript async flush(): Promise ``` 強制將所有緩衝的事件 flush 至 PostHog,而不關閉 exporter。這在 serverless 環境中特別實用,可確保 runtime 結束前已匯出 span。 ### shutdown ```typescript async shutdown(): Promise ``` Flush 待處理的批次事件,並關閉 PostHog client。 ## 使用方式 ### 零設定(使用環境變數) ```typescript import { PosthogExporter } from '@mastra/posthog' // Reads from POSTHOG_API_KEY, POSTHOG_HOST const exporter = new PosthogExporter() ``` ### 明確設定 ```typescript import { PosthogExporter } from '@mastra/posthog' const exporter = new PosthogExporter({ apiKey: process.env.POSTHOG_API_KEY!, host: 'https://us.i.posthog.com', serverless: true, }) ``` ## Span 類型對應 | Mastra Span 類型 | PostHog 事件類型 | | -------------------- | ---------------- | | `MODEL_GENERATION` | `$ai_generation` | | `MODEL_STEP` | `$ai_generation` | | `MODEL_CHUNK` | `$ai_span` | | `TOOL_CALL` | `$ai_span` | | `MCP_TOOL_CALL` | `$ai_span` | | `PROVIDER_TOOL_CALL` | `$ai_span` | | `PROCESSOR_RUN` | `$ai_span` | | `AGENT_RUN` | `$ai_span` | | `WORKFLOW_RUN` | `$ai_span` | | 所有其他 Workflow | `$ai_span` | | `GENERIC` | `$ai_span` | ## 回饋匯出 使用 [`addFeedback()`](https://mastra.zisheng.pro/zh-TW/docs/observability/feedback) 記錄的回饋會以原生 `$ai_feedback` 事件匯出至 PostHog。PostHog 會在連結的 trace 上將其顯示為 **User feedback**。不需要其他設定。 ```typescript const trace = await mastra.observability.getRecordedTrace({ traceId }) await trace.addFeedback({ feedbackType: 'thumbs', value: 'down', comment: 'Wrong answer', }) ``` 回饋事件會對應至下列 PostHog 屬性: | Mastra 回饋欄位 | PostHog 屬性 | | --------------------------------- | ------------------- | | `traceId` | `$ai_trace_id` | | `comment`(沒有 comment 時則為 `value`) | `$ai_feedback_text` | | `feedbackId` | `feedback_id` | | `feedbackType` | `feedback_type` | | `value` | `feedback_value` | | `feedbackSource` | `feedback_source` | | `spanId` | `span_id` | | `sourceId` | `source_id` | | `metadata.sessionId` | `$ai_session_id` | | `metadata`(其他 key) | 自訂屬性 | 沒有 `traceId` 的回饋會被捨棄,因為 PostHog 會透過 `$ai_trace_id` 將回饋連結至 trace。事件的 distinct ID 會依序從 `feedbackUserId`、`metadata.userId`、`defaultDistinctId` 與 `anonymous` 解析。