2019年5月21日 星期二

[ Python 常見問題 ] How to change the format of logged messages temporarily, in Python?

Source From Here 
Question 
What is the simplest method for temporarily changing the logging message format, in Python (through the logging module)? 

How-To 
Here is a simple solution, that can be deduced from Vinay Sajip's own HOWTO; it basically updates the logging formatter with setFormatter(): 
  1. import logging  
  2.   
  3. logger = logging.getLogger()  # Logger  
  4. logger_handler = logging.StreamHandler()  # Handler for the logger  
  5. logger.addHandler(logger_handler)  
  6.   
  7. # First, generic formatter:  
  8. logger_handler.setFormatter(logging.Formatter('%(message)s'))  
  9. logger.error('error message')  # Test  
  10.   
  11. # New formatter for the handler:  
  12. logger_handler.setFormatter(logging.Formatter('PROCESSING FILE xxx - %(message)s'))  
  13. logger.error('error message')  # Test  
This correctly produces: 
error message 
PROCESSING FILE xxx - error message

Supplement 
* FAQ - How to get the list all existing loggers using python.logging module 
  1. import logging  
  2. loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...