1.简单的将日志打印到屏幕

 

import logging

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

屏幕上打印:
WARNING:root:This is warning message

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

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='myapp.log',
                filemode='w')
    
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
 %(levelno)s: 打印日志级别的数值
 %(levelname)s: 打印日志级别名称
 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
 %(filename)s: 打印当前执行程序名
 %(funcName)s: 打印日志的当前函数
 %(lineno)d: 打印日志的当前行号
 %(asctime)s: 打印日志的时间
 %(thread)d: 打印线程ID
 %(threadName)s: 打印线程名称
 %(process)d: 打印进程ID
 %(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

3.将日志同时输出到文件和屏幕

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='myapp.log',
                filemode='w')

#################################################################################################
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

屏幕上打印:
root        : INFO     This is info message
root        : WARNING  This is warning message

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日志回滚

import logging
from logging.handlers import RotatingFileHandler

#################################################################################################
#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
################################################################################################

从上例和本例可以看出,logging有一个日志处理的主对象,其它处理方式都是通过addHandler添加进去的。
logging的几种handle方式如下:

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件
logging.FileHandler: 日志输出到文件

日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler
logging.handlers.BaseRotatingHandler
logging.handlers.RotatingFileHandler
logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets
logging.handlers.DatagramHandler:  远程输出日志到UDP sockets
logging.handlers.SMTPHandler:  远程输出日志到邮件地址
logging.handlers.SysLogHandler: 日志输出到syslog
logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志
logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer
logging.handlers.HTTPHandler: 通过"GET"或"POST"远程输出到HTTP服务器

由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中,
上述其它处理方式的使用请参见python2.5手册!

5.通过logging.config模块配置日志

#logger.conf

###############################################

[loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################

[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)

###############################################

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

上例3:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

上例4:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

6.logging是线程安全的

7.logging重定向strerr,strout

import loggingimport sys

class StreamToLogger(object):"""   Fake file-like stream object that redirects writes to a logger instance."""   def __init__(self, logger, log_level=logging.INFO):      self.logger = logger      self.log_level = log_level      self.linebuf = ''

   def write(self, buf):for line in buf.rstrip().splitlines():         self.logger.log(self.log_level, line.rstrip())

logging.basicConfig(   level=logging.DEBUG,   format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',   filename="out.log",   filemode='a')

stdout_logger = logging.getLogger('STDOUT')sl = StreamToLogger(stdout_logger, logging.INFO)sys.stdout = sl

stderr_logger = logging.getLogger('STDERR')sl = StreamToLogger(stderr_logger, logging.ERROR)sys.stderr = sl

print "Test to standard out"raise Exception('Test to standard error')

We define a custom file-like object called StreamToLogger object which sends anything written to it to a logger instead. We then create two instances of that object and replace sys.stdout and sys.stderr with our fake file-like instances.

The output logfile looks like this:

2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out  2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):  2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in   2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')  2011-08-14 14:46:20,574:ERROR:STDERR:Exception  2011-08-14 14:46:20,574:ERROR:STDERR::  2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error  2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in 2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')2011-08-14 14:46:20,574:ERROR:STDERR:Exception2011-08-14 14:46:20,574:ERROR:STDERR::2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error

python之强大的日志模块相关推荐

  1. python强大的模块_python之强大的日志模块-阿里云开发者社区

    1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('This is info messa ...

  2. Python项目中 封装日志模块logging 及快速调用方法

    前言 在 Python 中,可以直接用自带的 logging 模块来记录日志,但是在使用时我们需要配置一些 Handler.Formatter 来进行一些处理,比如把日志输出到不同的位置,或者设置一个 ...

  3. python成长日迹--日志模块logging

    简单输出日志 import logging #导入输出日志的模块#我们直接输出查看结果 logging.debug('debug message') logging.info('info messag ...

  4. python 技术篇-使用logging日志模块自定义时间格式

    首先看一下效果图: 下面是我定义的日志格式: import logginglogging.basicConfig(filename = path + 'log_' + today_date + '.t ...

  5. python写日志文件_Python logging日志模块 配置文件方式

    在一些微服务或web服务中我们难免需要日志功能,用来记录一些用户的登录记录,操作记录,以及一些程序的崩溃定位,执行访问定位等等; Python内置 非常强大的日志模块 ==> logging 今 ...

  6. Python日志模块

    一.loguru的使用 Loguru 一个能彻底解放你的日志记录器. 它即插即用,具备多种方式滚动日志.自动压缩日志文件.定时删除等功能. 除此之外,多线程安全.高亮日志.日志告警等功能也不在话下. ...

  7. 【Python】—日志模块logging使用详解1

    文章目录 1.日志级别 2.logging流程 3.几个重要的类 3.1 Logger类 1) 最常用的配置方法 2) 创建`Logger`对象`logging.getLogger([name])` ...

  8. python日志模块方法_python日志模块logbook使用方法

    python自带了日志模块logging,可以用来记录程序运行过程中的日志信息.同时python还有logbook模块用来取代logging模块,在很多的项目中logbook模块使用也是比较的多,因此 ...

  9. python 日志模块--python logbook使用方法

    python自带了日志模块logging,可以用来记录程序运行过程中的日志信息.同时python还有logbook模块用来取代logging模块,在很多的项目中logbook模块使用也是比较的多,因此 ...

最新文章

  1. JAVA数组的定义及用法
  2. schema.sql自动写入。由于版本问题。2.x之后。就不行了。·
  3. R语言使用car包的durbinWatsonTest函数检验回归模型的响应变量(或者残差)是否具有独立性(Independence、是否具有自相关关javascript系autocorrelated)
  4. Java 枚举(enum)详解
  5. linux驱动中printk的使用注意事项
  6. [***]HZOJ 柱状图
  7. Latex安装中知道的基础常识
  8. java get方法不序列化_java常用序列化与反序列化方法
  9. OS- -调度(二)
  10. Sharepoin学习笔记—架构系列--01 Sharepoint的网页(Page),网页解析(Parsing)与解析安全处理(Security)
  11. oracle 10g rac 修改sga_target不生效,Oracle Rac 修改SGA_TARGET值无变化
  12. NLP学习—13.Seq2eq在机器翻译中的实战(bleu指标的代码实现)
  13. JAVA Web开发MySQL数据库记录浏览分页
  14. MySql join 详解
  15. 计算机模拟电子云密度,小知识:分子动力学基本原理及应用
  16. c++面试常见题·Part 3 TCP/IP多线程编程设计模式Linux基操等
  17. CSS常用函数补充(var、clac、blur、gradient)
  18. 项目管理软件用哪个好?推荐这6款项目管理工具
  19. scJoint integrates atlas-scale single-cell RNA-seq and ATAC-seq data with transfer learning
  20. 直流无刷电机的调试与代码开源(配套资源)

热门文章

  1. 2张图片就能「算出」一段视频,Reddit网友都惊呆了 | 旷视北大出品
  2. 赶上直播电商、在线教育、小程序直播的风口 腾讯音视频解决方案助力
  3. 哪里不知道“瞄”哪里,这项AI黑科技,打开手机就能体验
  4. Vue面试中经常会被问到的面试题
  5. Java虚拟机04——垃圾收集器
  6. 中国在科技领域崛起 美国人的保护主义蠢蠢欲动
  7. IBM和Lightbend宣布构建新认知开发平台的战略
  8. Entity Freamwork 6连接PostgreSql数据库
  9. [Android] Handler源码解析 (Java层)
  10. Asp.Net 之 下载文件的常用方式