2014-10-05 233 views
0

我試圖在我的應用程序中使用日誌記錄模塊;看完後documenat我寫fullowing代碼:錯誤的格式化日誌消息;日誌記錄已寫入日誌

class mainwin(): 
    def start_logging(self , level): 

     logger = logging.getLogger('Rockdome:') 
     FORMAT = "***\n\n%s%(name)s [%(levelname)s]\nmodule: %(module)s\nMessage:%(message)s\n***" 
     logging.basicConfig(format=FORMAT, filename= "example.log" , filemode="w") 
     logger.setLevel(level) 
     self.logger = logger 

    def __init__(self): 
     self.start_logging(logging.INFO)   
     self.pid = os.getpid() 
     with open('%s/.aria2/pid'%self.home , 'w') as p: 
      p.write(str(self.pid)) 

我得到如下:

***{'threadName': 'MainThread', 'name': 'Rockdome:', 'thread': -1221756160, 'created': 1412549164.939926, 'process': 7195, 'processName': 'MainProcess', 'args':(), 'module': 'mainwin', 'filename': 'mainwin.py', 'levelno': 20, 'exc_text': None, 'pathname': 'mainwin.py', 'lineno': 184, 'msg': 'Application started PID= 7195', 'exc_info': None, 'message': 'Application started PID= 7195', 'funcName': '__init__', 'relativeCreated': 178.4038543701172, 'levelname': 'INFO', 'msecs': 939.9259090423584}Rockdome: [INFO] 
module: mainwin 
Message:Application started PID= 7195 
*** 

{}之間的文本是的LogRecord對象本身。

爲什麼logrecord對象已經寫入日誌文件?

問題是:如何得到這個輸出?

*** 
Rockdome: [INFO] 
module: mainwin 
Message:Application started PID= 7195 
*** 

回答

2

你只需要在您的格式字符串的開頭額外\n%s。刪除它們:

FORMAT = "***\n%(name)s [%(levelname)s]\nmodule: %(module)s\nMessage:%(message)s\n***" 

一旦你這樣做,你會得到正確的格式。額外的%s特別使得所有可能的logger屬性都被打印,這就是爲什麼你的消息看起來離你想要的太遠了。你可以更好地瞭解到底發生了什麼:

>>> d = {"test" : "abcdefg", "another" : "asdfasdf"} 
>>> print "%(test)s" % d # What you wanted to do 
abcdefg 
>>> print "%s" % d # What you ended up doing 
{'test': 'abcdefg', 'another': 'asdfasdf'} 
+1

我覺得這個神奇的答案被拒絕了。 (快速和準確) – esnadr 2014-10-05 23:50:02