2014-05-14 44 views
2

如何打印Python 2.7 ConfigParserlogging的內容?如何將ConfigParser的內容打印到我的日誌中?

我能找到的唯一解決方案是寫入臨時文件並將該文件重新讀入。另一個想法是從日誌記錄實用程序獲取假「文件句柄」,並將其傳遞給ConfigParser寫入方法,但我不知道如何獲得這樣的句柄表單日誌記錄。

回答

2

您應該能夠創建寫入日誌的可寫對象。像這樣的東西(如果你想保持串繞,你可以修改ConfigLogger保存它):

import ConfigParser 
import logging 

class ConfigLogger(object): 
    def __init__(self, log): 
     self.__log = log 
    def __call__(self, config): 
     self.__log.info("Config:") 
     config.write(self) 
    def write(self, data): 
     # stripping the data makes the output nicer and avoids empty lines 
     line = data.strip() 
     self.__log.info(line) 

config = ConfigParser.ConfigParser() 
config.add_section("test") 
config.set("test", "a", 1) 
# create the logger and pass it to write 
logging.basicConfig(filename="test.log", level=logging.INFO) 
config_logger = ConfigLogger(logging) 
config_logger(config) 

我們得到以下的輸出:

INFO:root:Config: 
INFO:root:[test] 
INFO:root:a = 1 
INFO:root: 
+0

啊,我明白了。所以只要傳遞給ConfigParser.write的對象具有自己的寫函數,它會調用它?太糟糕了,您無法獲得開箱即用的INFO日誌編寫器對象。 – Adam