Python可以使用不同的格式化程序将日志记录到同一文件吗

时间:2018-10-10 15:06:25

标签: python logging

我正在尝试使用两个不同的格式化程序登录到一个文件。用例是获取一个看起来像这样的文件:

+-------------------+
| Setup the servers |
+-------------------+
2018-10-10 17:24:33,891 [INFO] - func=test_01_pass:[7] - location=debug_tests.py - MSG=Doing something with servers

+---------------------------------------------------+
| Login to sdc with user: cs0008 & password: 123456 |
+---------------------------------------------------+
2018-10-10 17:24:33,892 [INFO] - func=test_01_pass:[11] - location=debug_tests.py - MSG=Doing something to login

+----------------+
| Create Service |
+----------------+
2018-10-10 17:24:33,892 [INFO] - func=test_01_pass:[14] - location=debug_tests.py - MSG=Doing create service flow

+----------------------+
| Teardown the servers |
+----------------------+
2018-10-10 17:24:33,893 [INFO] - func=test_01_pass:[17] - location=debug_tests.py - MSG=Doing something to teardown the servers

其中log.info()使用带有时间戳等的格式化程序,而我创建的另一个日志log.step()使用没有时间戳的格式化器。

定义两个写入sys.stdout的streamHandlers时,代码的输出:

logger.step('Create Service')
logger.info('Doing create service flow')

logger.step('Teardown the servers')
logger.info('Doing something to teardown the servers')

看起来不错,如上面的第一个片段所示。

但是,当使用写入同一日志的两个fileHandler时,输出会乱码:

2018-10-10 17:24:33,891 [INFO] - func=test_01_pass:[7] - location=d
+-----------------------------------------------2018-10-10 17:24:33,892 [INFO] - func=test_01_pass:[11] - location=debug_tests.py - MSG=Doing something to login
2018-10-10 17:24:33,892 [INFO] - func=test_01_pass:[14] - l
+----------------------+
| Teardown the servers |
+---2018-10-10 17:24:33,893 [INFO] - func=test_01_pass:[17] - location=debug_tests.py - MSG=Doing something to teardown the servers

是否可以使用两个不同的格式化程序来写入相同日志文件?

------其他信息------

我找到了一种解决方案How to use different formatters with the same logging handler in python,该解决方案可以根据调度程序(即哪个模块正在编写它。我正在尝试从该解决方案中修改类 DispatchingFormatter ,以根据消息的严重性级别选择格式化程序。

0 个答案:

没有答案
相关问题