2015-04-01 123 views
0

對於Python項目我有一個簡單的記錄器,看起來像這樣:Python的記錄器。不記錄自定義日誌項

#!flask/bin/python 
from flask import Flask,request, Response 
import os.path 
import json 
import sys 
import logging 
import logging.handlers 
from dbMongoManager import saveToMongo 
from dbSQLManager import saveToMYSQL 
from FailedRequest import FailedRequest 
from JSONValidation import validateJSON 



#create logger 
logger = logging.getLogger('werkzeug') 
#defines logger file and max size 
handler = logging.handlers.RotatingFileHandler('request.log',maxBytes=5000000) 
#define logger format 
formatter = logging.Formatter("test %(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") 
handler.setFormatter(formatter) 
#add loggerhandler to applications 
logger.addHandler(handler) 
app.logger.addHandler(handler) 

logger.info("Logger started") 
... 
#app implementation here 
. 

文件request.log被創建,但進入「開始記錄」是沒有出路的。 雖然來自瓶子的事件(服務器啓動/停止,請求響應)確實得到記錄。 我的所有自定義日誌(logger.info,logger.warning等)都不會出現在文件中。哪裏可能是我的錯誤? 我見過的所有例子顯然都適用於這個實現。

內容從日誌重新加載腳本後:

2015-04-01 08:54:52,479 [MainThread ] [INFO ] * Detected change in '/usr/local/bin/restService/restService.py', reloading 
2015-04-01 08:55:08,393 [Thread-1 ] [INFO ] 194.209.7.10 - - [01/Apr/2015 08:55:08] "POST/HTTP/1.1" 400 - 
2015-04-01 08:55:08,559 [Thread-1 ] [INFO ] 194.209.7.10 - - [01/Apr/2015 08:55:08] "POST/HTTP/1.1" 400 - 

回答

1

這應該工作

import logging 
import logging.handlers 

# create logger 
root_logger = logging.getLogger() 
root_logger.setLevel(0) 
# defines logger file and max size 
handler = logging.handlers.RotatingFileHandler('request.log', maxBytes=5000000) 
# define logger format 
formatter = logging.Formatter("test %(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") 
handler.setFormatter(formatter) 
handler.setLevel(0) 
# add loggerhandler to applications 
root_logger.addHandler(handler) 

logger = logging.getLogger('app') 

logger.info("Logger started") 
+0

這就是輝煌。 如果我明白這是正確的,「root_logger」會記錄一切,包括子記錄器「記錄器」的事件? – 2015-04-01 09:16:12

+1

是的,您可以構建日誌記錄層次結構,然後對層次結構中節點上層的設置應用於較低層,除非被覆蓋。 https://docs.python.org/2/library/logging.html#logging.getLogger – sanyi 2015-04-01 09:19:28