在Python中,你可以使用内置的`logging`模块来记录日志。下面是一个基本的示例,展示了如何配置和使用日志记录器:
python
import logging
配置日志记录器
logging.basicConfig(filename='example.log', level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
记录日志
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')
如果你想在终端输出日志,并且日志文件能够自动旋转(例如,当日志文件达到5MB时创建一个新的日志文件),你可以使用`RotatingFileHandler`:
python
import logging
from logging.handlers import RotatingFileHandler
创建日志记录器
logger = logging.getLogger('Robot')
创建一个StreamHandler,用于在终端输出日志
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
创建一个RotatingFileHandler,用于写入日志文件,并设置日志文件的最大大小和备份数量
file_handler = RotatingFileHandler(os.path.join('Logs', 'robot.log'), maxBytes=5 * 1024 * 1024, backupCount=10, encoding='utf-8')
设置日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
为StreamHandler和RotatingFileHandler设置日志格式
handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
将StreamHandler和RotatingFileHandler添加到日志记录器
logger.addHandler(handler)
logger.addHandler(file_handler)
记录日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
以上示例展示了如何配置日志记录器,包括设置日志级别、格式以及输出到终端和文件,并且如何实现日志文件的自动旋转。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/72766.html