AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill guides the integration of PostHog log capture into various application stacks. It automates the setup of OTLP exporters and provides instructions for adding structured logging alongside existing application logs. The skill ensures that log events are captured with meaningful properties, facilitating better observability and debugging within the PostHog platform.
What it does
- Detects the application platform and existing logging infrastructure.
- Configures the OpenTelemetry (OTLP) exporter for PostHog ingestion.
- Integrates PostHog log capture without replacing existing logging handlers.
- Ensures logs are captured with structured key-value properties.
- Manages environment variable configuration for API tokens and host URLs.
- Provides platform-specific guidance for SDK-native log capture.
When to use it
- After implementing new features that require observability.
- During code reviews when you identify a need for better log coverage.
- When setting up initial log export for a new project.
- When migrating from standard logging to structured, centralized log management.
Advantages
- Maintains existing logging architecture without disruptive changes.
- Supports a wide range of languages and frameworks via OpenTelemetry.
- Enables structured logging for improved search and filtering in PostHog.
- Automates the configuration of environment variables and ingestion endpoints.
Usage examples
- “Add PostHog log capture to my Node.js application.”
- The agent will analyze your package.json, install necessary OpenTelemetry dependencies, configure the OTLP exporter, and guide you through adding PostHog logging calls to your code.
- “I need to start tracking logs in my Android app using PostHog.”
- The agent will verify your Android SDK setup, configure the PostHogAndroidConfig for logs, and show you how to use PostHog.logger to capture structured events.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/posthog/instrument-logs/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-logs.zip -d .agents/skills
Documentation by PostHog
Add PostHog log capture
Use this skill to add PostHog log capture for new or changed code. Use it after implementing features or reviewing PRs to ensure meaningful log events are captured with structured properties. If PostHog log export is not yet configured, this skill also covers initial OTLP exporter setup. Supports any platform or language.
Supported platforms: Next.js, Node.js, Python, Go, Java, Datadog, Android, React Native, iOS, and any language via OpenTelemetry.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Detect the language, framework, and existing logging setup.
Look for dependency files and project files (package.json, Podfile, Package.swift, requirements.txt, go.mod, pom.xml, etc.).
Look for log libraries (winston, pino, logging module, logrus, log4j, serilog, os_log, Logger, etc.).
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, Podfile.lock, Package.resolved, etc.) to determine the package manager.
Check for existing PostHog log export setup. If the OTLP exporter is already configured, skip to STEP 5 to add log capture for new code.
STEP 2: Research log capture. (Skip if PostHog log export is already configured.) 2.1. Find the reference file below that matches the detected platform — it is the source of truth for OTLP exporter configuration and integration with existing logging. Read it now. 2.2. If no reference matches, use the "Other Languages" reference as a fallback — it covers the generic OpenTelemetry approach.
STEP 3: Install dependencies. (Skip if PostHog log export is already configured.)
Install the OpenTelemetry SDK and OTLP exporter packages for the detected platform.
Do not manually edit dependency files — use the package manager's install command.
STEP 4: Configure the OTLP exporter. (Skip if PostHog log export is already configured.)
PostHog logs use the OpenTelemetry protocol. Set up an OTLP exporter pointed at PostHog's ingest endpoint.
For SDK-native log support such as Android, React Native, and iOS, follow the platform reference instead of adding a separate OTLP exporter.
Follow the platform-specific reference for the exact configuration.
STEP 5: Integrate with existing logging.
Add the PostHog log exporter alongside existing logging. Don't replace existing log handlers or outputs.
Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.
You must read a file immediately before attempting to write it.
STEP 6: Add structured properties.
Ensure logs include structured key-value properties for filtering and search in PostHog.
Prefer structured log formats with key-value properties over plain text messages.
STEP 7: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.For the OpenTelemetry endpoint, use
https://us.i.posthog.com/v1(US) orhttps://eu.i.posthog.com/v1(EU), matching the region determined above.Write these values to the appropriate env file using the framework's naming convention.
Reference these environment variables in code instead of hardcoding them.
Reference files
references/nextjs.md- Next.js logs installationreferences/nodejs.md- Node.js logs installationreferences/python.md- Python logs installationreferences/go.md- Go logs installationreferences/java.md- Java logs installationreferences/datadog.md- Datadog logs installationreferences/android.md- Android logs installationreferences/react-native.md- React native logs installationreferences/ios.md- Ios logs installationreferences/flutter.md- Flutter logs installationreferences/other.md- Other languages logs installationreferences/start-here.md- Getting started with logsreferences/search.md- Search logsreferences/best-practices.md- Logging best practicesreferences/troubleshooting.md- Logs troubleshootingreferences/link-session-replay.md- Link session replayreferences/mcp.md- Use logs over PostHog mcpreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each platform reference contains specific OTLP configuration, SDK setup, and integration patterns. Find the one matching the user's stack.
Key principles
Environment variables: Always use environment variables for PostHog keys and OpenTelemetry endpoints. Never hardcode them.
Minimal changes: Add log export alongside existing logging. Don't replace or restructure existing logging code.
OpenTelemetry: PostHog logs use the OpenTelemetry protocol. Configure an OTLP exporter pointed at PostHog's ingest endpoint unless the platform SDK provides native log capture.
SDK-native logs: For Android, React Native, and iOS, use the SDK logger/capture APIs from the platform reference instead of adding a separate OTLP exporter.
Structured logging: Prefer structured log formats with key-value properties over plain text messages.
Files
- ATTRIBUTION.mdAdded by AutoGineer931 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md6.1 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/android.md9.2 KiB
- references/best-practices.md25.2 KiB
- references/datadog.md3.8 KiB
- references/flutter.md20.4 KiB
- references/go.md4.9 KiB
- references/ios.md11.1 KiB
- references/java.md4.7 KiB
- references/link-session-replay.md6.4 KiB
- references/mcp.md4.1 KiB
- references/nextjs.md6.9 KiB
- references/nodejs.md4.8 KiB
- references/other.md3.5 KiB
- references/python.md4.7 KiB
- references/react-native.md10.8 KiB
- references/search.md8.0 KiB
- references/start-here.md10.2 KiB
- references/troubleshooting.md6.5 KiB
references/flutter.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Flutter Logs installation
Canonical URL: https://posthog.com/docs/logs/installation/flutter
Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use
https://eu.posthog.cominstead ofhttps://us.posthog.comorhttps://app.posthog.com(app host for links).
On this page
Install posthog_flutter
Configure logs in your PostHogConfig
Capture logs
Test your setup
Tune buffering, rate cap, and resource attributes
Filter or redact with beforeSend
Next steps
The PostHog Flutter SDK has built-in support for capturing structured Logs from your Flutter app across mobile and web. The SDK handles the OTLP encoding, batching, and flushing — and on mobile, on-disk persistence across app restarts and app-lifecycle integration (web buffers in memory via posthog-js). You just call Posthog().captureLog(...) or Posthog().logger.{trace,debug,info,warn,error,fatal}(...).
Manual capture only. Logs are emitted by your code. The SDK does not autocapture system log streams (
debugPrint, ordart:developer'slog).
Minimum version:
posthog_flutter5.27.0or later (the release that adds Logs support). On mobile it pulls inposthog-android3.48.0or later automatically.
1
Install posthog_flutter
Required
If you haven't installed
posthog_flutteryet, follow the steps below. For full details, see the Flutter SDK guide.CocoaPods is becoming read-only. CocoaPods has announced the following schedule for its public specs repository:
November 2–6, 2026: A read-only dry run will prevent us from publishing new PostHog iOS SDK versions to CocoaPods.
December 2, 2026 onward: The repository will be permanently read-only. New PostHog iOS SDK versions will only be available through Swift Package Manager (SPM).
Existing native SDK versions will remain available through CocoaPods. To keep receiving native SDK updates on iOS and macOS, migrate your Flutter app to SPM. The
posthog_flutterpackage supports SPM, and Flutter 3.44 and later enable it by default. On earlier Flutter versions that support SPM, or if you disabled it, runflutter config --enable-swift-package-manager, then rebuild your app. Follow Flutter's SPM migration guide for project setup and troubleshooting.This change does not affect
posthog_flutterreleases on pub.dev, Android, or web.PostHog is available for install via Pub.
Configuration
Set your PostHog project token and enable automatic event tracking if you want the library to capture lifecycle events for you.
Remember that the application lifecycle events won't have any special context set for you by the time it is initialized. If you are using a self-hosted instance of PostHog you will need to have the public hostname or IP for your instance as well.
To start, add
posthog_flutterto yourpubspec.yaml:pubspec.yaml
# rest of your code dependencies: flutter: sdk: flutter posthog_flutter: ^5.26.0 # rest of your codeThen complete the setup for each platform:
For Session Replay and Surveys, you must set up the SDK manually by disabling the
com.posthog.posthog.AUTO_INITmode.Android setup
There are 2 ways of initializing the SDK, automatically and manually.
Automatically:
Add your PostHog configuration to your
AndroidManifest.xmlfile located in theandroid/app/src/main:android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name"> <application> <!-- ... other configuration ... --> <meta-data android:name="com.posthog.posthog.PROJECT_TOKEN" android:value="<ph_project_token>" /> <meta-data android:name="com.posthog.posthog.POSTHOG_HOST" android:value="https://us.i.posthog.com" /> <!-- usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' --> <!-- com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS is enabled by default since version 5.23.0 (previously named TRACK_APPLICATION_LIFECYCLE_EVENTS, which still works as an alias) --> <meta-data android:name="com.posthog.posthog.DEBUG" android:value="true" /> </application> </manifest>Or manually (more control and more configurations available):
Add your PostHog configuration to your
AndroidManifest.xmlfile located in theandroid/app/src/main:android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name"> <application> <!-- ... other configuration ... --> <meta-data android:name="com.posthog.posthog.AUTO_INIT" android:value="false" /> </application> </manifest>In both cases, you'll also need to update the minimum Android SDK version to
23inandroid/app/build.gradle:android/app/build.gradle
// rest of your config defaultConfig { minSdkVersion 23 // rest of your config } // rest of your configiOS setup
There are 2 ways of initializing the SDK, automatically and manually.
The SDK supports both CocoaPods and Swift Package Manager (SPM). Flutter 3.44 and later enable SPM by default. On earlier versions, or if you disabled SPM, enable it with
flutter config --enable-swift-package-manager.Automatically:
Add your PostHog configuration to the
Info.plistfile located in theios/Runnerdirectory:ios/Runner/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <!-- rest of your configuration --> <key>com.posthog.posthog.PROJECT_TOKEN</key> <string><ph_project_token></string> <key>com.posthog.posthog.POSTHOG_HOST</key> <string>https://us.i.posthog.com</string> <!-- com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS is enabled by default since version 5.23.0 --> <key>com.posthog.posthog.DEBUG</key> <true/> </dict> </plist>Or manually (more control and more configurations available):
Add your PostHog configuration to the
Info.plistfile located in theios/Runnerdirectory:ios/Runner/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <!-- rest of your configuration --> <key>com.posthog.posthog.AUTO_INIT</key> <false/> </dict> </plist>In both cases, you'll need to set the minimum platform version to iOS 13.0.
For CocoaPods projects, set it in your
Podfile:ios/Podfile
platform :ios, '13.0' # rest of your configFor Swift Package Manager projects without a
Podfile, set the Minimum Deployments version to iOS 13.0 for theRunnertarget in Xcode (Runner > General > Minimum Deployments). After you change Minimum Deployments, regenerate the iOS project's configuration files:flutter build ios --config-onlyDart setup (For manual step only)
If you followed the automatic SDK setup, then there's no more configuration needed in Dart.
If you followed the manual SDK setup:
import 'package:flutter/material.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; Future<void> main() async { // init WidgetsFlutterBinding if not yet WidgetsFlutterBinding.ensureInitialized(); final config = PostHogConfig('<ph_project_token>'); config.debug = true; // captureApplicationLifecycleEvents is enabled by default since version 5.23.0 config.host = 'https://us.i.posthog.com'; await Posthog().setup(config); runApp(MyApp()); }Web setup
If your project has a
web/directory, this step is required.Posthog().setup()is a no-op on web, so a web build without the snippet below captures nothing.Add your
Web snippet(which you can find in your project settings) in the<header>of yourweb/index.htmlfile. Write your project token into the snippet as a literal string. It's public, the same token ships to every visitor, and it needs no build-time or deploy-time injection:web/index.html
<!DOCTYPE html> <html> <head> <!-- ... other head elements ... --> <script async> !(function (t, e) { var o, n, p, r; e.__SV || ((window.posthog = e), (e._i = []), (e.init = function (i, s, a) { function g(t, e) { var o = e.split("."); (2 == o.length && ((t = t[o[0]]), (e = o[1])), (t[e] = function () { t.push([e].concat(Array.prototype.slice.call(arguments, 0))); })); } (((p = t.createElement("script")).type = "text/javascript"), (p.crossOrigin = "anonymous"), (p.async = !0), (p.src = s.api_host + "/static/array.js"), (r = t.getElementsByTagName("script")[0]).parentNode.insertBefore(p, r)); var u = e; for ( void 0 !== a ? (u = e[a] = []) : (a = "posthog"), u.people = u.people || [], Object.defineProperty(u, "toString", { configurable: !0, enumerable: !0, writable: !0, value: function (t) { var e = "posthog"; return ("posthog" !== a && (e += "." + a), t || (e += " (stub)"), e); }, }), Object.defineProperty(u.people, "toString", { configurable: !0, enumerable: !0, writable: !0, value: function () { return u.toString(1) + ".people (stub)"; }, }), o = "capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagResult reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".split( " ", ), n = 0; n < o.length; n++ ) g(u, o[n]); e._i.push([i, s, a]); }), (e.__SV = 1)); })(document, window.posthog || []); posthog.init("<ph_project_token>", { api_host: "https://us.i.posthog.com", // 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' defaults: "2026-08-30", }); </script> </head> <!-- other elements --> </html>For more information please check: /docs/libraries/js
2
Configure logs in your PostHogConfig
Required
Configure Logs through
config.logsConfigbefore callingPosthog().setup(...). All fields are optional; unset fields fall back to the native defaults, which are tuned for mobile (cellular bandwidth, battery, app lifecycle).final config = PostHogConfig('<ph_project_token>'); config.host = 'https://us.i.posthog.com'; config.logsConfig.serviceName = 'my-app'; // OTLP service.name – shown in the Logs UI config.logsConfig.environment = 'production'; // OTLP deployment.environment config.logsConfig.serviceVersion = '1.2.3'; // OTLP service.version await Posthog().setup(config);These resource attributes are captured at
setup(...)and apply to every batch.Web behavior. On Flutter Web, the SDK attaches to an already-initialized
posthog-jsinstance, soconfig.logsConfigis not applied on web. Configure your log options in theposthog.init({...})call in yourweb/index.htmlinstead.captureLogandloggerstill work on web (they are forwarded toposthog-js), andbeforeSendstill runs (in Dart) on web. Web also requires a recentposthog-jsbuild that exposescaptureLog.For example, set the same service identity on the
posthog-jssnippet inweb/index.html:<script> posthog.init('<ph_project_token>', { api_host: 'https://us.i.posthog.com', logs: { serviceName: 'my-app', environment: 'production', serviceVersion: '1.2.3', }, }) </script>See the JavaScript Logs installation guide for the full
posthog-jslogs config.3
Capture logs
Required
Use
Posthog().loggerfor the per-level convenience API, orPosthog().captureLogfor full control over level, attributes, and trace context.import 'package:posthog_flutter/posthog_flutter.dart'; // Per-level convenience methods Posthog().logger.info('checkout completed', {'order_id': 'ord_789', 'amount_cents': 4999}); Posthog().logger.warn('payment retry', {'attempt': 2}); Posthog().logger.error('payment failed', {'code': 'E001'}); // Lower-level API for custom severity / trace context Posthog().captureLog( body: 'checkout failed', level: PostHogLogSeverity.error, attributes: {'order_id': 'ord_789', 'step': 'auth'}, traceId: '4bf92f3577b34da6a3ce929d0e0e4736', // optional W3C trace context (32 hex chars) spanId: '00f067aa0ba902b7', // optional W3C span (16 hex chars) traceFlags: 1, );The per-level facade methods are
trace,debug,info,warn,error, andfatal, each taking aString bodyand an optionalMap<String, Object>of attributes. Available severity levels forcaptureLogarePostHogLogSeverity.trace,.debug,.info,.warn,.error, and.fatal.The optional W3C trace fields (
traceId,spanId,traceFlags) are available oncaptureLogonly, not on theloggerfacade.Records are buffered, batched, persisted to disk, and flushed automatically – every 30 seconds, when the buffer hits the threshold, when the app moves to the background, or on
Posthog().flush().flush()drains events, Session Replay, and Logs together.Each record is automatically tagged with the current distinct ID, session ID, active feature flags, and (on mobile) the current screen and app foreground/background state at the moment of capture. On web,
url.fullis tagged instead of screen name and app state.4
Test your setup
Recommended
Capture a test log from your app:
Posthog().logger.info('hello from Flutter'); Posthog().flush();Open the PostHog Logs UI.
Filter by
service.name = 'my-app'(or whatever value you set above).
You should see your record arrive within a few seconds.
5
Tune buffering, rate cap, and resource attributes
Optional
The
logsConfighas knobs for high-volume apps:final config = PostHogConfig('<ph_project_token>'); config.logsConfig.serviceName = 'my-app'; config.logsConfig.flushInterval = Duration(seconds: 5); // default 30s config.logsConfig.maxBufferSize = 200; // default 1000 config.logsConfig.maxBatchSize = 50; // default 50 config.logsConfig.flushAt = 20; // default 20 config.logsConfig.rateCapMaxLogs = 5000; // default 500 config.logsConfig.rateCapWindow = Duration(seconds: 60); // default 10s config.logsConfig.resourceAttributes = {'host.name': 'device-01'}; await Posthog().setup(config);Full configuration reference:
Field Default What it does serviceNameapp bundle id (iOS) / app namespace (Android) OTLP service.nameresource attributeserviceVersionapp version OTLP service.versionresource attributeenvironmentnone OTLP deployment.environmentresource attributeresourceAttributes{}Extra OTLP resource attributes flushInterval30sPeriodic flush interval flushAt20Buffer threshold that triggers an automatic flush maxBatchSize50Max records per outbound POST maxBufferSize1000Max records held on disk before FIFO eviction rateCapMaxLogs500Max records per rateCapWindow. Set to0to disable.rateCapWindow10sRate-cap window length Defaults are tuned for cellular-aware mobile apps. Raise
rateCapMaxLogsandmaxBufferSizefor high-volume scenarios.On web, these fields are not applied – configure them in your
posthog.init({...})call inweb/index.htmlinstead.6
Filter or redact with beforeSend
Optional
Use
config.logsConfig.beforeSendfor redaction, sampling, or filtering by level. It is aList<BeforeSendLogCallback>, where each callback is aFutureOr<PostHogLogRecord?> Function(PostHogLogRecord). Callbacks run in Dart on all platforms (including web), evaluated left-to-right. Each callback receives a mutablePostHogLogRecord(with mutablebody,level, andattributes) and returns either the (possibly mutated) record ornullto drop it. Callbacks can be synchronous or asynchronous.config.logsConfig.beforeSend = [ (record) { // Drop debug logs in production if (record.level == PostHogLogSeverity.debug) return null; // Redact a sensitive attribute record.attributes?.remove('password'); return record; }, // Compose a chain – callbacks run left-to-right (record) => record.body.contains('secret') ? null : record, ];Returning
nullfrom any callback short-circuits and drops the record. Settingrecord.bodyto an empty or whitespace-only string also drops the record. A callback that throws is logged and the record is dropped (fail-closed).Next steps
Checkpoint
What you can do with your logs
Action Description Why you need logs What logs show you that nothing else does Search logs Use the search interface to find specific log entries Filter by level Filter by INFO,WARN,ERROR, etc.Link session replay Connect logs to users and session replays by passing posthogDistinctIdandsessionIdLink logs to a person Surface every log emitted on behalf of a user on their PostHog person profile Logging best practices Learn what to log, how to structure logs, and patterns that make logs useful in production
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-logs · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-logs.zip