Python之logging模块
一、引言
之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下:
#!/usr/bin/python
# -*- coding=utf-8 -*- import time
import os def record_log(names,act,things,price,money):
#日志文件名
logfile = 'log.txt'
#数据插入的日期
date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
record_line = date + '\t' + names + '\t' + act + '\t' + things + '\t' + price + '\t' + str(money) + '\n'
#判断日志文件是否存在,如果不存在就创建一个新文件,并插入单位名称
if not os.path.exists(logfile):
f = open(logfile,'w')
record = '日期' + '\t\t' + '用户' + '\t\t' + '动作' + '\t\t' + '事务' + '\t\t' + '价格' + '\t\t' + '余额' + '\n'
f.write(record)
f.close()
f = open(logfile,'a')
f.write(record_line)
f.flush()
f.close()
后来发现有logging模块,感觉自己之前的写的好low!今天就来介绍一下logging模块。
二、logging模块
Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。
logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。
logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。
与log4j类似,logger,handler和日志消息的调用可以有具体的日志级别(level),只有在日志消息的级别大于logger和handler的级别。
#!/usr/bin/env python
# -*- coding=utf-8 -*- import logging #创建一个logging的实例logger
logger = logging.getLogger('Richard')
#设定全局日志级别为DEBUG
logger.setLevel(logging.INFO)
#创建一个屏幕的handler,并且设定级别为DEBUG
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#创建一个日志文件的handler,并且设定级别为DEBUG
fh = logging.FileHandler("access.log")
fh.setLevel(logging.CRITICAL)
#设置日志的格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
#add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
#add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
#'application' code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("crititcal message")
输出结果:
"D:\Program Files (x86)\python34\python.exe" F:/Python/Alex/s12/Blog/log.py
2016-03-22 06:13:09,764 - Richard - INFO - info message
2016-03-22 06:13:09,764 - Richard - WARNING - warn message
2016-03-22 06:13:09,764 - Richard - ERROR - error message
2016-03-22 06:13:09,764 - Richard - CRITICAL - crititcal message access.log:
2016-03-22 06:13:09,764 - Richard - CRITICAL - crititcal message
在这里需要说明的一点是logger.setLevel(logging.INFO)和ch.setLevel(logging.DEBUG)的区别:
通过例子来看:
#设定全局日志级别为CRITICAL
logger.setLevel(logging.CRITICAL)
#创建一个屏幕的handler,并且设定级别为DEBUG
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#创建一个日志文件的handler,并且设定级别为INFO
fh = logging.FileHandler("access.log")
fh.setLevel(logging.INFO) 输出结果:
"D:\Program Files (x86)\python34\python.exe" F:/Python/Alex/s12/Blog/log.py
2016-03-22 06:20:10,712 - Richard - CRITICAL - crititcal message access.log:
2016-03-22 06:20:10,712 - Richard - CRITICAL - crititcal message
就是全局日志级别为CRITICAL的话,局部变量想设置成INFO或者DEBUG都会失效。
由此可以得出全局的比局部的级别要高,加入全局的设成DEBUG的话,局部可以设成WARNING,那么logging只会输出WARNG、ERROR、CRITICAL这三种类型。
备注:关于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的关键字替换。提供的关键字包括:
Attribute name | Format | Description |
---|---|---|
args | You shouldn’t need to format this yourself. | The tuple of arguments merged into msg to produce message , or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary). |
asctime | %(asctime)s |
Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time). |
created | %(created)f |
Time when the LogRecord was created (as returned by time.time() ). |
exc_info | You shouldn’t need to format this yourself. | Exception tuple (à la sys.exc_info ) or, if no exception has occurred, None. |
filename | %(filename)s |
Filename portion of pathname . |
funcName | %(funcName)s |
Name of function containing the logging call. |
levelname | %(levelname)s |
Text logging level for the message ('DEBUG' , 'INFO' , 'WARNING' , 'ERROR' ,'CRITICAL' ). |
levelno | %(levelno)s |
Numeric logging level for the message (DEBUG , INFO , WARNING , ERROR ,CRITICAL ). |
lineno | %(lineno)d |
Source line number where the logging call was issued (if available). |
module | %(module)s |
Module (name portion of filename ). |
msecs | %(msecs)d |
Millisecond portion of the time when the LogRecord was created. |
message | %(message)s |
The logged message, computed as msg % args . This is set whenFormatter.format() is invoked. |
msg | You shouldn’t need to format this yourself. | The format string passed in the original logging call. Merged with args to produce message , or an arbitrary object (see Using arbitrary objects as messages). |
name | %(name)s |
Name of the logger used to log the call. |
pathname | %(pathname)s |
Full pathname of the source file where the logging call was issued (if available). |
process | %(process)d |
Process ID (if available). |
processName | %(processName)s |
Process name (if available). |
relativeCreated | %(relativeCreated)d |
Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. |
stack_info | You shouldn’t need to format this yourself. | Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record. |
thread | %(thread)d |
Thread ID (if available). |
threadName | %(threadName)s |
Thread name (if available). |
logging官网地址:
https://docs.python.org/3.5/library/logging.html
Python之logging模块的更多相关文章
- python的logging模块
python提供了一个日志处理的模块,那就是logging 导入logging模块使用以下命令: import logging logging模块的用法: 1.简单的将日志打印到屏幕上 import ...
- python的logging模块之读取yaml配置文件。
python的logging模块是用来记录应用程序的日志的.关于logging模块的介绍,我这里不赘述,请参见其他资料.这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出. python要读取 ...
- python中logging模块的用法
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...
- python基础--logging模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...
- Python中logging模块的基本用法
在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 ...
- python之logging模块简单用法
前言: python引入logging模块,用来记录自己想要的信息.print也可以输入日志,但是logging相对print来说更好控制输出在哪个地方.怎么输出以及控制消息级别来过滤掉那些不需要的信 ...
- Python的logging模块详解
Python的logging模块详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.日志级别 日志级别指的是产生的日志的事件的严重程度. 设置一个级别后,严重程度 ...
- Python的logging模块基本用法
Python 的 logging 模块的简单用法 在服务器部署时,往往都是在后台运行.当程序发生特定的错误时,我希望能够在日志中查询.因此这里熟悉以下 logging 模块的用法. logging 模 ...
- python(logging 模块)
1.logging 模块的日志级别 DEBUG:最详细的日志信息,典型应用场景是 问题诊断 INFO:信息详细程度仅次于DEBUG,通常只记录关键节点信息,用于确认一切都是按照我们预期的那样进行工作 ...
随机推荐
- OpenCV 3.1 StereoBM 获取正确视差Dispariy
OpenCV更新到3.0版本后,Stereo模块变化的挺多的,首先去掉了StereoBMState和StereoSGBMState这两个专门控制BM和SGBM算法参数的类,而且StereoBM不能直接 ...
- Hibernate+Struts2进行数据的修改
1.先把userid传给修改的页面 2.跳转到修改的页面 3.用request接收传入输入需改信息的页面 传到action Action, 通过request获取id service层 DAO层 & ...
- Daily Scrum 10.28
今天是周一,大家基本都结束了设计阶段转入代码实现的阶段,由于同志们感觉这部分的难度比较大,所以经过讨论延长了这部分的估计时间. 下面是今天的Task统计: 所有迭代的状态:
- BizTalk开发系列(十五) Schema设计之Qualified 与Unqualified
XML Schema中的命名空间前缀限定包括对元素(Element)或属性(Attribute)的限定,即常见的如 “<ns0:root>...</ns0:root>”之类的格 ...
- eclipse汉化过程
第一步: 打开浏览器,浏览“参考资料”内给出的“eclipse语言包下载”地址,在博客新页面找到地址链接,如图所示.“Babel Language...”开头的一栏下面就是各个eclise版本的语言包 ...
- poj1061-青蛙的约会(扩展欧几里德算法)
一,题意: 两个青蛙在赤道上跳跃,走环路.起始位置分别为x,y. 每次跳跃距离分别为m,n.赤道长度为L.两青蛙跳跃方向与次数相同的情况下, 问两青蛙是否有方法跳跃到同一点.输出最少跳跃次数.二,思路 ...
- Python高级特性(1):Iterators、Generators和itertools(参考)
对数学家来说,Python这门语言有着很多吸引他们的地方.举几个例子:对于tuple.lists以及sets等容器的支持,使用与传统数学类 似的符号标记方式,还有列表推导式这样与数学中集合推导式和集的 ...
- 【后台测试】手把手教你jmeter压测
◆版权声明:本文出自胖喵~的博客,转载必须注明出处. 转载请注明出处:http://www.cnblogs.com/by-dream/p/5611555.html 我知道我迟早是要踏上了后台测试之路 ...
- Git 学习01
一.下载并安装git bash 双击打开出现命令窗口 创建一个版本库非常简单,首先,选择一个合适的地方,创建一个空目录: cd F: mkdir learngit pwd F/learngit 显示当 ...
- autocomplete一次返回多个值,并且选定后填到不同的Textbox中
$(txtTest1).autocomplete({ source: function (request, response) { $.ajax({ url: 'HttpHandler.ashx?to ...