在Python中,你可以使用内置的`logging`模块来记录日志。下面是一个基本的示例,展示了如何配置和使用日志记录器:
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`:
import loggingfrom 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')
以上示例展示了如何配置日志记录器,包括设置日志级别、格式以及输出到终端和文件,并且如何实现日志文件的自动旋转。

