I'm trying to log into a single file using two different Formatters. The use-case for this is to get a file that looks like this:
+-------------------+
| 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
Where log.info() uses a formatter with a timestamp etc., while another log I created log.step() uses a formatter without a timestamp.
When defining two streamHandlers that write to sys.stdout, the output of the code:
logger.step('Create Service')
logger.info('Doing create service flow')
logger.step('Teardown the servers')
logger.info('Doing something to teardown the servers')
looks OK, as seen in the first snippet above.
However, when using the two fileHandlers that write to the same log, the output is garbled up:
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
Is there a way to write to the same log file using two different formatters?
------ Additional Info ------
I found a solution How to use different formatters with the same logging handler in python that allows to change the formatter depending on the dispatcher, i.d. which module is writing it. I am trying to modify the class DispatchingFormatter from that solution to select the formatter depending on the message severity level.