-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlogging_sample.py
More file actions
52 lines (43 loc) · 1.41 KB
/
logging_sample.py
File metadata and controls
52 lines (43 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
from logging import getLogger, DEBUG
from microsoft.opentelemetry import use_microsoft_opentelemetry
# Connection string can also be passed directly:
# azure_monitor_connection_string="InstrumentationKey=..."
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string=os.environ.get("APPLICATIONINSIGHTS_CONNECTION_STRING", ""),
logger_name="my_app",
)
logger = getLogger("my_app")
logger.setLevel(DEBUG)
# Basic log levels — all of these will be exported as trace telemetry
logger.debug("Debug-level detail for troubleshooting")
logger.info("Application started successfully")
logger.warning("Cache miss for key 'user-session-42'")
logger.error("Failed to connect to database after 3 retries")
# Structured logging with extra attributes
logger.info(
"User login",
extra={
"user.id": "user-789",
"auth.method": "oauth2",
},
)
# Logging an exception — the traceback is captured automatically
try:
result = 1 / 0
except ZeroDivisionError:
logger.exception("Math error during calculation")
# Custom event via the microsoft.custom_event.name attribute
logger.info(
"Order placed",
extra={
"microsoft.custom_event.name": "OrderPlaced",
"order.id": "ORD-001",
"order.total": 99.99,
},
)
print("Log records sent. Waiting for export...")
input()