Python opentelemetry events in Application Insights

88 Views Asked by At

I'm following the guides below trying to setup logging in Azure Application Insights for my django application:

https://uptrace.dev/get/instrument/opentelemetry-django.html https://uptrace.dev/opentelemetry/python-tracing.html https://opentelemetry.io/docs/languages/python/automatic/logs-example/

And have ended up with code that looks like this:

myapp/manage.py

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

    # Configure OpenTelemetry to use Azure Monitor with the specified connection string
    configure_azure_monitor(
        connection_string="InstrumentationKey=myKey;IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/",
    )

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

myapp/views.py

import logging
from opentelemetry import trace

class SomeView(LoginRequiredMixin, TemplateView):
    login_required = True
    template_name = "myapp/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        tracer = trace.get_tracer(__name__)

        with tracer.start_as_current_span("SomeView") as span:
            if span.is_recording():
                span.set_attribute("user.id", self.request.user.id)
                span.set_attribute("user.email", self.request.user.email)

                span.add_event("log", {
                    "log.severity": "info",
                    "log.message": "Mark was here.",
                    "user.id": self.request.user.id,
                    "user.email": self.request.user.email,
                })

                span.add_event("This is a span event")
                logging.getLogger().error("This is a log message")

        context['something'] = SomeThing.objects.all()
        
        return context

The good: I do get results in Application Insights.

When I look at end-to-end transaction details I see something like this, which is great.

Traces & Events
10 Traces
0 Events <- THIS IS THE ISSUE
View timeline
Filter to a specific component and call
Local time  Type    Details
1:32:52.989 PM  Request Name: GET some/path/, Successful request: true, Response time: 5.6 s, URL: https://someurl.com
1:32:53.260 PM  Trace   Message: log
1:32:53.260 PM  Trace   Message: This is a span event
1:32:53.260 PM  Trace   Severity level: Error, Message: This is a log message
1:32:53.260 PM  Internal    Name: SomeView, Type: InProc, Call status: true
1:32:53.577 PM  Trace   Severity level: Information, Message: some
1:32:53.587 PM  Trace   Severity level: Information, Message: message
1:32:53.602 PM  Trace   Severity level: Information, Message: here

However, what I can't get to occur is log an actual Event. So when I'm looking at Application Insights and I click on "Activity Log" in the menu, I nothing but a message stating "No events to display".

So, I've got traces working, but I'm unable to log "Events". Any help would be greatly appreciated.

1

There are 1 best solutions below

0
RithwikBojja On

AFAIK, this is a bug in creating events using OpenTelemetry and there is support request which I raised in Github.

As an Alternative, You can integrate code of below into your djjango views.py and manage.py:

import logging
from opencensus.ext.azure.log_exporter import AzureEventHandler


rithwik_lor = logging.getLogger(__name__)
rithwik_lor.addHandler(AzureEventHandler(connection_string='InstrumentationKey=hg65f87-u8frx;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/'))
rithwik_lor.setLevel(logging.INFO)
rithwik_lor.info('Hi Mr.Bojja, Event Created In Events')

Output:

enter image description here