首页 > 解决方案 > 如何从 Databricks 中的 Python 笔记本创建日志记录到 ADLS Gen2(无需安装)?

问题描述

我正在尝试在 Databricks Python 笔记本中创建一个日志记录机制。尝试使用下面的代码来实现相同的 -

import logging

def create_logger(name,log_path=None):
  
    logger = logging.getLogger(name)  
    logger.setLevel(logging.DEBUG)
    formatter    = logging.Formatter("%(asctime)s - %(levelname)-8s - %(message)s")  
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)
    
    if log_path is not None:        
        file_handler = logging.FileHandler(log_path)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        
    return logger

但是,每当我尝试调用如下函数时 -

from datetime import date, datetime
current_date = date.today()
current_timestamp = datetime.strftime(datetime.now(),"%Y%m%d%H%M%S")

name = "temp_logs"
log_path = f"abfss://{storageContainer}@{storageAccount}.dfs.core.windows.net/{target_dir}/logs/{current_date}/{name}_{current_timestamp}.txt"

logger = create_logger(name = name,log_path = log_path)

这给出了错误 -

[Errno 2] No such file or directory: /databricks/driver/abfss:/temp-ontainer@teststorage.dfs.core.windows.net/test/logs/2021-09-13/temp_logs_20210913101150.txt'

有没有办法处理这个(不使用挂载点位置)?

标签: pythonazureapache-sparkpysparkdatabricks

解决方案


我们可以尝试通过导入“BlobStorageRotatingFileHandler”来使用它,如下所示:

from azure_storage_logging.handlers import BlobStorageRotatingFileHandler

可以参考有关 azure-storage-logging 的 python 文档,因为它提供了将标准 Python 日志记录 API 的输出发送到 Microsoft Azure 存储的功能。

在此处输入图像描述

示例代码如下:

import logging
from azure_storage_logging.handlers import TableStorageHandler

# configure the handler and add it to the logger
logger = logging.getLogger('example')
handler = TableStorageHandler(account_name='mystorageaccountname',
                              account_key='mystorageaccountkey',
                              extra_properties=('%(hostname)s',
                                                '%(levelname)s'))
logger.addHandler(handler)

# output log messages
logger.info('info message')
logger.warning('warning message')
logger.error('error message')

使用上述日志记录错误信息。

对于“找不到目录”,我们需要检查路径。请查看文档


推荐阅读