pypi opencensus-ext-azure无法正常运行(多次发送相同的数据+不发送logging.info()跟踪信息)

问题描述 投票:0回答:1

我正在使用以下功能将一些记录标准输出从Databricks发送到Azure应用程序见解日志。

我的功能

import logging
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.trace import config_integration
from opencensus.trace.samplers import AlwaysOnSampler
from opencensus.trace.tracer import Tracer

def custom_logging_function(log_type, instrumentation_key_value, input_x):
    """
    Purpose: The standard output sent to Application insights logs
    Inputs: -
    Return: -
    """
    config_integration.trace_integrations(['logging'])
    logging.basicConfig(format='%(asctime)s traceId=%(traceId)s spanId=%(spanId)s %(message)s')
    tracer=Tracer(sampler=AlwaysOnSampler())

    logger=logging.getLogger(__name__)
    logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey={0}'.format(instrumentation_key_value)))

    if log_type=="INFO" or log_type=="SUCESSFULL":
        #[UPDATE]
        logger.setLevel(logging.INFO)
        logger.info(input_x)
        #logging.info(input_x)
    elif log_type=="ERROR":
        #[UPDATE]
        logger.setLevel(logging.ERROR)
        logger.exception(input_x)
        #logging.exception(input_x)
    else:
        logger.warning(input_x)

[更新]通过将日志记录级别设置为INFO,ERROR,可以记录不同类型的跟踪。

尽管此函数正确执行,但由于以下两个原因而出错:

原因1当我要打印logger.info()消息时,它未在应用程序见解中成功记录。出于无法解释的原因,只有logger.warning()消息已成功发送到“应用程序见解”日志。例如,

custom_logging_function("INFO", instrumentation_key_value, "INFO: {0} chronical dates in the specified time-frame have been created!".format(len(date_list)))

# Uses the logger.info() based on my function!

输出enter image description here

这永远不会被记录。但是只记录以下内容,

custom_logging_function("WARNING", instrumentation_key_value, "INFO: {0} chronical dates in the specified time-frame have been created!".format(len(date_list)))

# Uses the logger.warning() based on my function!

输出enter image description here

原因1已由我解决。请检查我的功能编辑

------------------------------------------------ ------------------------

原因2

同一条消息被记录多次,而不是仅记录一次。一些代码可以解释相同的问题,

# Set keyword parameters
time_scale=12
time_frame_repetition=1
timestamp_snapshot=datetime.utcnow()

round_up = math.ceil(time_frame_repetition*365/time_scale)
day_list = [(timestamp_snapshot - timedelta(days=x)).strftime("%d") for x in range(round_up)]
month_list = [(timestamp_snapshot - timedelta(days=x)).strftime("%m") for x in range(round_up)]
year_list = [(timestamp_snapshot - timedelta(days=x)).strftime("%Y") for x in range(round_up)]

date_list=[[day_list[i], month_list[i], year_list[i]] for i in range(0, len(day_list))]

custom_logging_function("INFO", instrumentation_key_value, "INFO: {0} chronical dates in the specified time-frame have been created!".format(len(date_list))) #the function already written in the start of my post.

以上代码片段的输出在“应用程序见解”中记录了1次以上,而我试图找出原因。

应用程序见解中的输出日志

enter image description here

您可以从查询的输出中看到,同一行被多次记录。

自第一个问题解决以来,您对第二个问题有何建议?


[[更新]基于@Izchen在下面提供的答案

def instantiate_logger(instrumentation_key_value):
    config_integration.trace_integrations(['logging'])
    logging.basicConfig(format='%(asctime)s traceId=%(traceId)s spanId=%(spanId)s %(message)s')
    tracer=Tracer(sampler=AlwaysOnSampler())

    logger=logging.getLogger(__name__)

    return logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey={0}'.format(instrumentation_key_value)))

logging_instance=instantiate_logger()

def custom_logging_function(logging_instance, disable_logging, log_type, input_x, *arguments):
    """
    Purpose: The standard output sent to Application insights logs
    Inputs: -
    Return: The logger object.
    """
    if disable_logging==0:

        if log_type=="INFO" or log_type=="SUCCESSFUL":
            logging_instance.setLevel(logging.INFO)
            logging_instance.info(input_x)
            print(input_x, *arguments)

        elif log_type=="ERROR":
            logging_instance.setLevel(logging.ERROR)
            logging_instance.exception(input_x)
            print(input_x, *arguments)

        else:
            logging_instance.warning(input_x)
            print(input_x, *arguments)

    else:
        print(input_x, *arguments)
python azure logging azure-application-insights
1个回答
0
投票

由于原因2:

您是否正在Databricks笔记本中运行Python文件?笔记本将保留所有实例化对象的状态(包括使用的Python记录器)。在用户在笔记本中多次运行代码之前,我们会遇到重复的日志条目,因为每次再次执行代码时,AzureLogHandler都会作为处理程序添加到根记录器中。以正常的Python模块运行不会导致此行为,因为在后续运行中不会保持状态。

如果您不使用笔记本,那么问题似乎出在多次添加AzureLogHandler上。您的Databricks管道中是否存在多个执行相同逻辑的工作程序?

© www.soinside.com 2019 - 2024. All rights reserved.