我真的錯過了關於python日誌記錄模塊的基本知識。幫我理解python的日誌記錄模塊及其處理程序
在下面的代碼中,我創建了一個記錄器對象(log
)並添加了兩個處理程序。一個與 'INFO'級別和一個'警告'級別。他們都應該打印到標準輸出。我希望調用log.info(msg)
將在我的標準輸出中產生msg
的一個副本,並且調用log.warn(msg)
可以產生 兩個副本msg
打印到我的標準輸出。這裏是代碼:
import logging
import sys
logging.basicConfig()
log = logging.getLogger('myLogger')
log.handlers = []
h1 = logging.StreamHandler(sys.stdout)
h1.level = logging.INFO
h1.formatter = logging.Formatter('H1 H1 %(message)s ')
h2 = logging.StreamHandler(sys.stdout)
h2.level = logging.WARNING
h2.formatter = logging.Formatter('H2 H2 %(message)s')
log.addHandler(h1)
log.addHandler(h2)
print 'log.level == %s'%logging.getLevelName(log.level)
print 'log.info'
log.info('this is some info')
print 'done'
print 'log.warn'
log.warn('this is a warning')
print 'done'
輸出對我來說真的很奇怪。呼叫.info
不會導致視覺效果。 但是,調用warn
會導致將兩個msg打印到stdout(這是OK),但也會將一個副本打印到stderr(爲什麼?)。這是上述代碼的輸出。請注意此輸出中最後一行的格式。這一行打印到stderr。
log.level == NOTSET
log.info
done
log.warn
H1 H1 this is a warning
H2 H2 this is a warning
done
WARNING:myLogger:this is a warning
所以我的問題是:
- 爲什麼,我呼籲
info
沒有輸出結果儘管h1
的級別設置爲INFO的事實? - 爲什麼我打電話給
warn
會導致額外的輸出到stderr?
我不能肯定,但你可能會運行到麻煩,因爲Python的'logging'有警告和信息一個內置的水平。 – brc
@brc這會回答我的第一個問題,但不是第二個問題 –