【发布时间】:2019-09-08 01:07:04
【问题描述】:
我想使用日志将信息(当前相同的信息)记录到控制台和文件中。
但是,我看到控制台打印出多余的不需要的信息。
我想在控制台和文件中都获得以下输出:
INFO - thisuser executed the pipeline at 2019-04-17 13:44:50,626
default log message
other default log message
INFO - pipeline execution completed at 2019-04-17 13:44:50,627
INFO - total time elapsed: 100.4 minutes
我在文件中得到了预期的输出,但控制台输出以下内容:
INFO:start_log:thisuser
INFO - thisuser executed the pipeline at 2019-04-17 13:44:50,626
INFO:root:default log message
default log message
INFO:root:other default log message
other default log message
INFO:end_log:-
INFO - pipeline execution completed at 2019-04-17 13:44:50,627
INFO:duration_log:100.4
INFO - total time elapsed: 100.4 minutes
我想删除打印到控制台的额外信息(上面的奇数行)。任何帮助将不胜感激!
下面是我正在运行的代码:
import logging
import getpass
class DispatchingFormatter:
def __init__(self, formatters, default_formatter):
self._formatters = formatters
self._default_formatter = default_formatter
def format(self, record):
formatter = self._formatters.get(record.name, self._default_formatter)
return formatter.format(record)
logging.basicConfig(level=logging.INFO)
formatter = DispatchingFormatter({
'start_log': logging.Formatter('%(levelname)s - %(message)s executed the pipeline at %(asctime)s'),
'end_log': logging.Formatter('%(levelname)s - pipeline execution completed at %(asctime)s'),
'duration_log': logging.Formatter('%(levelname)s - total time elapsed: %(message)s minutes')
},
logging.Formatter('%(message)s'),
)
c_handler = logging.StreamHandler()
c_handler.setFormatter(formatter)
f_handler = logging.FileHandler('log.txt')
f_handler.setFormatter(formatter)
logging.getLogger().addHandler(c_handler)
logging.getLogger().addHandler(f_handler)
logging.getLogger('start_log').info(f'{getpass.getuser()}')
logging.info('default log message')
logging.info('other default log message')
logging.getLogger('end_log').info('-')
time_elapsed = 100.4
logging.getLogger('duration_log').info(f'{time_elapsed}')
管道将打印大约 100 行信息(分析结果),我不想在任何日志级别之前添加这些信息,因此我尝试使用多个格式化程序来实现。
我知道这是一个有点老套的解决方案。如果有人对改进有一般性建议,我们也将不胜感激!
【问题讨论】:
标签: python python-3.x logging output formatter