Skip to content

Commit eae8a80

Browse files
andrewmathew1Andrew MathewCopilot
authored
Added Samples for User Agents (#43561)
* added samples for user agents * Apply suggestions from code review Co-authored-by: Copilot <[email protected]> * changed test_delete_item to match async test --------- Co-authored-by: Andrew Mathew <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 4022775 commit eae8a80

File tree

3 files changed

+511
-1
lines changed

3 files changed

+511
-1
lines changed
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
# -------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See LICENSE.txt in the project root for
4+
# license information.
5+
# -------------------------------------------------------------------------
6+
import azure.cosmos.cosmos_client as cosmos_client
7+
from azure.cosmos.partition_key import PartitionKey
8+
import config
9+
10+
# ----------------------------------------------------------------------------------------------------------
11+
# Prerequisites -
12+
#
13+
# 1. An Azure Cosmos account -
14+
# https://azure.microsoft.com/documentation/articles/documentdb-create-account/
15+
#
16+
# 2. Microsoft Azure Cosmos PyPi package -
17+
# https://pypi.python.org/pypi/azure-cosmos/
18+
# ----------------------------------------------------------------------------------------------------------
19+
# Sample - demonstrates how to configure custom user agents for Azure Cosmos DB clients
20+
#
21+
# User agents help identify which application or process is making requests to Cosmos DB.
22+
# Custom user agents are particularly useful for:
23+
# - Identifying different applications using the same Cosmos DB account
24+
# - Distinguishing between different versions of your application
25+
# - Tracking requests from specific microservices or processes
26+
# - Debugging and monitoring application behavior in diagnostics
27+
# - Analyzing usage patterns across different client applications
28+
#
29+
# The user agent string appears in Cosmos DB diagnostics, logs, and monitoring tools,
30+
# making it easier to pinpoint which client instance is making specific requests.
31+
# ----------------------------------------------------------------------------------------------------------
32+
# Note -
33+
#
34+
# Running this sample will create (and delete) multiple Containers on your account.
35+
# Each time a Container is created the account will be billed for 1 hour of usage based on
36+
# the provisioned throughput (RU/s) of that account.
37+
# ----------------------------------------------------------------------------------------------------------
38+
39+
HOST = config.settings['host']
40+
MASTER_KEY = config.settings['master_key']
41+
DATABASE_ID = config.settings['database_id']
42+
CONTAINER_ID = config.settings['container_id']
43+
44+
45+
def create_client_with_default_user_agent():
46+
"""
47+
Create a Cosmos DB client with the default user agent.
48+
49+
The default user agent includes information about the SDK version and Python version.
50+
Example: "azsdk-python-cosmos/4.5.0 Python/3.11.0 (Windows-10-10.0.22621-SP0)"
51+
"""
52+
print('\n1. Creating client with default user agent')
53+
54+
client = cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY})
55+
56+
print('Client created with default user agent')
57+
print('The default user agent includes SDK version, Python version, and platform information')
58+
59+
return client
60+
61+
62+
def create_client_with_custom_user_agent():
63+
"""
64+
Create a Cosmos DB client with a custom user agent suffix.
65+
66+
The user_agent parameter appends a custom string to the default user agent,
67+
allowing you to identify your specific application or service.
68+
"""
69+
print('\n2. Creating client with custom user agent')
70+
71+
# Add a custom suffix to identify your application
72+
custom_user_agent = "MyApplication/1.0.0"
73+
74+
client = cosmos_client.CosmosClient(
75+
HOST,
76+
{'masterKey': MASTER_KEY},
77+
user_agent=custom_user_agent
78+
)
79+
80+
print(f'Client created with custom user agent: {custom_user_agent}')
81+
print('This will appear as: [default-user-agent] {}'.format(custom_user_agent))
82+
83+
return client
84+
85+
86+
def create_client_with_detailed_user_agent():
87+
"""
88+
Create a client with a detailed custom user agent including multiple identifiers.
89+
90+
You can include multiple pieces of information to make diagnostics more useful:
91+
- Application name and version
92+
- Service or microservice name
93+
- Environment (dev, staging, production)
94+
- Instance or process identifier
95+
"""
96+
print('\n3. Creating client with detailed custom user agent')
97+
98+
# Include detailed information about your application
99+
app_name = "OrderProcessingService"
100+
app_version = "2.3.1"
101+
environment = "production"
102+
instance_id = "instance-42"
103+
104+
detailed_user_agent = f"{app_name}/{app_version} env:{environment} {instance_id}"
105+
106+
client = cosmos_client.CosmosClient(
107+
HOST,
108+
{'masterKey': MASTER_KEY},
109+
user_agent=detailed_user_agent
110+
)
111+
112+
print(f'Client created with detailed user agent: {detailed_user_agent}')
113+
print('This helps identify specific instances in diagnostics and logs')
114+
115+
return client
116+
117+
118+
def create_multiple_clients_with_different_user_agents():
119+
"""
120+
Demonstrate creating multiple clients with different user agents.
121+
122+
This is useful when you have multiple services or components in your application
123+
that need to be tracked separately in diagnostics.
124+
"""
125+
print('\n4. Creating multiple clients with different user agents')
126+
127+
# Client for data ingestion service
128+
ingestion_client = cosmos_client.CosmosClient(
129+
HOST,
130+
{'masterKey': MASTER_KEY},
131+
user_agent="DataIngestionService/1.0.0"
132+
)
133+
print('Created client for data ingestion: DataIngestionService/1.0.0')
134+
135+
# Client for query service
136+
query_client = cosmos_client.CosmosClient(
137+
HOST,
138+
{'masterKey': MASTER_KEY},
139+
user_agent="QueryService/1.0.0"
140+
)
141+
print('Created client for queries: QueryService/1.0.0')
142+
143+
# Client for analytics service
144+
analytics_client = cosmos_client.CosmosClient(
145+
HOST,
146+
{'masterKey': MASTER_KEY},
147+
user_agent="AnalyticsService/1.0.0"
148+
)
149+
print('Created client for analytics: AnalyticsService/1.0.0')
150+
151+
print('\nNow you can distinguish requests from different services in diagnostics')
152+
153+
return ingestion_client, query_client, analytics_client
154+
155+
156+
def demonstrate_user_agent_in_operations(client, custom_suffix="DemoClient/1.0.0"):
157+
"""
158+
Perform operations with a custom user agent and show how it helps with diagnostics.
159+
160+
The user agent will appear in:
161+
- Azure Monitor logs
162+
- Cosmos DB diagnostic logs
163+
- Request headers sent to the service
164+
- Performance and usage analytics
165+
"""
166+
print('\n5. Demonstrating user agent in operations')
167+
168+
try:
169+
# Create database
170+
db = client.create_database_if_not_exists(id=DATABASE_ID)
171+
print(f'Database created/accessed with user agent: {custom_suffix}')
172+
173+
# Create container
174+
container = db.create_container_if_not_exists(
175+
id=CONTAINER_ID,
176+
partition_key=PartitionKey(path='/id')
177+
)
178+
print(f'Container created/accessed with user agent: {custom_suffix}')
179+
180+
# Create or upsert an item
181+
item = {
182+
'id': 'sample_item_1',
183+
'name': 'Sample Item',
184+
'description': 'Created with custom user agent'
185+
}
186+
container.upsert_item(body=item)
187+
print(f'Item created/updated with user agent: {custom_suffix}')
188+
189+
# Query items
190+
items = list(container.query_items(
191+
query="SELECT * FROM c WHERE c.id = @id",
192+
parameters=[{"name": "@id", "value": "sample_item_1"}],
193+
enable_cross_partition_query=True
194+
))
195+
print(f'Query executed with user agent: {custom_suffix}')
196+
print(f'Found {len(items)} item(s)')
197+
198+
print('\nAll these operations will show your custom user agent in diagnostics')
199+
200+
# Cleanup: Delete the item
201+
container.delete_item(item='sample_item_1', partition_key='sample_item_1')
202+
print(f'\nCleanup: Deleted sample item')
203+
204+
except Exception as e:
205+
print(f'Error during operations: {e}')
206+
207+
def demonstrate_operations_with_multiple_user_agents():
208+
"""
209+
Show how different user agents help track multiple operations.
210+
"""
211+
print('\n6. Demonstrating Multiple operations with different user agents')
212+
213+
def operation_with_user_agent(user_agent_suffix, operation_name):
214+
"""Helper function to perform operation with specific user agent."""
215+
client = cosmos_client.CosmosClient(
216+
HOST,
217+
{'masterKey': MASTER_KEY},
218+
user_agent=user_agent_suffix
219+
)
220+
db = client.create_database_if_not_exists(id=DATABASE_ID)
221+
print(f'{operation_name} completed with user agent: {user_agent_suffix}')
222+
223+
# Run multiple operations with different user agents
224+
operation_with_user_agent("Worker1/1.0.0", "Worker 1")
225+
operation_with_user_agent("Worker2/1.0.0", "Worker 2")
226+
operation_with_user_agent("Worker3/1.0.0", "Worker 3")
227+
228+
print('\nEach operation can be tracked separately in diagnostics')
229+
230+
def run_sample():
231+
"""
232+
Run all user agent examples.
233+
"""
234+
print('=' * 70)
235+
print('Azure Cosmos DB - User Agent Management Sample')
236+
print('=' * 70)
237+
238+
# Example 1: Default user agent
239+
default_client = create_client_with_default_user_agent()
240+
241+
# Example 2: Simple custom user agent
242+
custom_client = create_client_with_custom_user_agent()
243+
244+
# Example 3: Detailed user agent
245+
detailed_client = create_client_with_detailed_user_agent()
246+
247+
# Example 4: Multiple clients with different user agents
248+
ingestion_client, query_client, analytics_client = create_multiple_clients_with_different_user_agents()
249+
250+
# Example 5: Show user agent in operations
251+
demonstrate_user_agent_in_operations(detailed_client, "OrderProcessingService/2.3.1")
252+
253+
# Example 6: Operations with different user agents
254+
demonstrate_operations_with_multiple_user_agents()
255+
256+
print('\n' + '=' * 70)
257+
print('Sample completed!')
258+
print('=' * 70)
259+
260+
if __name__ == '__main__':
261+
run_sample()

0 commit comments

Comments
 (0)