常用模块之logging

用于便捷记录日志且线程安全的模块

import logging

logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10) logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

对于等级:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

只有大于当前日志等级的操作才会被记录。

对于格式,有如下属性可是配置:

---------------------------------------------------------------------------------------------

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

最简单用法

import logging

logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down") #输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down

看一下这几个日志级别分别代表什么意思

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

  

如果想把日志写到文件里,也很简单

import logging

logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志 才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

logging.basicConfig(filename='example.log',level=logging.INFO)

感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.') #输出
12/12/2010 11:46:36 AM is when this event was logged.

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.
import logging

#create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.DEBUG) # create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) # create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
# create formatter
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('critical message')

参考链接:

http://www.cnblogs.com/alex3714/articles/5161349.html

http://www.cnblogs.com/wupeiqi/articles/4963027.html

Python学习笔记——基础篇【第六周】——logging模块的更多相关文章

  1. Python学习笔记——基础篇【第一周】——变量与赋值、用户交互、条件判断、循环控制、数据类型、文本操作

    目录 Python第一周笔记 1.学习Python目的 2.Python简史介绍 3.Python3特性 4.Hello World程序 5.变量与赋值 6.用户交互 7.条件判断与缩进 8.循环控制 ...

  2. Python学习笔记——基础篇【第二周】——解释器、字符串、列表、字典、主文件判断、对象

    目录 1.Python介绍 2.Python编码 3.接受执行传参 4.基本数据类型常用方法 5.Python主文件判断 6.一切事物都是对象 7.   int内部功能介绍 8.float和long内 ...

  3. Python学习笔记基础篇——总览

    Python初识与简介[开篇] Python学习笔记——基础篇[第一周]——变量与赋值.用户交互.条件判断.循环控制.数据类型.文本操作 Python学习笔记——基础篇[第二周]——解释器.字符串.列 ...

  4. Python学习笔记——基础篇【第七周】———类的静态方法 类方法及属性

    新式类和经典类的区别 python2.7 新式类——广度优先 经典类——深度优先 python3.0 新式类——广度优先 经典类——广度优先 广度优先才是正常的思维,所以python 3.0中已经修复 ...

  5. Python学习笔记——基础篇【第五周】——常用模块学习

    模块介绍 本节大纲: 模块介绍 time &datetime模块   (时间模块) random   (随机数模块) os   (系统交互模块) sys shutil   (文件拷贝模块) j ...

  6. Python 学习笔记---基础篇

    1. 简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200 import subprocess cmd="cmd.exe" b ...

  7. Python成长笔记 - 基础篇 (六)python模块

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

  8. Python学习笔记——基础篇【第六周】——面向对象

    Python之路,Day6 - 面向对象学习 本节内容:   面向对象编程介绍 为什么要用面向对象进行开发? 面向对象的特性:封装.继承.多态 类.方法.       同时可参考链接: http:// ...

  9. Python学习笔记——基础篇【第六周】——json & pickle & shelve & xml处理模块

    json & pickle 模块(序列化) json和pickle都是序列化内存数据到文件 json和pickle的区别是: json是所有语言通用的,但是只能序列化最基本的数据类型(字符串. ...

随机推荐

  1. dtrace sample

    #!/usr/sbin/dtrace -s #pragma D option flowindent /* monitor file open */ syscall::open:entry { prin ...

  2. Microsoft Message Analyzer (微软消息分析器,“网络抓包工具 - Network Monitor”的替代品)官方正式版现已发布

    Microsoft Message Analyzer (微软消息分析器,“网络抓包工具 - Network Monitor”的替代品)官方正式版现已发布 来自官方日志的喜悦 被誉为全新开始的消息分析器 ...

  3. 4月13号的web标准化交流化-开端

    这是实习工作的开始,也是正式踏入北京之后去参加的第一个活动.也算是想着法的去融入这个圈子. 这两个分享都是基于nodejs的.nodejs从11年开始就开始红火.但是真正nodejs能用来干什么? 我 ...

  4. SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面)

    挺好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面) 这个工具主要就是自动备份数据库,一键还原数据库,发送备份数据库日志报告到邮箱,自动压缩备份好的数据库 定期执行数 ...

  5. Single Image Haze Removal Using Dark Channel Prior

    <Single Image Haze Removal Using Dark Channel Prior>一文中图像去雾算法的原理.实现.效果及其他. Posted on 2013-08-2 ...

  6. SL.XNA中的Popup

    如果要xna与sl混合显示,就不能用popup,不然会有各种显示错乱的问题.如果xna与sl单独显示,可以使用popup,但是要记得移除UIElementRenderer.就是说popup只能交给系统 ...

  7. [置顶] javascript-基于对象or面向对象?

    最近完成了javascript的初级学习,在这个学习的视频中,我特别注意了两个词,解释性语言和对象,javascript按照我的理解,应该是种解释性语言,他有关于面向对象的思想的体现,但是,他和vb一 ...

  8. Android 短信模块分析(三) MMS入口分析

    MMS入口分析:      在Mms中最重要的两个Activity,一个是conversationList(短信列表) ,另一个就是ComposeMessageActivity(单个对话或者短信).每 ...

  9. HashMap完全解读

    一.什么是HashMap 基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了非同步和允许使用 null 之外,HashMap 类与 Has ...

  10. java异常处理01

    当我们做java项目的时候,多多少少都会出现一些异常,如何快速处理异常也将会影响到一个项目开发的进度. 以下将是面对的一些异常将如何去处理: 1.数据库没有启动 解决方法:计算机-->管理--& ...