python logging类库使用例子(2)
# "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