Configuring log correlation in Azure Functions and application insights
I have a simple Azure Function that I’m trying to setup logging and tracing with open telemetry. I managed to get the logs to show in Application Insights, but I can’t get the traces to be correlated with the requests logs generated automatically.
This is what my code looks like:
import json
import logging
from logging import INFO, Formatter, getLogger
import azure.functions as func
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.propagate import extract
root_logger = logging.getLogger()
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
configure_azure_monitor(
logger_name="AI-simple-post",
logging_formatter=Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"),
)
logger = logging.getLogger("AI-simple-post")
def main(req: func.HttpRequest, context) -> func.HttpResponse:
logger.info("Request Correlation test")
carrier = {
"traceparent": context.trace_context.Traceparent,
"tracestate": context.trace_context.Tracestate,
}
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span(
"local_test_az_function", context=extract(carrier)
):
logger.info("Processing a request")
logger.error("Test timeout from external resource")
return func.HttpResponse(
json.dumps({"Test": "Successful"}), mimetype="application/json"
)
And here’s my host.json file:
{
"version": "2.0",
"telemetryMode": "OpenTelemetry",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
},
"logLevel": {
"default": "Warning"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
The problem is that the logs I created are not correlated to the request I get on Application Insights, instead they have a new parentId, is there any way to fix that? Or is my configuration wrong somewhere?
Read more here: Source link
