我正在尝试将具有自定义维度的日志添加到应用程序洞察中的跟踪表中。我有下面的代码可以工作,但它会写入依赖项表。有任何指示如何写入跟踪和指标吗?
import azure.functions as cho
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
tt = cho.FunctionApp(http_auth_level=cho.AuthLevel.ANONYMOUS)
@tt.route(route="http_trigger")
def http_trigger(req: cho.HttpRequest) -> cho.HttpResponse:
configure_azure_monitor(connection_string="ai conn str")
ri_ch = trace.get_tracer(__name__)
with ri_ch.start_as_current_span("This is a Log") as val:
val.set_attribute("who", "rithwik")
print("Hello Rithwik Bojja, the logs are Logged")
return cho.HttpResponse("This HTTP triggered function executed successfully.",status_code=200)
我修改了您的代码以包含
logger
和 request
的属性,以添加具有自定义维度的日志,并在该功能的 Application Insights 中捕获 traces
和 metrics
。
logger.info("Hello Kamali", extra={"custom_dimension": "Kam_value"})
# Added attributes for the request
span.set_attribute("http.method", req.method)
span.set_attribute("http.route", "/http_trigger")
span.set_attribute("http.status_code", 200)
span.set_attribute("custom_dimension", "Kam_value")
span.set_attribute("who", "Kamali")
function_app.py:
import logging
import azure.functions as func
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.trace import SpanKind
from opentelemetry.sdk._logs import LoggingHandler
configure_azure_monitor(connection_string="<AppInsightsConneString>")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = LoggingHandler()
logger.addHandler(handler)
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
"""
Handles the HTTP trigger and logs telemetry to Application Insights.
"""
logger.info("Hello Kamali", extra={"custom_dimension": "Kam_value"})
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("HTTP Request", kind=SpanKind.SERVER) as span:
span.set_attribute("http.method", req.method)
span.set_attribute("http.route", "/http_trigger")
span.set_attribute("http.status_code", 200)
span.set_attribute("custom_dimension", "Kam_value")
span.set_attribute("who", "Kamali")
return func.HttpResponse(
"This HTTP triggered function executed successfully.",
status_code=200
)
主机.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": ""
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
需求.txt:
azure-functions
azure-monitor-opentelemetry
opentelemetry-api
opentelemetry-sdk
opentelemetry-semantic-conventions
查询获取痕迹:
traces
| where message == "Hello Kamali"
| project timestamp, message, customDimensions
查询获取指标:
customMetrics
| project timestamp, name, value, customDimensions
交易搜索痕迹: