python - python - 添加自定义处理程序以使用root级别记录logging.basicConfig()

我试图构建一个自定义日志处理程序,它通过http发送日志消息,但我不想使用addHandler()方法添加处理程序,我希望在日志root级别直接配置自定义处理程序,使用logging.basicConfig(),确保通过http发送来自不同模块触发的所有日志消息,我如何实现这个?

这是我现在的代码


"""Entrypoint to execute python scripts."""


import argparse


import logging


import sys


import utils


from batch import Batch


from data_source import DataSource



# Load default logging configuration


logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


log = logging.getLogger(__name__)



# Define custom log handler


class CustomLogHandler(logging.Handler):


"""Custom logs handler to send log messages to GraphQL API."""



 def __init__(self, authorization: str, batch_id: int):


 logging.Handler.__init__(self)


 self.authorization = authorization


 self.batch_id = str(batch_id)



 def emit(self, log_record):


 file_name = log_record.name


 log_level = log_record.levelname


 log_message = self.format(log_record)



 # Do stuff here...


 utils.execute_graphql_request(self.authorization, mutation)



if __name__ == '__main__':


 parser = argparse.ArgumentParser(description='Entry point to execute data quality scripts.')


 parser.add_argument('authorization', type=str, help='Authentication token of the user')


 parser.add_argument('method', type=str, help='Method to be executed: execute_batch, test_data_source')


 parser.add_argument('id', type=int, help='Id of the object on which to execute the method.')


 arguments = parser.parse_args()



 authorization = arguments.authorization


 method = arguments.method



 if method == 'execute_batch':


 batch_id = arguments.id



 # Overwrite log root basic config to send logs to GraphQL API when executing a batch


 logging.basicConfig(


 level=logging.INFO,


 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',


 handlers=[logging.StreamHandler(), CustomLogHandler(authorization, batch_id)])



 batch = Batch()


 batch.execute(authorization, batch_id)



 elif [...]



时间: 原作者:

有两种方法可以将处理程序添加到root logger,将它添加到basicConfig:


 logging.basicConfig(


 level=logging.INFO,


 format="%(asctime)s [%(levelname)s] %(message)s",


 handlers=[


 logging.StreamHandler(),


 CustomLogHandler()


 ]


 )



或者在基本配置完成后,你可以将它添加到root logger ,如下所示:


root_log = logging.getLogger()


root_log.addHandler(CustomLogHandler())



当你做一个


import logging



log = logging.getLogger(__name__)


log.info("message")



日志应该可以通过root logger发送了。

原作者:
...