使用 logging.basicConfig() 添加自定义处理程序以记录根级别
Add custom handler to log root level with logging.basicConfig()
我正在尝试构建一个自定义日志处理程序,它通过 http 发送日志消息。但是,我不想使用 addHandler()
方法添加处理程序。我希望使用 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 [...]
您有两种方法可以将处理程序添加到根记录器,
要么将其添加到 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")
"message" 日志应该通过您的根记录器发送。
我正在尝试构建一个自定义日志处理程序,它通过 http 发送日志消息。但是,我不想使用 addHandler()
方法添加处理程序。我希望使用 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 [...]
您有两种方法可以将处理程序添加到根记录器,
要么将其添加到 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")
"message" 日志应该通过您的根记录器发送。