PostHog Rust
The official Rust SDK for PostHog. See the PostHog docs for more information.
Features
- Event capture - Send events to PostHog for product analytics
- Feature flags - Evaluate feature flags with local or remote evaluation
- A/B testing - Support for multivariate flags and experiments
- Group analytics - Track events and flags for B2B use cases
- Async and sync clients - Choose based on your runtime
Quickstart
Add posthog-rs to your Cargo.toml.
[]
= "0.3.7"
let client = client;
// Capture events
let mut event = new;
event.insert_prop.unwrap;
event.insert_prop.unwrap;
client.capture.unwrap;
// Check feature flags
let is_enabled = client.is_feature_enabled.unwrap;
if is_enabled
Feature Flags
The SDK now supports PostHog feature flags, allowing you to control feature rollout and run A/B tests.
Basic Usage
use ;
use HashMap;
use json;
let client = client;
// Check if a feature is enabled
let is_enabled = client.is_feature_enabled.unwrap;
// Get feature flag value (boolean or variant)
match client.get_feature_flag.unwrap
With Properties
// Include person properties for flag evaluation
let mut person_props = new;
person_props.insert;
person_props.insert;
let flag = client.get_feature_flag.unwrap;
With Groups (B2B)
// For B2B apps with group-based flags
let mut groups = new;
groups.insert;
let mut group_props = new;
let mut company_props = new;
company_props.insert;
group_props.insert;
let flag = client.get_feature_flag.unwrap;
Get All Flags
// Get all feature flags for a user
let = client.get_feature_flags.unwrap;
for in feature_flags
Feature Flag Payloads
// Get additional data associated with a feature flag
let payload = client.get_feature_flag_payload.unwrap;
if let Some = payload
Error Handling
In production code, handle errors properly instead of using .unwrap():
use ;
let client = client;
// Pattern 1: Match on the error type
match client.get_feature_flag
// Pattern 2: Use unwrap_or for simple defaults
let is_enabled = client
.is_feature_enabled
.unwrap_or; // Default to disabled on error
// Pattern 3: Propagate errors with ?
Observability
The SDK uses tracing for structured logging. To see logs, add a tracing subscriber to your application:
use ;
// Initialize tracing (e.g., in main.rs)
fmt
.with_env_filter
.init;
Then set the RUST_LOG environment variable to control log levels:
# See all posthog logs
RUST_LOG=posthog_rs=debug
# See only warnings and errors
RUST_LOG=posthog_rs=warn
# See trace-level logs for flag evaluation
RUST_LOG=posthog_rs=trace
Log levels:
error: Connection failures, HTTP errorswarn: Configuration issues, failed flag fetchesinfo: Client initialization, poller start/stopdebug: Flag evaluation results, API fallback decisionstrace: Detailed cache updates, individual flag lookups
Acknowledgements
Thanks to @christos-h for building the initial version of this project.