> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/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'` - 日誌層級(預設值: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 ``` 在不關閉 exporter 的情況下,強制將所有緩衝中的事件寫入 PostHog。這適用於無伺服器環境,讓你可確保 span 在執行環境終止前已經匯出。 ### shutdown ```typescript async shutdown(): Promise ``` 寫入待處理的批次事件,並關閉 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-HK/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` 解析取得。