我正在尝试构建一个通过 http 发送日志消息的自定义日志处理程序。但是,我不想添加带有addHandler()方法的处理程序。我希望直接在日志根级别配置自定义处理程序,logging.basicConfig()特别是确保从具有不同记录器的不同模块触发的所有日志消息都通过 http 发送。我怎样才能做到这一点?这是我当前的代码"""Entrypoint to execute python scripts."""import argparseimport loggingimport sysimport utilsfrom batch import Batchfrom data_source import DataSource# Load default logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')log = logging.getLogger(__name__)# Define custom log handlerclass 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
1 回答
青春有我
TA贡献1784条经验 获得超8个赞
您有两种方法可以将处理程序添加到根记录器,或者将其添加到basicConfig:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(),
CustomLogHandler()
]
)
或者在完成基本配置后,您可以将其添加到根记录器(以确保传播),如下所示:
root_log = logging.getLogger()
root_log.addHandler(CustomLogHandler())
然后每当你做一个
import logging
log = logging.getLogger(__name__)
log.info("message")
“消息”日志应通过您的根记录器发送。
添加回答
举报
0/150
提交
取消
