azure-sdk-for-python: don't know how to set operation_Id, operation_ParentId and operation_Name in logger (using configure_azure_monitor from azure.monitor.opentelemetry)

  • Package Name: azure-monitor-opentelemetry
  • Package Version: 1.23
  • Operating System: Windows and Linux:
  • Python Version: 3.11

Describe the bug When logging from an Azure Function using configure_azure_monitor to create a logger, I don’t know how to/cannot set the fields operation_Id, operation_ParentId and operation_Name that are displayed in AppInsights

To Reproduce Steps to reproduce the behavior:

  1. Create the logger
conn_string  = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
configure_azure_monitor(
    connection_string=conn_string,
    logger_name=__name__,       
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
  1. log something:
logger.info(f">>> Worker {worker_index} started >>>")

Expected behavior I would like to be able to set (when creating the logger) the context information (that is passed to an Azure Function) that contains the operation_Id, operation_name, etc. when creating the logger

Screenshots AppInsightsTraces

Additional context A sample Azure Function is depicted below. Please note that since the Azure FX is using multiprocessing the original Azure FX logger cannot be passed to the multiprocessing.Process instances as parameter (it is not pickable) . Each instance needs to create its own logger. The goal is to have a uniform logging experience in AppInsights.

import azure.functions as func

import os
import time
import logging

from azure.monitor.opentelemetry import configure_azure_monitor

app = func.FunctionApp()

@app.schedule(schedule="0 15 3 * * *", arg_name="myTimer", run_on_startup=True,
              use_monitor=False) 
def test_multiprocessor(myTimer: func.TimerRequest, context: func.Context) -> None:

    #set warning level for all azure libraries
    logger = logging.getLogger('azure')
    logger.setLevel(logging.WARNING)
    
    if myTimer.past_due:
      logging.warn(f"test_multiprocessor timer is past due")
    
    start_time = time.time()
    logging.info('test_multiprocessor started')
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    test_processor = TestMultiprocessing(logger, context)
    test_processor.process_in_parallel()
    logging.info( f"test_multiprocessor finished processing in {int(time.time()-start_time)} seconds")
        
class TestMultiprocessing:
  
  _QUEUE_END_MARKER                         = "__END_OF_QUEUE__"
  _RET_CODE_KEY                             = "ret_code"
  
  def __init__(self, logger, context, **kwargs):

    self.logger = logger
    self.number_threads = 2

  def process_job(self, worker_index):

    conn_string  = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
    configure_azure_monitor(
        connection_string=conn_string,
        logger_name=__name__,       
    )
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    
    logger.info(f">>> Worker {worker_index} started >>>")
    time.sleep(5)
    logger.info(f"<<< Worker {worker_index} finished <<<")
    
    for handler in logger.handlers:
      handler.flush()
    
    return

  def process_in_parallel(self):
    from multiprocessing import Process
  
    self.logger.info(f"Starting to process in parallel with: {self.number_threads} thread(s)")
        
    #prepare multiprocessing
    parallel_jobs_arr = []
    #prepare worker threads
    #func = process_site_inventory
    for i in range(self.number_threads):
      worker_process=Process(target=self.process_job,
        args=(
          i, 
        )
      )

      parallel_jobs_arr.append(worker_process)
      worker_process.start()

    #just to make sure
    for inventory_job in parallel_jobs_arr:
      inventory_job.join()
      
    self.logger.info(f"Finished all {self.number_threads} thread(s)")
    
    return 

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 28 (12 by maintainers)

Most upvoted comments

Hello, any progress on this?

Is this working in the meantime? We planned a while ago to switch from OpenCensus to Opentelemetry for Azure Functions but the missing OperationName in the traces blocked us.

I ended up monkey-patching the code:

import azure.monitor.opentelemetry.exporter.export.logs._exporter as xxx_logs


def patch_34655(ai_operation_name: str) -> None:
    """
    Patching the AzureMonitorLogExporter, see https://github.com/Azure/azure-sdk-for-python/issues/34655
    """
    # pylint: disable=protected-access
    orig_convert_log_to_envelope = xxx_logs._convert_log_to_envelope

    # pylint: disable=import-outside-toplevel
    from azure.monitor.opentelemetry.exporter._generated.models import TelemetryItem
    from opentelemetry.sdk._logs import LogData

    def custom_convert_log_to_envelope(log_data: LogData) -> TelemetryItem:
        """Add operation_Name to the envelope"""
        envelope = orig_convert_log_to_envelope(log_data)
        envelope.tags[ContextTagKeys.AI_OPERATION_NAME] = ai_operation_name
        return envelope

    xxx_logs._convert_log_to_envelope = custom_convert_log_to_envelope


patch_34655(ai_operation_name="fubar")