logging——日志
- 导读
- 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为
debug(), info(), warning(), error() and critical()
5个级别import logging
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down") #output WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down简单用法
- 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为
- 日志级别,DEBUG为最低级别
Level When it’s used DEBUG
Detailed information, typically of interest only when diagnosing problems. INFO
Confirmation that things are working as expected. WARNING
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. ERROR
Due to a more serious problem, the software has not been able to perform some function. CRITICAL
A serious error, indicating that the program itself may be unable to continue running. - 写日志文件
import logging
logging.basicConfig(filename = 'example.log',level = logging.INFO)
#创建一个'example.log'日志文件,日志级别为INFO
logging.debug('This message should go to the log file')#级别低于INFO,不会写入到日志文件中
logging.info('So should this')
logging.warning('And this, too') #注意:如果运行多次,则会在之前的记录后面追加记录,不会覆盖原有的记录
- 自定义日志格式
%(name)s Logger的名字 %(levelno)s 数字形式的日志级别 %(levelname)s 文本形式的日志级别 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 %(filename)s 调用日志输出函数的模块的文件名 %(module)s 调用日志输出函数的模块名 %(funcName)s 调用日志输出函数的函数名 %(lineno)d 调用日志输出函数的语句所在的代码行 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d 线程ID。可能没有 %(threadName)s 线程名。可能没有 %(process)d 进程ID。可能没有 %(message)s 用户输出的消息 import logging
logging.basicConfig(filename = 'example.log',
level = logging.INFO,
format='%(asctime)s-%(levelno)s-%(levelname)s-%(pathname)s-%(filename)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info('So should this')
logging.warning('And this, too')日志格式代码示例
- 日志同时输出到文件和屏幕
- 知识储备
- 如果想同时把log打印到屏幕和日志文件中,需要了解一点复杂的知识。python使用logging模块记录日志涉及四个主要类,使用官方文档的概括最为合适:
- logger提供应用程序可以直接使用的接口;
- handler将(logger创建的)日志记录发送到合适的目的输出;
- filter提供了细度设备来决定输出哪条日志记录;
- formatter决定日志记录的最终输出格式
- 功能分析
- logger:每个程序在输出信息之前都要获得一个logger。logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
- LOG = logging.getLogger("chat.gui")
- 核心模块可以:LOG = logging.getLogger("chat.kernel")
- 还可以绑定handle和filters
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
- handler:handler对象负责发送相关的信息到指定目的地。Python的日志系统有很多种Handle可以使用。有些Handler可以把信息输出到控制台,有些Handler可以把信息输出到文件,还有些Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多Handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象每个Logger可以附加多个Handler。接下来我们介绍一些常用的Handler:
- 1.logging.StreamHandler使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息
- 2.logging.FileHandler 和StreamHandler 类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文
- 3.logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
- maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
- backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。
- 4.logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval
是时间间隔。when
参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:- S 秒
- M 分
- H 小时
- D 天
- W 每星期(interval==0时代表星期一)
- midnight 每天凌晨
- formatter:日志的formatter是个独立的组件,可以跟handler组合
如果你想对日志内容进行过滤,就可自定义一个filter
class IgnoreBackupLogFilter(logging.Filter):
"""忽略带db backup 的日志"""
def filter(self, record): #固定写法
return "db backup" not in record.getMessage()注意filter函数会返加True or False,logger根据此值决定是否输出此日志
然后把这个filter添加到logger中
logger.addFilter(IgnoreBackupLogFilter())
下面的日志就会把符合filter条件的过滤掉
logger.debug("test ....")
logger.info("test info ....")
logger.warning("start to run db backup job ....")
logger.error("test error ....")import logging class IgnoreBackupLogFilter(logging.Filter):
"""忽略带db backup 的日志"""
def filter(self, record): #固定写法
return "db backup" not in record.getMessage() #1.生成logger对象
logger = logging.getLogger("Web")
logger.setLevel(logging.DEBUG)
#1.1把filter对象添加到logger中
logger.addFilter(IgnoreBackupLogFilter()) #2.生成handler对象
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
fh = logging.FileHandler("web.log")
fh.setLevel(logging.WARNING)
#2.1把handler对象绑定到logger对象
logger.addHandler(ch)
logger.addHandler(fh) #3.生成format对象
#3.1把formatter对象绑定handler对象
file_formatter = logging.Formatter('%(asctime)s %(message)s')
console_formatter = logging.Formatter('%(asctime)s %(message)s')
ch.setFormatter(console_formatter)
fh.setFormatter(file_formatter) logger.debug("test ....")
logger.info("test info ....")
logger.warning("start to run db backup job ....")
logger.error("test error ....")示例
- logger:每个程序在输出信息之前都要获得一个logger。logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
import logging
from logging import handlers logger = logging.getLogger(__name__)
log_file = "timelog.log"
fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)
formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logging——日志的更多相关文章
- logging 日志模块学习
logging 日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪,所以还是灰常重要滴,下面我就来从入门到放弃的系统学习一下日志既可以在屏幕上显示,又可以在文件中体现. ...
- logging日志模块
为什么要做日志: 审计跟踪:但错误发生时,你需要清除知道该如何处理,通过对日志跟踪,你可以获取该错误发生的具体环境,你需要确切知道什么是什么引起该错误,什么对该错误不会造成影响. 跟踪应用的警告和错误 ...
- python 自动化之路 logging日志模块
logging 日志模块 http://python.usyiyi.cn/python_278/library/logging.html 中文官方http://blog.csdn.net/zyz511 ...
- python-整理-logging日志
python的日志功能模块是logging 功能和使用方式非常类似于log4 如何使用logging: # 导入日志模块import logging# 使用配置文件设置日志时,需要导入这个模块 imp ...
- form,ajax注册,logging日志使用
一.form表单类型提交注册信息 二.ajax版本提交注册信息 <!DOCTYPE html> <html lang="en"> <head> ...
- 【转】python模块分析之logging日志(四)
[转]python模块分析之logging日志(四) python的logging模块是用来写日志的,是python的标准模块. 系列文章 python模块分析之random(一) python模块分 ...
- day31 logging 日志模块
# logging 日志模块 ****** # 记录用户行为或者代码执行过程 # print 来回注释比较麻烦的 # logging # 我能够“一键”控制 # 排错的时候需要打印很多细节来帮助我排错 ...
- python模块分析之logging日志(四)
前言 python的logging模块是用来设置日志的,是python的标准模块. 系列文章 python模块分析之random(一) python模块分析之hashlib加密(二) python模块 ...
- logging日志模块的使用
logging日志模块的使用 logging模块中有5个日志级别: debug 10 info 20 warning 30 error 40 critical 50 通常使用日志模块,是用字典进行配置 ...
- slf4j/logback: logging日志的配置
slf4j/logback: logging日志的配置 import依赖: import org.slf4j.Logger;import org.slf4j.LoggerFactory;private ...
随机推荐
- echarts使用中的那些事儿(二)
然而第二天的事情你怎么能猜到客户的心思呢: 客户:右边的是啥? 偶:可放大缩小查看各个时期的数据. 客户:把它去掉吧,全部直观显示. 偶:哦,不过数据过多的话会导致页面过长的. 客户:只有你知道这个可 ...
- Redis、Memcache区别
Redis.Memcache区别 redis单核 memcahce多核 redis支持数据持久化 redis支持的数据类型比较多 memcache 只有key->value类型 key-> ...
- Linux上通过MySQL命令访问MySQL数据库时常见问题汇总
Linux上通过mysql命令访问MySQL数据库时常见问题汇总 1)创建登录账号 #创建用户并授权 #允许本地访问 create user 'test'@'localhost' identified ...
- 洛谷 P2966 [USACO09DEC]牛收费路径Cow Toll Paths
题目描述 Like everyone else, FJ is always thinking up ways to increase his revenue. To this end, he has ...
- wall命令
wall——发送广播信息 write all /usr/bin/wall 示例1: # wall 输入命令之后回车便可以广播消息,如输入Hello everybody online后Ctrl+D结束并 ...
- 晒一下MAC下终端颜色配置
效果图: ~/.vimrc 配置 filetype on set history=1000 set background=dark syntax on set autoindent set smart ...
- python3.6 配置COCO API出错解决方案
使用Anaconda Prompt进行安装 问题出现的背景:在尝试使用mask-rcnn时,遇到了这个问题,最终解决掉了
- [论文理解]SSD:Single Shot MultiBox Detector
SSD:Single Shot MultiBox Detector Intro SSD是一套one-stage算法实现目标检测的框架,速度很快,在当时速度超过了yolo,精度也可以达到two-stag ...
- 使用FontDialog组件设置字体
实现效果: 知识运用: FontDialog组件的Font属性 //获取或设置选定的字体 public Font Font { get;set; } 实现代码: private void butto ...
- hadoop相关资料集锦
1 Hadoop集群系列集锦http://www.cnblogs.com/xia520pi/archive/2012/04/08/2437875.html 2 Hadoop和MapReduce详解ht ...