項目用到日誌,收集了一個方法,不廢話直接上代碼
import logging
from logging import handlers
class Logger(object):
level_relations = {
‘debug’:logging.DEBUG,
‘info’:logging.INFO,
‘warning’:logging.WARNING,
‘error’:logging.ERROR,
‘crit’:logging.CRITICAL
}#日誌級別關係映射
def __init__(self,filename,level=’info’,when=’D',backCount=3,fmt=’%(asctime)s – %(pathname)s[line:%(lineno)d] – %(levelname)s: %(message)s’):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt)#設置日誌格式
self.logger.setLevel(self.level_relations.get(level))#設置日誌級別
sh = logging.StreamHandler()#往屏幕上輸出
sh.setFormatter(format_str) #設置屏幕上顯示的格式
th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding=’utf-8′)#往文件裏寫入#指定間隔時間自動生成文件的處理器
#實例化TimedRotatingFileHandler
#interval是時間間隔,backupCount是備份文件的個數,如果超過這個個數,就會自動刪除,when是間隔的時間單位,單位有以下幾種:
# S 秒
# M 分
# H 小時、
# D 天、
# W 每星期(interval==0時代表星期一)
# midnight 每天淩晨
th.setFormatter(format_str)#設置文件裏寫入的格式
self.logger.addHandler(sh) #把對象加到logger裏
self.logger.addHandler(th)
if __name__ == ‘__main__’:
log = Logger(‘all.log’,level=’debug’)
log.logger.debug(‘debug’)
log.logger.info(‘info’)
log.logger.warning(‘警告’)
log.logger.error(‘報錯’)
log.logger.critical(‘嚴重’)
Logger(‘error.log’, level=’error’).logger.error(‘error’)
屏幕上的結果如下:
2018-03-13 21:06:46,092 – D:/write_to_log.py[line:25] – DEBUG: debug
2018-03-13 21:06:46,092 – D:/write_to_log.py[line:26] – INFO: info
2018-03-13 21:06:46,092 – D:/write_to_log.py[line:27] – WARNING: 警告
2018-03-13 21:06:46,099 – D:/write_to_log.py[line:28] – ERROR: 報錯
2018-03-13 21:06:46,099 – D:/write_to_log.py[line:29] – CRITICAL: 嚴重
2018-03-13 21:06:46,100 – D:/write_to_log.py[line:30] – ERROR: error
相關說明:
1、VIP會員無限製任意下載,免積分。立即前往開通>>
2、下載積分可通過日常 簽到、綁定郵箱 以及 積分兌換 等途徑獲得!
3、本站資源大多存儲在雲盤,如出現鏈接失效請評論反饋,如有密碼,均為:www.ipipn.com。
4、所有站內資源僅供學習交流使用。未經原版權作者許可,禁止用於任何商業環境,否則後果自負。為尊重作者版權,請購買正版作品。
5、站內資源來源於網絡公開發表文件或網友分享,如侵犯您的權益,請聯係管理員處理。
6、本站提供的源碼、模板、軟件工具等其他資源,都不包含技術服務,請大家諒解!
7、源碼、模板等資源會隨著技術、壞境的升級而存在部分問題,還請慎重選擇。
PS.源碼均收集自網絡,如有侵犯閣下權益,請發信件至: admin@ipipn.com .
源站網 »
Python 利用 logging 將日誌輸出到屏幕並且寫入文件