Write log entries to Azure App Insights

 

Images by Markus Spiske from pexels.com
Images by Markus Spiske from pexels.com

As an application developer, I write log entries so that I can monitor what operations that my application is performing, what exceptions are thrown, and the debugging statements to track potential problems in the code.

When we are coding in Python, Python's logging library is used. Log entries are written to the log files in my local filesystem when I am developing the code. And, I want to write them to Azure App Insights when my application is deployed.

In this blog, we show how to write log to local filesystem (during development), and Azure App Insights (during production).

The requirement is OpenCensus. So we need to install opencensus-ext-azure.

pip install opencensus-ext-azure

I will name my Python module as example. I create a file, logger.py under example/logging folder.

import logging
import os
from example.logging.appinsight_handle import AppInsightsHandle
from example.logging.file_handle import FileHandle

class Logger:
    """This class is encapsulate logging related functions"""

    initialized = False

    @classmethod
    def init(cls):
        """Initializes logger. This initialization steps will only
        occur once.
        """
        if not Logger.initialized:
            Logger.initialized = True

            handler = (
                FileHandle.get() if is_dev_mode() else AppInsightsHandle.get()
) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(os.environ.get("LOG_LEVEL", "INFO")) root.addHandler(handler)

is_dev_mode is a function that returns True if we are in development mode. In this manner, we switch between log handle from example.logging.appinsight_handle and example.logging.file_handle. Below are the two classes.

import logging.handlers as handlers

class FileHandle:
    """This class is encapsulate file logging related functions"""

    @classmethod
    def get(cls):
        """Returns file log handler"""
        return handlers.WatchedFileHandler("example.log")

----

import os
from opencensus.ext.azure.log_exporter import AzureLogHandler
from example.errors.missing_env_parameter import MissingEnvParameter


class AppInsightsHandle:
    """This class is encapsulate app insights logging related functions"""

    @classmethod
    def get(cls):
        """Returns app insight log handler"""
        conn_str = os.getenv("APP_INSIGHT_CONNECTION_STR")
        if conn_str is None:
            raise MissingEnvParameter(
                "missing environment parameter, APP_INSIGHT_CONNECTION_STR"
            )
        return AzureLogHandler(connection_string=conn_str)


With these three Python files, we have shown how to write log entries to a log file, or Azure App Insights.



Comments

Popular posts from this blog

OpenAI: Functions Feature in 2023-07-01-preview API version

Storing embedding in Azure Database for PostgreSQL

Happy New Year, 2024 from DALL-E