python logging类库使用例子

 更新时间:2014年11月22日 14:21:21   投稿:junjie  
这篇文章主要介绍了python logging类库使用例子,本文讲解了简单使用、logging的level、Handlers、FileHandler + StreamHandler等内容,需要的朋友可以参考下

一、简单使用

复制代码 代码如下:

def TestLogBasic():
    import logging
    logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
    logging.debug('this is a message')
    logging.info("this is a info")
    logging.disable(30)#logging.WARNING
    logging.warning("this is a warnning")
    logging.critical("this is a critical issue")
    logging.error("this is a error")
    logging.addLevelName(88,"MyCustomError")
    logging.log(88,"this is an my custom error")
    try:
      raise Exception('this is a exception')
    except:
      logging.exception( 'exception')
    logging.shutdown()

TestLogBasic()

说明:(此实例为最简单的用法,用来将log记录到log文件中)

1)logging.basicConfig()中定义默认的log到log.txt,log文件为append模式,处理所有的level大于logging.NOTSET的logging,log的格式定义为'%(asctime)s - %(levelname)s: %(message)s';

2)使用logging.debug()...等来log相应level的log;

3)使用logging.disable()来disable某个logging level;

4)使用logging.addLevelName增加自定义的logging level;

5)使用logging.log来log自定义的logging level的log;

输出的text的log如下:

复制代码 代码如下:

2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
  File "testlog.py", line 15, in TestLogBasic
    raise Exception('this is a exception')
Exception: this is a exception

二、logging的level

复制代码 代码如下:

#logging level
#logging.NOTSET 0
#logging.DEBUG 10
#logging.INFO 20
#logging.WARNING 30
#logging.ERROR 40
#logging.CRITICAL 50

logging的level对应于一个int,例如10,20...用户可以自定义logging的level。

可以使用logging.setLevel()来指定要处理的logger级别,例如my_logger.setLevel(logging.DEBUG)表示只处理logging的level大于10的logging。
 

三、Handlers

Handler定义了log的存储和显示方式。

NullHandler不做任何事情。

StreamHandler实例发送错误到流(类似文件的对象)。
FileHandler实例发送错误到磁盘文件。
BaseRotatingHandler是所有轮徇日志的基类,不能直接使用。但是可以使用RotatingFileHandler和TimeRotatingFileHandler。
RotatingFileHandler实例发送信息到磁盘文件,并且限制最大的日志文件大小,并适时轮徇。
TimeRotatingFileHandler实例发送错误信息到磁盘,并在适当的事件间隔进行轮徇。
SocketHandler实例发送日志到TCP/IP socket。
DatagramHandler实例发送错误信息通过UDP协议。
SMTPHandler实例发送错误信息到特定的email地址。
SysLogHandler实例发送日志到UNIX syslog服务,并支持远程syslog服务。
NTEventLogHandler实例发送日志到WindowsNT/2000/XP事件日志。
MemoryHandler实例发送日志到内存中的缓冲区,并在达到特定条件时清空。
HTTPHandler实例发送错误信息到HTTP服务器,通过GET或POST方法。
NullHandler,StreamHandler和FileHandler类都是在核心logging模块中定义的。其他handler定义在各个子模块中,叫做logging.handlers。

当然还有一个logging.config模块提供了配置功能。

四、FileHandler + StreamHandler

复制代码 代码如下:

def TestHanderAndFormat():
    import logging
    logger = logging.getLogger("simple")
    logger.setLevel(logging.DEBUG)
   
    # create file handler which logs even debug messages
    fh = logging.FileHandler("simple.log")
    fh.setLevel(logging.DEBUG)
   
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
   
    # create formatter and add it to the handlers
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
   
    # add the handlers 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")

TestHanderAndFormat()

说明:(此实例同时使用FileHandler和StreamHandler来实现同时将log写到文件和console)

1)使用logging.getLogger()来新建命名logger;

2)使用logging.FileHandler()来生成FileHandler来将log写入log文件,使用logger.addHandler()将handler与logger绑定;

3)使用logging.StreamHandler()来生成StreamHandler来将log写到console,使用logger.addHandler()将handler与logger绑定;

4)使用logging.Formatter()来构造log格式的实例,使用handler.setFormatter()来将formatter与handler绑定;

 运行结果

