拉丁的傳說(shuō)
2022-07-12 10:03:39
我正在嘗試構(gòu)建一個(gè)通過(guò) http 發(fā)送日志消息的自定義日志處理程序。但是,我不想添加帶有addHandler()方法的處理程序。我希望直接在日志根級(jí)別配置自定義處理程序,logging.basicConfig()特別是確保從具有不同記錄器的不同模塊觸發(fā)的所有日志消息都通過(guò) http 發(fā)送。我怎樣才能做到這一點(diǎn)?這是我當(dāng)前的代碼"""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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
您有兩種方法可以將處理程序添加到根記錄器,或者將其添加到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())
然后每當(dāng)你做一個(gè)
import logging
log = logging.getLogger(__name__)
log.info("message")
“消息”日志應(yīng)通過(guò)您的根記錄器發(fā)送。
添加回答
舉報(bào)
0/150
提交
取消