Search code examples
pythonazureazure-functionsazure-application-insights

Azure Functions for python, structured logging to Application Insights?


When using Python (3.8) in Azure Functions, is there a way to send structured logs to Application Insights? More specifically, I'm trying to send custom dimensions with a log message. All I could find about logging is this very brief section.


Solution

  • Update 0127:

    It's solved as per this github issue. And here is the sample code:

    # Change Instrumentation Key and Ingestion Endpoint before you run this function app
    
    import logging
    
    import azure.functions as func
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger_opencensus = logging.getLogger('opencensus')
    logger_opencensus.addHandler(
        AzureLogHandler(
            connection_string='InstrumentationKey=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee;IngestionEndpoint=https://eastus-6.in.applicationinsights.azure.com/'
        )
    )
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
        properties = {
            'custom_dimensions': {
                'key_1': 'value_1',
                'key_2': 'value_2'
            }
        }
    
        logger_opencensus.info('logger_opencensus.info Custom Dimension', extra=properties)
        logger_opencensus.info('logger_opencensus.info Statement')
        return func.HttpResponse("OK")
    

    Please try OpenCensus Python SDK.

    The example code is in the Logs section, step 5:

    Description: You can also add custom properties to your log messages in the extra keyword argument by using the custom_dimensions field. These properties appear as key-value pairs in customDimensions in Azure Monitor.

    The sample:

    import logging
    
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger = logging.getLogger(__name__)
    # TODO: replace the all-zero GUID with your instrumentation key.
    logger.addHandler(AzureLogHandler(
        connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
    )
    
    properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
    
    # Use properties in logging statements
    logger.warning('action', extra=properties)