zoukankan      html  css  js  c++  java
  • python日志模块logging

    python日志模块logging

     

    1. 基础用法

    python提供了一个标准的日志接口,就是logging模块。日志级别有DEBUG、INFO、WARNING、ERROR、CRITICAL五种(级别依次升高),分别对应的函数为debug()、info()、warning()、error()、critical()。

    >>> import logging 
    >>> logging.debug("ni hao")
    >>> logging.info("ni hao2")
    >>> logging.warning("ni hao")
    WARNING:root:ni hao
    >>> logging.error("ni hao")
    ERROR:root:ni hao
    >>> logging.critical("ni hao")
    CRITICAL:root:ni hao
    >>> 
    

    可以发现debug()和info()方法没有显示任何信息,这是因为默认的日志级别是WARNING,所以低于此级别的日志不会记录。

    可以利用函数basicCinfig修改日志级别

    >>> import logging
    >>> logging.basicConfig(level=logging.INFO)
    >>> logging.info("nihao")
    INFO:root:nihao
    >>> logging.debug("dfasl")
    >>> logging.basicConfig(level=logging.DEBUG)
    >>> logging.info(4)
    INFO:root:4
    >>>
    

    basicConfig()函数还可以定义更多的内容,如

    logging.basicConfig(format=log_format,datefmt='%Y-%m-%d %H:%M:%S %p',level=logging.DEBUG) 
    

    举例 

    import logging
    log_format = '%(filename)s %(funcName)s %(asctime)s %(message)s'
    log_filename = "logging_test.log"
    logging.basicConfig(filename=log_filename, format=log_format, datefmt='%Y-%m-%d %H:%M:%S:%S %p', filemode='w', level=logging.INFO)
    
    logging.warning("warning###########")
    logging.warning("error@@@@@@@@@@@@@@")
    logging.error("error~~~~~~~~~~~~~~~~")

     结果(输出文件“logging_test.log”内容)

    del.py <module> 2015-04-30 16:29:02:02 PM warning
    del.py <module> 2015-04-30 16:29:02:02 PM error
    del.py <module> 2015-04-30 16:29:02:02 PM error
    

    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被忽略

    日志的设置是使用basicConfig()方法,日志写入文件的默认方式是‘a’,即“追加”,如果想覆盖文件,使用filemode='w'。

    logging模块的功能非常强大,可以通过更加自由的接口,自定义出更复杂的日志形式。需要用到下面3种对象logger、formatter、handler 。以下介绍logger

    2. logger

    logger对象直接提供日志接口。

    通过handler对象可以把日志内容写到不同的地方。

    例:将日志同时输出到文件和屏幕

    #coding: utf-8
    import logging
    
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    
    fh = logging.FileHandler("test.log")
    ch = logging.StreamHandler()
    
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    
    logger.addHandler(fh)        #可以设置addHandler添加内容(fh、ch、fh+ch),从而设置输出位置
    logger.addHandler(ch)
    
    logger.error("error$$$$$$$$$$")
    logger.debug("aaaaa**********")

    3. 模块

    #! /usr/bin/env python
    # --*-- coding:utf-8 --*--
    import os
    import logging
    import logging.handlers
    
    #LOGGER = logging.getLogger(__name__)
    
    def init_log(LOGGER, log_file_path):
        LOGGER.setLevel(logging.INFO)
    
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter("%(asctime)s %(levelname)s %(filename)s(%(lineno)d) %(message)s ", "%Y-%m-%d %H:%M:%S")
        ch.setFormatter(formatter)
        LOGGER.addHandler(ch)
    
        log_dir = os.path.dirname(log_file_path)
        if not os.path.isdir(log_dir):
            os.makedirs(log_dir)
        fh = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=10*1024*1024, backupCount=9)
        fh.setLevel(logging.INFO)
        fh.setFormatter(formatter)
        LOGGER.addHandler(fh)
    
    if __name__=="__main__":
    
        print "Unsupported in main module..."

    :logging.handlers.RotatingFileHandler
    这个Handler可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。最后重新创建 chat.log,继续输出日志信息。【这样保证了chat.log里面是最新的日志】它的构造函数是:
    RotatingFileHandler(filename[, mode[, maxBytes[, backupCount]]])
    其中filename和mode两个参数和FileHandler一样。
    maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
    backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。

     
  • 相关阅读:
    ABAP接口用法
    监听textarea数值变化
    The first step in solving any problem is recognizing there is one.
    Wrinkles should merely indicate where smiles have been.
    God made relatives.Thank God we can choose our friends.
    Home is where your heart is
    ABAP跳转屏幕
    Python 工具包 werkzeug 初探
    atom通过remote ftp同步本地文件到远程主机的方法
    Mongodb学习笔记一
  • 原文地址:https://www.cnblogs.com/Vito2008/p/4929249.html
Copyright © 2011-2022 走看看