Я пытаюсь создать собственный обработчик журнала, который отправляет сообщения журнала через 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 [...]