赞
踩
Python日志记录器是Python标准库中的一部分,它允许将消息和问题记录到日志中,以便在需要时进行查看和分析。可以使用基本配置或自定义配置来设置日志记录器,并使用不同级别的日志记录来掌握应用程序的运行情况。
一、标准库logging模块
- import logging
-
- logging.basicConfig(filename='example.log', level=logging.DEBUG)
-
- 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')
'运行
- import logging
-
- LOG_FORMAT = "%(asctime)s - %(levelname)s %(funcName)s - %(message)s"
- logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG)
-
-
- def print_hi(name):
- logging.debug('this is print_hi debug')
- logging.info('this is print_hi info')
- logging.warning('this is print_hi warning')
- logging.error('this is print_hi error')
- logging.critical('this is print_hi critical')
- print(f'Hi print_hi, {name}')
-
-
- if __name__ == '__main__':
- print_hi('XieJava')
-
'运行
在此示例中,我们设置了一个日志记录器并将其配置为写入到“example.log”文件中。然后记录了五条不同级别的日志消息。输出到日志文件的内容将如下所示:
- DEBUG:root:This is a debug message
- INFO:root:This is an info message
- WARNING:root:This is a warning message
- ERROR:root:This is an error message
- CRITICAL:root:This is a critical message
二、三方库loguru模块
- from loguru import logger
-
- # 按照时间切割
- logger.add("logs/{time:YYYY-MM-DD}.log", rotation="00:00", compression="zip")
- # 按照大小切割
- logger.add("logs/{time:YYYY-MM-DD}.log", rotation="30 M", compression="zip")
- logger.info("This is a test log message")
此示例中在日志文件夹下创建日志文件,并且在每天凌晨自动切割日志,并且将旧日志文件压缩保存。
三、logging模块,创建日志记录器
- from loguru import logger
- from logging.handlers import TimedRotatingFileHandler
-
- handler = TimedRotatingFileHandler(os.path.join(LOG_PATH, "flask.log"), when="midnight",
- backupCount=7, encoding='utf-8')
- # 将 TimedRotatingFileHandler 对象添加到 logger 对象中
- logger.add(handler)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。