亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Python: Logging模塊實例詳解

標簽:
Python

Logging 模块

import logging

Quick Start

导入模块后直接logging.waring()logging.error()简单粗暴地调用即可。默认的levelDEBUG,所以warning会打印出信息,info级别更低,不会输出信息。如果你不知道level等参数的意义请后面解释,淡定,继续往下看。

如果不特别配置,logging模块将日志打印到屏幕上(stdout)。

#!/usr/local/bin/python# -*- coding:utf-8 -*-import logging
logging.warning('Watch out!')  # print message to consolelogging.info('I told you so')  # will not print anything

Log写入文件

更常见的情形是把信息记录在log文件里。需要用logging.basicConfig()设置文件名以及level等参数,常见的level见下表。

LevelValueUsage
CRITICAL50严重错误,表明程序已不能继续运行了
ERROR40严重的问题,程序已不能执行一些功能了
WARNING30有意外,将来可能发生问题,但依然可用
INFO20证明事情按预期工作
DEBUG10详细信息,调试问题时会感兴趣。

如果设置levelINFO,那么DEBUG级别的信息就不会输出。常见的函数接口有debug(), info(), warning(), error() and critical(),分别对应log不同严重级别的信息。

注意把下面代码写入脚本(直接在terminal里不会生成文件),比如test_log.py

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG,filemode='w')# filemode = 'w' 每次运行,重写loglogging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
cat example.log
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too

改变Log输出格式

通过format参数,可以定制写入log文件的格式。

import logging
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

记录时间

通过datafmt参数,可以格式化输出log的时间。

import logging
logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

07/16/2016 12:10:35 AM is when this event was logged.

更丰富的Log控制

上面的代码大部分是利用默认配置,其实我们自定义更多。比如把输出到terminallog.txt文件里。

首先理解几个概念是有用的。

  • Logger 记录器,暴露了应用程序代码能直接使用的接口。

  • Handler 处理器,将(记录器产生的)日志记录发送至合适的目的地。

  • Filter 过滤器,提供了更好的粒度控制,它可以决定输出哪些日志记录。

  • Formatter 格式化器,指明了最终输出中日志记录的布局。

首先,创建一个logger,记录器,然后给其添加不同的handler,输出到不同的渠道,比如下面这个例子就会生成log.txt文件,并同时输出在terminal里。

import logging# create logger with name# if not specified, it will be rootlogger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)# create a handler, write to log.txt# logging.FileHandler(self, filename, mode='a', encoding=None, delay=0)# A handler class which writes formatted logging records to disk files.fh = logging.FileHandler('log.txt')
fh.setLevel(logging.DEBUG)# create another handler, for stdout in terminal# A handler class which writes logging records to a streamsh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)# set formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)# add handler to loggerlogger.addHandler(fh)
logger.addHandler(sh)# log itlogger.debug('Debug')
logger.info('Info')
2016-07-18 21:43:14,648 - my_logger - DEBUG - Debug2016-07-18 21:43:14,650 - my_logger - INFO - Info

Ref:



作者:米乐乐果
链接:https://www.jianshu.com/p/29cb6a535e2d


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消