AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/EXAMPLE-django.md · 24000

how_new_feature, 'feature_config': feature_config, }

return render(request, 'core/dashboard.html', context)

@login_required def burrito_view(request): """Example page demonstrating event tracking""" count = request.session.get('burrito_count', 0)

context = {
    'burrito_count': count,
}

return render(request, 'core/burrito.html', context)

@login_required @require_POST def consider_burrito_view(request): """API endpoint for tracking burrito considerations""" count = request.session.get('burrito_count', 0) + 1 request.session['burrito_count'] = count

# PostHog: Track custom event
capture('burrito_considered', properties={
    'total_considerations': count,
})

return JsonResponse({
    'success': True,
    'count': count,
})

@login_required def profile_view(request): """Profile page with error tracking demonstration""" user_id = str(request.user.id)

# PostHog: Track profile view
capture('profile_viewed')

context = {
    'user': request.user,
}

return render(request, 'core/profile.html', context)

@login_required @require_POST def trigger_error_view(request): """API endpoint that demonstrates error tracking""" try: error_type = request.POST.get('error_type', 'generic')

    if error_type == 'value':
        raise ValueError("Invalid value provided by user")
    elif error_type == 'key':
        data = {}
        _ = data['nonexistent_key']
    else:
        raise Exception("Something went wrong!")

except Exception as e:
    # PostHog: Capture exception
    posthog.capture_exception(e)

    # PostHog: Track error trigger event
    capture('error_triggered', properties={
        'error_type': error_type,
        'error_message': str(e),
    })

    return JsonResponse({
        'success': False,
        'error': str(e),
        'message': 'Error has been captured by PostHog',
    }, status=400)

return JsonResponse({'success': True})

@login_required def group_analytics_view(request): """Example demonstrating group analytics""" user_id = str(request.user.id)

# PostHog: Identify group
posthog.group_identify(
    group_type='company',
    group_key='acme-corp',
    properties={
        'name': 'Acme Corporation',
        'plan': 'enterprise',
        'employee_count': 150,
    }
)

# PostHog: Capture event with group
capture(
    'feature_used',
    properties={
        'feature_name': 'group_analytics',
    },
    groups={
        'company': 'acme-corp',
    }
)

return JsonResponse({
    'success': True,
    'message': 'Group analytics event captured',
})

---

## manage.py

```py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()


posthog_example/init.py

# PostHog Django example project


posthog_example/asgi.py

"""
ASGI config for PostHog example project
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings')

application = get_asgi_application()


posthog_example/settings.py

"""Django settings for PostHog example project"""

import os
from pathlib import Path

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-example-key-change-in-production')

DEBUG = os.environ.get('DEBUG', 'True').lower() == 'true'

ALLOWED_HOSTS = ['localhost', '127.0.0.1']


# PostHog configuration
POSTHOG_PROJECT_TOKEN = os.environ.get('POSTHOG_PROJECT_TOKEN', '<ph_project_token>')
POSTHOG_HOST = os.environ.get('POSTHOG_HOST', 'https://us.i.posthog.com')
POSTHOG_DISABLED = os.environ.get('POSTHOG_DISABLED', 'False').lower() == 'true'


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core.apps.CoreConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'posthog.integrations.django.PosthogContextMiddleware',
]

ROOT_URLCONF = 'posthog_example.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'posthog_example.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

STATIC_URL = 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


posthog_example/urls.py

"""
URL configuration for PostHog example project
"""

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # Include the core app URLs for PostHog examples
    path('', include('core.urls')),
]


posthog_example/wsgi.py

"""
WSGI config for PostHog example project
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings')

application = get_wsgi_application()


requirements.txt

Django>=4.2,<5.0
posthog  # Always use latest version
python-dotenv>=1.0.0