一、引言

  之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个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. [CareerCup] 18.4 Count Number of Two 统计数字2的个数

    18.4 Write a method to count the number of 2s between 0 and n. 这道题给了我们一个整数n,让我们求[0,n]区间内所有2出现的个数,比如如 ...

  2. Centos Odoo Service Config

    #!/bin/sh ### BEGIN INIT INFO # Provides: openerp-server # Required-Start: $remote_fs $syslog # Requ ...

  3. SQL 语句调用这个存储过程,生成顺序编码

    一直很讨厌存储过程,没想到今天帮了我大忙啊,或许会因为今天让我慢慢喜欢上存储过程吧,不多说了,切入正题 在使用数据库的时候,难免要在使用过程中进行删除的操作,如果是使用int类型的字段,令其自增长,这 ...

  4. CSS3初学篇章_5(背景样式/列表样式/过渡动画)

    背景样式 1.背景颜色语法:background-color : transparent | color body { background-color:#CCCCCC;} 2.渐变色彩语法:back ...

  5. HTTP 战役 与 历史

    导火线1992年,有一家公司Nombas 开发了一种叫C--的嵌入式脚本语言,后来觉得名字比较晦气,最终改名为scriptEase.而这种可以嵌入网页中的脚本的理念,成为日后移动互联网蓬勃发展的一块重 ...

  6. 【iCore3 双核心板_ uC/OS-III】例程二:任务的建立与删除

    实验指导书及代码包下载: http://pan.baidu.com/s/1bD7ulK iCore3 购买链接: https://item.taobao.com/item.htm?id=5242294 ...

  7. maven使用本地jar包

    引入本地jar包 方式一:将本地Jar包安装到本地仓库,再按常规方式引用 mvn install:install-file -Dfile=libs\tools.jar -DgroupId=com.su ...

  8. easyUI datagrid笔记

    easyUI datagrid 简单使用与注意细节 背景: 业余爱好,使用了一下easyUI的搜索框与数据表格,并把两者整合起来进行使用. 使用前提(引入需要的js and css): <lin ...

  9. MVC Pager 使用

    MVC Pager  4.0+     3.0版本使用  ,直接来点使用的.一看就明白 @Ajax.Pager(Model,pagerOptions,mvcAjaxOptions); @using W ...

  10. Java集合---HashMap源码剖析

    一.HashMap概述二.HashMap的数据结构三.HashMap源码分析     1.关键属性     2.构造方法     3.存储数据     4.调整大小 5.数据读取           ...