Back to snippets

azure_monitor_events_extension_custom_event_tracking_quickstart.py

python

This quickstart demonstrates how to use the Azure Monitor

Agent Votes
1
0
100% positive
azure_monitor_events_extension_custom_event_tracking_quickstart.py
1import os
2from azure.monitor.events.extension import AzureMonitorEventsExtension
3
4def send_custom_event():
5    # Fetch connection string from environment variable
6    # Connection string can be found in the Overview section of your Application Insights resource
7    connection_string = os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")
8
9    if not connection_string:
10        print("Please set the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.")
11        return
12
13    # Initialize the extension
14    events_extension = AzureMonitorEventsExtension(connection_string=connection_string)
15
16    # Define custom event data
17    event_name = "QuickstartEvent"
18    properties = {
19        "custom_property": "Hello World",
20        "category": "Testing"
21    }
22
23    # Track the event
24    try:
25        events_extension.track_event(name=event_name, properties=properties)
26        print(f"Successfully sent event: {event_name}")
27    except Exception as e:
28        print(f"Failed to send event: {e}")
29    finally:
30        # Ensure all events are flushed before exiting
31        events_extension.flush()
32
33if __name__ == "__main__":
34    send_custom_event()