一、引言

  之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个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 (DEBUGINFOWARNINGERROR,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模块的更多相关文章

  1. python的logging模块

    python提供了一个日志处理的模块,那就是logging 导入logging模块使用以下命令: import logging logging模块的用法: 1.简单的将日志打印到屏幕上 import ...

  2. python的logging模块之读取yaml配置文件。

    python的logging模块是用来记录应用程序的日志的.关于logging模块的介绍,我这里不赘述,请参见其他资料.这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出. python要读取 ...

  3. python中logging模块的用法

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...

  4. python基础--logging模块

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...

  5. Python中logging模块的基本用法

    在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 ...

  6. python之logging模块简单用法

    前言: python引入logging模块,用来记录自己想要的信息.print也可以输入日志,但是logging相对print来说更好控制输出在哪个地方.怎么输出以及控制消息级别来过滤掉那些不需要的信 ...

  7. Python的logging模块详解

          Python的logging模块详解 作者:尹正杰  版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.日志级别 日志级别指的是产生的日志的事件的严重程度. 设置一个级别后,严重程度 ...

  8. Python的logging模块基本用法

    Python 的 logging 模块的简单用法 在服务器部署时,往往都是在后台运行.当程序发生特定的错误时,我希望能够在日志中查询.因此这里熟悉以下 logging 模块的用法. logging 模 ...

  9. python(logging 模块)

    1.logging 模块的日志级别 DEBUG:最详细的日志信息,典型应用场景是 问题诊断 INFO:信息详细程度仅次于DEBUG,通常只记录关键节点信息,用于确认一切都是按照我们预期的那样进行工作 ...

随机推荐

  1. mysql错误代码整理

    1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除 ...

  2. mysql远程连接提示无法连接,报1130错误

    可能是你的帐号不允许从远程登陆,只能在localhost.这个时候只要在localhost的那台电脑,登入mysql后,更改 “mysql” 数据库里的 “user” 表里的 “host” 项,从”l ...

  3. SQL异常:ORA-00936: missing expression

    select * from t_user where id in()当条件in的内容为空时抛 java.sql.SQLException: ORA-00936: missing expression ...

  4. jsp页面向后台传值出现乱码的问题

    1.采用decode()方法 页面: Url: '<%=path%>/sfyh/infodata.jsp?type='+encodeURI(ss) , 后台: String result  ...

  5. C++11---nullptr

    1.nullprt与NULL 代码: void f(int i) {    cout << "f(int)" << endl;} void f(char* ...

  6. HDU 1565&1569 方格取数系列(状压DP或者最大流)

    方格取数(2) Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  7. 根据value选择select

    <script> var tem="{$Zgoods.type_2}"; $("#type_2 option[value='"+tem+" ...

  8. RDIFramework.NET ━ 9.13 系统日志与系统异常管理 ━ Web部分

    RDIFramework.NET ━ .NET快速信息化系统开发框架 9.13  系统日志与系统异常管理 -Web部分  一个软件在投入运行时不可能没有任何异常,在软件发生异常时及时的记录下来,也好我 ...

  9. delphi关闭程序Close,application.Terminate与halt区别

    当Close是一个主窗体时,程序会退出.Close会发生FormClose事件,FormCloseQuery事件Halt会发生FormDestory事件,Application.Terminate以上 ...

  10. APP更新名称

    在bundle中添加Bundle display name的key即可