参考源:http://www.cnblogs.com/yuanchenqi/articles/5732581.html

logging模块 (****重点***)

一 (简单应用)

import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

输出:

WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message

可见,默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。

二  灵活配置日志级别,日志格式,输出位置(只能屏幕或文件输出二选一)

import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w') logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

查看输出:
cat /tmp/test.log 
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message

可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open('test.log','w')),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(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用户输出的消息

三  logger对象(实现屏幕和文件同时输出的功能)

上述几个例子中我们了解到了logging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical()(分别用以记录不同级别的日志信息),logging.basicConfig()(用默认日志格式(Formatter)为日志系统建立一个默认的流处理器(StreamHandler),设置基础配置(如日志级别等)并加到root logger(根Logger)中)这几个logging模块级别的函数,另外还有一个模块级别的函数是logging.getLogger([name])(返回一个logger对象,如果没有指定名字将返回root logger)

 import logging
#日志函数logger对象
logger=logging.getLogger() #设置文件输出方式和屏幕输出方式对象,并设置输出格式
fh=logging.FileHandler('test.log')
ch=logging.StreamHandler() formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter)
ch.setFormatter(formatter) #日志函数对象把文件和屏幕输出对象加入自己
logger.addHandler(fh)
logger.addHandler(ch) logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message') 输出结果:
2018-06-14 15:52:36,657 - root - WARNING - logger warning message
2018-06-14 15:52:36,657 - root - ERROR - logger error message
2018-06-14 15:52:36,657 - root - CRITICAL - logger critical message

logger对象

从这个输出可以看出logger = logging.getLogger()返回的Logger名为root。这里没有用logger.setLevel(logging.Debug)显示的为logger设置日志级别,所以使用默认的日志级别WARNIING,故结果只输出了大于等于WARNIING级别的信息。

 import logging
#日志函数logger对象(两个)
logger1=logging.getLogger()
logger2=logging.getLogger()
#配置logger对象的日志级别
logger1.setLevel(logging.DEBUG)
logger2.setLevel(logging.INFO) #设置文件输出方式和屏幕输出方式对象,并设置输出格式
fh=logging.FileHandler('test.log')
ch=logging.StreamHandler() formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter)
ch.setFormatter(formatter) #日志函数对象把文件和屏幕输出对象加入自己
logger1.addHandler(fh)
logger1.addHandler(ch)
logger2.addHandler(fh)
logger2.addHandler(ch) logger1.debug('logger debug message')
logger1.info('logger info message')
logger1.warning('logger warning message')
logger1.error('logger error message')
logger1.critical('logger critical message')
logger2.debug('logger debug message')
logger2.info('logger info message')
logger2.warning('logger warning message')
logger2.error('logger error message')
logger2.critical('logger critical message') 输出结果:
2018-06-14 16:10:38,441 - root - INFO - logger info message
2018-06-14 16:10:38,442 - root - WARNING - logger warning message
2018-06-14 16:10:38,442 - root - ERROR - logger error message
2018-06-14 16:10:38,442 - root - CRITICAL - logger critical message
2018-06-14 16:10:38,442 - root - INFO - logger info message
2018-06-14 16:10:38,442 - root - WARNING - logger warning message
2018-06-14 16:10:38,442 - root - ERROR - logger error message
2018-06-14 16:10:38,442 - root - CRITICAL - logger critical message

两个logger对象

这里有两个个问题:

<1>我们明明通过logger1.setLevel(logging.DEBUG)将logger1的日志级别设置为了DEBUG,为何显示的时候没有显示出DEBUG级别的日志信息,而是从INFO级别的日志开始显示呢?

原来logger1和logger2对应的是同一个Logger实例,只要logging.getLogger(name)中名称参数name相同则返回的Logger实例就是同一个,且仅有一个,也即name与Logger实例一一对应。在logger2实例中通过logger2.setLevel(logging.INFO)设置mylogger的日志级别为logging.INFO,所以最后logger1的输出遵从了后来设置的日志级别。

