一、引言

  之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个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. HDU 1421 DP

    搬寝室 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...

  2. tomcat域名问题

    首先可以确认,tomcat支持以下的配置: 1.同一个tomcat配置多个端口来发布不同的应用,配置多个<Service>即可; 2.同一个tomcat可以配置多个虚拟主机,以指定不同的域 ...

  3. [转载] Can't create table './store/#sql-b2c_1a.frm' (errno: 150)和sql execution error #1452添加外键时错误解决方法

    Can't create table './store/#sql-b2c_1a.frm' (errno: 150)解决方法 错误原因有四: 1.外键的引用类型不一样,主键是int外键是char 2.找 ...

  4. iOS frame从导航栏下面开始

    iOS7.0 之后,页面布局默认延伸到了手机界面的边缘;导航栏背景成透明颜色. 解决fram从导航栏下面开始方法: 第一种: 将导航栏改成不透明即可 if( ([[[UIDevice currentD ...

  5. Educational Codeforces Round 16 A B C E

    做题太久也有点累了..难题不愿做 水题不愿敲..床上一躺一下午..离下一场div2还有点时间 正好有edu的不计分场 就做了一下玩玩了 D是个数学题 F是个AC自动机 都没看明白 留待以后补 A 给出 ...

  6. ssh增加密匙登录

    使用要创建登录密匙的账号登录 生成密匙 #ssh-keygen -t rsa 生成时提示输入密码,如果不输入,则直接回车即可,如果输入,将在无密匙登陆时要求输入该密码 进入生成目录.ssh #cd ~ ...

  7. 使用 U盘 重装 Mac OSX

    一.制作 U 盘系统启动盘 1.从 App Store 上下载 OS Application.(这里需要注意,取消下载完的自动更新,并存储下这个 OS.Application 文件,因为系统更新完后, ...

  8. Visual Studio中编写C程序

    相信很多科班出身的程序猿和我一样,第一个接触到的编程语言是C语言,第一个写的程序是“Hello World!”. 对于一个.Net程序猿,VS肯定是个非常熟悉的工具,但是如何使用VS编写一个C语言程序 ...

  9. CSS典型案例实践

    CSS案例实践 一.层布局:定位元素重叠 在CSS中可以通过z-index属性来确定定位元素的层叠等级.需要注意的是: z-index属性只有在元素的position属性取值为relative.abs ...

  10. 盒模型--padding

    突然增加padding会使盒子变大,所以要按实际情况做调整. 没有写padding的时候: <style>div{ background:gray;}</style></ ...