记录日志logging.debug('This is a debug message')logging.info('This is an info message')logging.warning('This is a warning message')logging.error('This is an error message')logging.critical('This is a critical message')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
LOG_FILENAME = 'log.txt'
logging.basicConfig(
filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.debug('hello logging!')
with open(LOG_FILENAME, 'rt') as f:
body = f.read()
print('FILE: ')
print(body)
运行脚本后输出如下:
FILE:
DEBUG:root:hello logging!
日志文件的循环
要让每次程序运行时,生成一个新的文件,需要向 basicConfig() 传一个值为 w 的 filemode 参数。还有一个更方便的方法,就是使用 RotatingFileHandler,可以同时自动创建文件和保存旧文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import logging.handlers
LOG_FILENAME = 'log.txt'
my_logger = logging.getLogger('SpecificLogger')
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(f'i = {i}')
# See what files are created
log_files = glob.glob(f'{LOG_FILENAME}*')
for filename in sorted(log_files):
print(filename)
记录日志logging.debug('This is a debug message')logging.info('This is an info message')logging.warning('This is a warning message')logging.error('This is an error message')logging.critical('This is a critical message')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
LOG_FILENAME = 'log.txt'
logging.basicConfig(
filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.debug('hello logging!')
with open(LOG_FILENAME, 'rt') as f:
body = f.read()
print('FILE: ')
print(body)
运行脚本后输出如下:
FILE:
DEBUG:root:hello logging!
日志文件的循环
要让每次程序运行时,生成一个新的文件,需要向 basicConfig() 传一个值为 w 的 filemode 参数。还有一个更方便的方法,就是使用 RotatingFileHandler,可以同时自动创建文件和保存旧文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import logging.handlers
LOG_FILENAME = 'log.txt'
my_logger = logging.getLogger('SpecificLogger')
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(f'i = {i}')
# See what files are created
log_files = glob.glob(f'{LOG_FILENAME}*')
for filename in sorted(log_files):
print(filename)