将Azure函数用于Python,将结构化日志记录到应用程序洞察力?
问题描述
在Azure函数中使用Python(3.8)时,有没有办法将结构化日志发送到Application Insights?更具体地说,我正在尝试发送带有日志消息的自定义维度。我所能找到的关于日志的所有内容都是this非常简短的部分。
解决方案
更新0127:
按this github issue求解。以下是示例代码:
# 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")
请尝试OpenCensus Python SDK。
示例代码位于Logs部分,第5步:
说明:您还可以使用custom_dimensions
字段在Extra关键字参数中向日志消息添加自定义属性。这些属性在Azure监视器的CustomDimensions中显示为键-值对。
样本:
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)
相关文章