我试图在使用两个将输出流式传输到控制台的记录器对象之前和之后使用打印功能。事情是我得到了一个不符合预期顺序的非常混乱的输出。
我尝试将 print() 更改为 logger_object.info() 并且效果很好。
具有意外输出的完整代码:
import logging
# Create logger objects and set level
loggerA = logging.getLogger()
loggerA.setLevel(logging.DEBUG)
loggerB = logging.getLogger()
loggerB.setLevel(logging.DEBUG)
# Set log output format
log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y - %I:%M:%S %p')
# Create a console stream handler
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(log_format)
# Add handlers to the loggers
loggerA.addHandler(stream_handler)
loggerB.addHandler(stream_handler)
def main():
for i in range(10):
print('Starting loop number {}'.format(i))
loggerA.info("loop number {}".format(i))
loggerB.info("loop number {}".format(i))
print('Finished loop number {}'.format(i))
if __name__ == '__main__':
main()
添加 loggerC 对象以将 print() 替换为 loggerC.info() :
...
loggerC = logging.getLogger()
loggerC.setLevel(logging.DEBUG)
...
def main():
for i in range(10):
loggerC('Starting loop number {}'.format(i))
loggerA.info("loop number {}".format(i))
loggerB.info("loop number {}".format(i))
loggerC('Finished loop number {}'.format(i))
...
使用 print() 意外输出的第一种情况是:
04/06/2019 - 10:10:34 AM - INFO - loggerA - loop number 1
Starting loop number 1
04/06/2019 - 10:10:34 AM - INFO - loggerB - loop number 1
04/06/2019 - 10:10:34 AM - INFO - loggerA - loop number 2
04/06/2019 - 10:10:34 AM - INFO - loggerB - loop number 2
Finished loop number 1
Starting loop number 2
Finished loop number 2
Starting loop number 3
Finished loop number 3
04/06/2019 - 10:10:34 AM - INFO - loggerA - loop number 3
04/06/2019 - 10:10:34 AM - INFO - loggerB - loop number 3
第二种情况使用 loggerC.info() 而不是 print() 这是预期的输出:
04/06/2019 - 10:12:21 AM - INFO - loggerC - Starting loop number 1
04/06/2019 - 10:12:21 AM - INFO - loggerA - loop number 1
04/06/2019 - 10:12:21 AM - INFO - loggerB - loop number 1
04/06/2019 - 10:12:21 AM - INFO - loggerC - Finished loop number 1
04/06/2019 - 10:12:21 AM - INFO - loggerC - Starting loop number 2
04/06/2019 - 10:12:21 AM - INFO - loggerA - loop number 2
04/06/2019 - 10:12:21 AM - INFO - loggerB - loop number 2
04/06/2019 - 10:12:21 AM - INFO - loggerC - Finished loop number 2
04/06/2019 - 10:12:21 AM - INFO - loggerC - Starting loop number 3
04/06/2019 - 10:12:21 AM - INFO - loggerA - loop number 3
04/06/2019 - 10:12:21 AM - INFO - loggerB - loop number 3
04/06/2019 - 10:12:21 AM - INFO - loggerC - Finished loop number 3