python logging类库使用例子

2019-10-05 13:17:29于丽

 运行结果

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]