simple.txt

复制代码 代码如下:

2011-01-18 11:25:57,026 - simple - DEBUG - debug message
2011-01-18 11:25:57,072 - simple - INFO - info message
2011-01-18 11:25:57,072 - simple - WARNING - warn message
2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

console

复制代码 代码如下:

2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

五、RotatingFileHandler

复制代码 代码如下:

def TestRotating():
    import glob
    import logging
    import logging.handlers
   
    LOG_FILENAME = 'logging_rotatingfile_example.out'

    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)

    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)

    my_logger.addHandler(handler)

    # Log some messages
    for i in range(20):
        my_logger.debug('i = %d' % i)

    # See what files are created
    logfiles = glob.glob('%s*' % LOG_FILENAME)

    for filename in logfiles:
        print(filename)
       
TestRotating()

说明:

RotatingFileHandler指定了单个log文件的size的最大值和log文件的数量的最大值,如果文件大于最大值,将分割为多个文件,如果log文件的数量多于最多个数,最老的log文件将被删除。例如此例中最新的log总是在logging_rotatingfile_example.out,logging_rotatingfile_example.out.5中包含了最老的log。

运行结果:

复制代码 代码如下:

logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

六、使用fileConfig来使用logger

复制代码 代码如下:

import logging
import logging.config

logging.config.fileConfig("logging.conf")

# create logger
logger = logging.getLogger("simpleExample")

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

logging.conf文件如下:

复制代码 代码如下:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

运行结果:

复制代码 代码如下:

2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

相关文章

  • python 检测图片是否有马赛克

    python 检测图片是否有马赛克

    这篇文章主要介绍了python 如何检测图片是否有马赛克,帮助大家更好的理解和使用python处理图片,感兴趣的朋友可以了解下
    2020-12-12
  • python中yield的用法详解——最简单,最清晰的解释

    python中yield的用法详解——最简单,最清晰的解释

    这篇文章主要介绍了python中yield的用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • Python操作MongoDB数据库的方法示例

    Python操作MongoDB数据库的方法示例

    这篇文章主要介绍了Python操作MongoDB数据库的方法,结合实例形式分析了Python命令行模式下操作MongoDB数据库实现连接、查找、删除、排序等相关操作技巧,需要的朋友可以参考下
    2018-01-01
  • Python调整图像hue值结合ImageEnhance库以实现色调增强

    Python调整图像hue值结合ImageEnhance库以实现色调增强

    这篇文章主要介绍了Python调整图像hue值结合ImageEnhance库以实现色调增强,PIL库中的ImageEnhance类可用于图像增强,可以调节图像的亮度、对比度、色度和锐度,通过RGB到HSV的变换加调整可以对图像的色调进行调整,需要的朋友可以参考下
    2023-09-09
  • python使用正则筛选信用卡

    python使用正则筛选信用卡

    这篇文章主要为大家详细介绍了python使用正则筛选信用卡,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • python游戏开发的五个案例分享

    python游戏开发的五个案例分享

    本文给大家分享了作者整理的五个python游戏开发的案例,通过具体设计思路,代码等方面详细了解python游戏开发的过程,非常的详细,希望大家能够喜欢
    2020-03-03
  • Django数据库迁移报错InconsistentMigrationHistory

    Django数据库迁移报错InconsistentMigrationHistory

    最近在使用Django,学习了一下Django数据库迁移,在执行迁移命令时,突然报错,本文就总结了一下原因,感兴趣的小伙伴们可以参考一下
    2021-05-05
  • Python高级特性 切片 迭代解析

    Python高级特性 切片 迭代解析

    这篇文章主要介绍了Python高级特性 切片 迭代解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Python文件简单操作及openpyxl操作excel文件详解

    Python文件简单操作及openpyxl操作excel文件详解

    这篇文章主要为大家详细介绍了python对文件的简单使用及openpyxl操作excel文件的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-10-10
  • Flask框架学习笔记之模板操作实例详解

    Flask框架学习笔记之模板操作实例详解

    这篇文章主要介绍了Flask框架学习笔记之模板操作,结合实例形式详细分析了flask框架模板引擎Jinja2的模板调用、模板继承相关原理与操作技巧,需要的朋友可以参考下
    2019-08-08

最新评论