常用模块之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. [转]Bypassing iOS security

    src: http://blog.thireus.com/tag/kernelcache Before going further it is important to enumerate some ...

  2. 2012 T-SQL 新特性 and O2O项目

    SQL Server 2012 T-SQL 新特性 NoSQL之HBase   9月初淘宝飞芃做了一个关于HBase的分享,讲的激情飞扬,让听众收益匪浅,现做下简单总结. HBase是一个NoSQL数 ...

  3. oracle中sys和System的默认密码

    sys:change_on_install system:oracle 如果用pl/sql登录的话,记得在下面用户权限选项选择sysdba,如图所示:

  4. JS判断字符串是否包含某字符串 indexOf()方法使用

    定义和用法 indexOf()方法可返回某个指定的字符串值在字符串中首次出现的位置. 开始的.如果没有找到子字符串,则返回 -1. 示例: <script type="text/jav ...

  5. 让MyEclipse里的Tomcat自动reloadable

    1  修改server.xml Context path="/***" docBase="XXX" reloadable="true"/&g ...

  6. 在windows上编译MatConvNet

    有个BT的要求,在windows上使用MatConvNet,并且需要支持GPU. 费了些力气,记录一下过程(暂不支持vl_imreadjpeg函数) 在这里下载MatConvNet,机器配置vs201 ...

  7. 简单实现TCP下的大文件高效传输

    简单实现TCP下的大文件高效传输 在TCP下进行大文件传输不象小文件那样直接打包个BUFFER发送出去,因为文件比较大所以不可能把文件读到一个BUFFER发送出去.主要有些文件的大小可能是1G,2G或 ...

  8. MacOSX 下.app支持同时运行多个实例

    在MacOSX下的.app是一个程序包(实际上是个目录),双击该目录时系统会根据包的目录结构启动相应的可执行程序..app的程序默认是单实例运行的,所以从.app启动的程序实例只有一个(可执行程序不受 ...

  9. 三千万数据量下redis2.4的一统计情况

    先说一下工作场景,要求做一个服务,满足:处理千万级别数据,单个请求响应时间在20ms以下.由于是存储的数据格式为key:list[],所以很适合使用redis来存放数据,为了测试一下redis存储的效 ...

  10. 作怪的Buffer

    俗话说:人丑多作怪.在编程界里面也有很多作怪之物,其中首推buffer. 上一次聊到了tar.gz创建导出的问题,我本以为自己把相关的文件流操作都摸清楚了.没想到当我开心地去研究ip库替换方案和同事们 ...