<2>为什么logger1、logger2对应的每个输出分别显示两次?
       这是因为我们通过logger = logging.getLogger()显示的创建了root Logger,而logger1 = logging.getLogger('mylogger')创建了root Logger的孩子(root.)mylogger,logger2同样。而孩子,孙子,重孙……既会将消息分发给他的handler进行处理也会传递给所有的祖先Logger处理。

 import os
import time
import logging
from config import settings #这里有问题 def get_logger(card_num, struct_time): if struct_time.tm_mday < 23:
file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22)
else:
file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22) file_handler = logging.FileHandler(
os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name),
encoding='utf-8'
)
fmt = logging.Formatter(fmt="%(asctime)s : %(message)s")
file_handler.setFormatter(fmt) logger1 = logging.Logger('user_logger', level=logging.INFO)
logger1.addHandler(file_handler)
return logger1 调用:
logger=get_logger()
logger.info('信息')

ATM应用

Day15 Python基础之logging模块(十三)的更多相关文章

  1. Python自建logging模块

    本章将介绍Python内建模块:日志模块,更多内容请从参考:Python学习指南 简单使用 最开始,我们用最短的代码体验一下logging的基本功能. import logging logger = ...

  2. 十八. Python基础(18)常用模块

    十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...

  3. python基础,函数,面向对象,模块练习

    ---恢复内容开始--- python基础,函数,面向对象,模块练习 1,简述python中基本数据类型中表示False的数据有哪些? #  [] {} () None 0 2,位和字节的关系? # ...

  4. python基础31[常用模块介绍]

    python基础31[常用模块介绍]   python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...

  5. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  6. Python实战之logging模块使用详解

    用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...

  7. Python基础-包与模块

    Python基础-包与模块 写在前面 如非特别说明,下文均基于Python3 摘要 为重用以及更好的维护代码,Python使用了模块与包:一个Python文件就是一个模块,包是组织模块的特殊目录(包含 ...

  8. Python中的logging模块就这么用

    Python中的logging模块就这么用 1.日志日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICALDEBUG:详细的信息,通常只出现在诊断问题 ...

  9. python中日志logging模块的性能及多进程详解

    python中日志logging模块的性能及多进程详解 使用Python来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析.Python的 ...

随机推荐

  1. xpath语法大全

    XPath 节点 XPath 术语 节点 在 XPath 中,有七种类型的节点:元素.属性.文本.命名空间.处理指令.注释以及文档(根)节点.XML 文档是被作为节点树来对待的.树的根被称为文档节点或 ...

  2. 优雅的使用Spring

    Bean声明的三种方式: 1.@Component, @Service, @Repository,@Controller 用于声明一个组件,程序启动时会扫描这些组件,并创建实例. 2.在applica ...

  3. C语言 求两数的最大公约数和最小公倍数

    //作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ #include<stdio.h> //最大公约数 int gys(int x,int ...

  4. 从Hadoop到Spark的架构实践

    当下,Spark已经在国内得到了广泛的认可和支持:2014年,Spark Summit China在北京召开,场面火爆:同年,Spark Meetup在北京.上海.深圳和杭州四个城市举办,其中仅北京就 ...

  5. C. Magic Ship cf 二分

    C. Magic Ship time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...

  6. Alex网络

    alexNet共有八层网络卷积层1:输入224*224*3 卷积核11*11*3*96 步长为4 然后是ReLU.局部归一化.3*3步长为2的最大值池化卷积层2:输入为28*28*96 卷积核5*5* ...

  7. maven-resources-plugin插件关于占位符不生效问题

    插件版本: <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0. ...

  8. No.0

    算法类 1.快速排序算法 2.树的非递归后序排序算法 3.希尔排序 4.冒泡排序 5.链表和链表转向 6.其他   设计模式 1.单例模式 2.工厂模式 3.抽象工厂模式 4.面向对象设计,ooa,o ...

  9. P2802 回家 (DFS+剪枝)

    这里详细讲一下剪枝的点: 因为,可以重复在同一个点上走动.所以,这个步数是无穷的. 剪枝一:步数< n*m;    (因为起点不算所以不取等号) 剪枝二:步数当大于已有的答案时,直接退出DFS, ...

  10. P1145 约瑟夫 W(模拟)

    暴力+模拟 #include<iostream> #include<cstring> using namespace std; int ans, k, k2; ]; bool ...