参考源: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. Q2Day81

    性能相关 在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢. import requests def fetch_async(url): ...

  2. 消除Warning: Using a password on the command line interface can be insecure的提示

    最近在部署Zabbix时需要用脚本取得一些MySQL的返回参数,需要是numberic格式的,但是调用脚本时总是输出这一句: Warning: Using a password on the comm ...

  3. LeetCode算法题-Remove Linked List Elements(Java实现)

    这是悦乐书的第189次更新,第191篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第48题(顺位题号是203).移除单链表中节点值为val的节点.例如: 输入:1-> ...

  4. 《Java大学教程》--第2章 选择

    迭代(iteration).重复(repetition):三种循环* for: 重复执行固定次数* while: 重复执行不固定次数* do...while: 比while至少多一次 1.答:P47迭 ...

  5. 08.Python网络爬虫之图片懒加载技术、selenium和PhantomJS

    引入 今日概要 图片懒加载 selenium phantomJs 谷歌无头浏览器 知识点回顾 验证码处理流程 今日详情 动态数据加载处理 一.图片懒加载 什么是图片懒加载? 案例分析:抓取站长素材ht ...

  6. MySQL高级知识(八)——ORDER BY优化

    前言:在使用order by时,经常出现Using filesort,因此对于此类sql语句需尽力优化,使其尽量使用Using index. 0.准备 #1.创建test表. drop table i ...

  7. chrome-performance页面性能分析使用教程

    运行时性能表现(runtime performance)指的是当你的页面在浏览器运行时的性能表现,而不是在下载页面的时候的表现.这篇指南将会告诉你怎么用Chrome DevTools Performa ...

  8. ROS 小乌龟测试

    教程 1.维基 http://wiki.ros.org/cn/ROS/Tutorials 2. 创客智造 http://www.ncnynl.com/category/ros-junior-tutor ...

  9. 在JS中调用CS里的方法(PageMethods)

    在JS中调用CS里的方法(PageMethods) 2014年04月28日 11:18:18 被动 阅读数:2998   最近一直在看别人写好的一个项目的源代码,感觉好多东西都是之前没有接触过的.今天 ...

  10. 深入剖析kafka架构内部原理

    1 概述 Kakfa起初是由LinkedIn公司开发的一个分布式的消息系统,后成为Apache的一部分,它使用Scala编写,以可水平扩展和高吞吐率而被广泛使用.目前越来越多的开源分布式处理系统如Cl ...