1. 程式人生 > 實用技巧 >python基礎-logging模組

python基礎-logging模組

共5個等級,預設輸出大於等於warning級別

import logging

logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error("error")
logging.critical('critical')

1. 可通過def basicConfig(**kwargs):修改

filename  Specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified
(if filemode is unspecified, it defaults to 'a').
format Use the specified format string for the handler.
datefmt Use the specified date/time format.
style If a format string is specified, use this to specify the
type of format string (possible values '%', '{', '$', for
%-formatting, :meth:`str.format` and :class:`string.Template`
- defaults to '%').
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with 'filename' - if both
are present, 'stream' is ignored.
handlers If specified, this should be an iterable of already created
handlers, which will be added to the root handler. Any handler
in the list which does not have a formatter assigned will be
assigned the formatter created in this function.
import logging

logging.basicConfig(
    level=logging.DEBUG,
    filename='logger.log',
    format='%(asctime)s %(lineno)d %(message)s'
)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')

logging.basicConfig函式各引數:
filename: 指定日誌檔名
filemode: 和file函式意義相同,指定日誌檔案的開啟模式,'w'或'a'
format: 指定輸出的格式和內容,format可以輸出很多有用資訊,如上例所示:
 %(levelno)s: 列印日誌級別的數值
 %(levelname)s: 列印日誌級別名稱
 %(pathname)s: 列印當前執行程式的路徑,其實就是sys.argv[0]
 %(filename)s: 列印當前執行程式名
 %(funcName)s: 列印日誌的當前函式
 %(lineno)d: 列印日誌的當前行號
 %(asctime)s: 列印日誌的時間
 %(thread)d: 列印執行緒ID
 %(threadName)s: 列印執行緒名稱
 %(process)d: 列印程序ID
 %(message)s: 列印日誌資訊
datefmt: 指定時間格式,同time.strftime()
level: 設定日誌級別,預設為logging.WARNING
stream: 指定將日誌的輸出流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略

2.logging.getLogger()函式設定


import logging

logger = logging.getLogger()#可傳參
fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
fm = logging.Formatter('%(asctime)s %(lineno)d %(msg)s')
fh.setFormatter(fm)
ch.setFormatter(fm)
logger.addHandler(fh)
logger.addHandler(ch)
logger.setLevel('ERROR')
logging.debug('debug
') logging.info('info') logging.warning('warning') logging.error('error') logging.critical('critical')