1. 使用`logging.basicConfig`进行基本配置:
import logginglogging.basicConfig(level=logging.DEBUG,format='%(asctime)s[%(levelname)s]%(message)s',handlers=[logging.FileHandler('app.log'),logging.StreamHandler()])logger = logging.getLogger(__name__)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')
2. 使用`logging.getLogger`创建自定义的日志记录器,并添加处理器和格式化器:
import logginglogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)ch = logging.StreamHandler()ch.setLevel(logging.DEBUG)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')ch.setFormatter(formatter)logger.addHandler(ch)logger.debug('debug message')logger.info('info message')logger.warning('warn message')logger.error('error message')
3. 使用`logging.fileConfig`从配置文件加载日志设置:
import logginglogging.fileConfig('logging.conf')logger = logging.getLogger()logger.debug('Debug message from file config')
4. 使用`logging.dictConfig`从字典配置加载日志设置:
import loggingLOGGING_CONFIG = {'version': 1,'disable_existing_loggers': False,'formatters': {'default': {'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}},'handlers': {'console': {'class': 'logging.StreamHandler','level': 'DEBUG','formatter': 'default','stream': 'ext://sys.stdout'},'file': {'class': 'logging.FileHandler','level': 'DEBUG','formatter': 'default','filename': 'app.log'}},'loggers': {'': { root logger'handlers': ['console', 'file'],'level': 'DEBUG','propagate': False}}}logging.config(LOGGING_CONFIG)logger = logging.getLogger()logger.debug('Debug message from dict config')
以上示例展示了如何使用Python的`logging`模块进行日志记录配置。您可以根据需要选择不同的配置方法

