当前位置:   article > 正文

Python---日志记录_python 日志记录

python 日志记录

Python日志记录器是Python标准库中的一部分,它允许将消息和问题记录到日志中,以便在需要时进行查看和分析。可以使用基本配置或自定义配置来设置日志记录器,并使用不同级别的日志记录来掌握应用程序的运行情况。

一、标准库logging模块

  1. import logging
  2. logging.basicConfig(filename='example.log', level=logging.DEBUG)
  3. logging.debug('This is a debug message')
  4. logging.info('This is an info message')
  5. logging.warning('This is a warning message')
  6. logging.error('This is an error message')
  7. logging.critical('This is a critical message')
'
运行
  1. import logging
  2. LOG_FORMAT = "%(asctime)s - %(levelname)s %(funcName)s - %(message)s"
  3. logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG)
  4. def print_hi(name):
  5. logging.debug('this is print_hi debug')
  6. logging.info('this is print_hi info')
  7. logging.warning('this is print_hi warning')
  8. logging.error('this is print_hi error')
  9. logging.critical('this is print_hi critical')
  10. print(f'Hi print_hi, {name}')
  11. if __name__ == '__main__':
  12. print_hi('XieJava')
'
运行

在此示例中,我们设置了一个日志记录器并将其配置为写入到“example.log”文件中。然后记录了五条不同级别的日志消息。输出到日志文件的内容将如下所示:

  1. DEBUG:root:This is a debug message
  2. INFO:root:This is an info message
  3. WARNING:root:This is a warning message
  4. ERROR:root:This is an error message
  5. CRITICAL:root:This is a critical message

二、三方库loguru模块

  1. from loguru import logger
  2. # 按照时间切割
  3. logger.add("logs/{time:YYYY-MM-DD}.log", rotation="00:00", compression="zip")
  4. # 按照大小切割
  5. logger.add("logs/{time:YYYY-MM-DD}.log", rotation="30 M", compression="zip")
  6. logger.info("This is a test log message")

此示例中在日志文件夹下创建日志文件,并且在每天凌晨自动切割日志,并且将旧日志文件压缩保存。

三、logging模块,创建日志记录器

  1. from loguru import logger
  2. from logging.handlers import TimedRotatingFileHandler
  3. handler = TimedRotatingFileHandler(os.path.join(LOG_PATH, "flask.log"), when="midnight",
  4. backupCount=7, encoding='utf-8')
  5. # 将 TimedRotatingFileHandler 对象添加到 logger 对象中
  6. logger.add(handler)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/810438
推荐阅读
相关标签
  

闽ICP备14008679号