0
# Event Tracking
1
2
Event tracking functionality enables recording user actions and behaviors with comprehensive property support. Mixpanel supports both real-time event tracking and historical data import for events older than 5 days.
3
4
## Capabilities
5
6
### Basic Event Tracking
7
8
Track user events with properties and metadata. Events are recorded with automatic timestamp generation and unique insert IDs for deduplication.
9
10
```python { .api }
11
def track(distinct_id: str, event_name: str, properties: dict = None, meta: dict = None):
12
"""
13
Record an event.
14
15
Parameters:
16
- distinct_id (str): Identifies the user triggering the event
17
- event_name (str): A name describing the event
18
- properties (dict, optional): Additional data to record; keys should be strings, and values should be strings, numbers, or booleans
19
- meta (dict, optional): Overrides Mixpanel special properties
20
21
Returns:
22
None
23
"""
24
```
25
26
**Usage Example:**
27
28
```python
29
from mixpanel import Mixpanel
30
31
mp = Mixpanel("YOUR_PROJECT_TOKEN")
32
33
# Basic event tracking
34
mp.track("user_123", "page_viewed", {
35
"page": "homepage",
36
"referrer": "google.com",
37
"device": "mobile"
38
})
39
40
# Event with custom properties
41
mp.track("user_456", "purchase", {
42
"product_id": "shoe_001",
43
"price": 99.99,
44
"category": "footwear",
45
"color": "black",
46
"size": 42
47
})
48
49
# Event with meta overrides
50
mp.track("user_789", "signup", {
51
"source": "facebook_ad"
52
}, meta={
53
"time": 1609459200 # Override automatic timestamp
54
})
55
```
56
57
### Historical Data Import
58
59
Import events that occurred more than 5 days in the past. This requires API credentials and is useful for backfilling historical data or migrating from other analytics platforms.
60
61
```python { .api }
62
def import_data(api_key: str, distinct_id: str, event_name: str, timestamp: int, properties: dict = None, meta: dict = None, api_secret: str = None):
63
"""
64
Record an event that occurred more than 5 days in the past.
65
66
Parameters:
67
- api_key (str): (DEPRECATED) Your Mixpanel project's API key
68
- distinct_id (str): Identifies the user triggering the event
69
- event_name (str): A name describing the event
70
- timestamp (int): UTC seconds since epoch
71
- properties (dict, optional): Additional data to record; keys should be strings, and values should be strings, numbers, or booleans
72
- meta (dict, optional): Overrides Mixpanel special properties
73
- api_secret (str, optional): Your Mixpanel project's API secret (recommended over api_key)
74
75
Returns:
76
None
77
78
Note: The api_key parameter is deprecated. Use api_secret instead.
79
"""
80
```
81
82
**Usage Example:**
83
84
```python
85
import time
86
from datetime import datetime, timedelta
87
from mixpanel import Mixpanel
88
89
mp = Mixpanel("YOUR_PROJECT_TOKEN")
90
91
# Import historical event (more than 5 days old)
92
historical_timestamp = int((datetime.now() - timedelta(days=30)).timestamp())
93
94
mp.import_data(
95
api_key="DEPRECATED_API_KEY", # Will be removed in future versions
96
api_secret="YOUR_API_SECRET", # Recommended approach
97
distinct_id="user_123",
98
event_name="historical_purchase",
99
timestamp=historical_timestamp,
100
properties={
101
"product": "vintage_item",
102
"price": 149.99,
103
"imported": True
104
}
105
)
106
```
107
108
## Error Handling
109
110
Event tracking methods may raise `MixpanelException` when network issues occur or when the Mixpanel API returns errors.
111
112
```python
113
from mixpanel import Mixpanel, MixpanelException
114
115
mp = Mixpanel("YOUR_PROJECT_TOKEN")
116
117
try:
118
mp.track("user_123", "critical_event", {"value": 100})
119
except MixpanelException as e:
120
print(f"Failed to track event: {e}")
121
# Implement retry logic or fallback handling
122
```
123
124
## Best Practices
125
126
### Property Guidelines
127
128
- Use consistent naming conventions for event names and properties
129
- Keep property keys as strings and values as strings, numbers, or booleans
130
- Avoid deeply nested objects in properties
131
- Use descriptive event names that clearly indicate the user action
132
133
### Performance Considerations
134
135
- Consider using `BufferedConsumer` for high-volume event tracking
136
- Batch related events when possible to reduce network overhead
137
- Handle `MixpanelException` appropriately for production reliability
138
139
### Data Quality
140
141
- Ensure distinct_id values are consistent across a user's lifecycle
142
- Use proper data types for properties to enable effective analysis
143
- Include relevant context in event properties for better insights