• logging 彩色日志 封装类(直接使用即可)


    背景:项目大了,日志混乱。需要进行规范。方便调试和查看。

    功能:封装成工具类方便后续使用。直接保存为单独的py文件即可直接运行。

    语音:python3.7+。推荐3.9

    包含功能:彩色日志,只保留7天数据。日志分级别打印,兼容linux和win系统。

    1. #!/usr/bin/python3
    2. # -*- coding: UTF-8 -*-
    3. """
    4. create:
    5. author:
    6. fuction:
    7. """
    8. import logging
    9. import os
    10. import colorlog
    11. import platform
    12. import re
    13. from logging.handlers import TimedRotatingFileHandler
    14. class Logger(object):
    15. def __init__(self, log_name="test"):
    16. log_colors_config = {
    17. 'DEBUG': 'white', # cyan white
    18. 'INFO': 'green',
    19. 'WARNING': 'yellow',
    20. 'ERROR': 'red',
    21. 'CRITICAL': 'bold_red'
    22. }
    23. self.logger = logging.getLogger(name=log_name)
    24. # 输出到控制台
    25. console_handler = logging.StreamHandler()
    26. # interval 滚动周期,
    27. # when="MIDNIGHT", interval=1 表示每天0点为更新点,每天生成一个文件
    28. # backupCount 表示日志保存个数
    29. current_path = os.path.dirname(__file__)
    30. if platform.system().lower() == "windows":
    31. parent_path = os.path.dirname(current_path) + "\log\debug.log"
    32. else:
    33. parent_path = os.path.dirname(current_path) + "/log/debug.log"
    34. #print(f"current_path={current_path}")
    35. file_handler = TimedRotatingFileHandler(
    36. filename=parent_path, when="MIDNIGHT", interval=1, backupCount=3
    37. )
    38. # 输出到文件
    39. # filename="mylog" suffix设置,会生成文件名为mylog.2020-02-25.log
    40. file_handler.suffix = "%Y-%m-%d.log"
    41. # 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。
    42. file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
    43. # file_handler = logging.FileHandler(filename='debug.log', mode='a', encoding='utf8')
    44. # 日志级别,logger 和 handler以最高级别为准,不同handler之间可以不一样,不相互影响
    45. if platform.system().lower() == "windows":
    46. self.logger.setLevel(logging.DEBUG)
    47. console_handler.setLevel(logging.DEBUG)
    48. file_handler.setLevel(logging.ERROR)
    49. else:
    50. self.logger.setLevel(logging.DEBUG)
    51. console_handler.setLevel(logging.DEBUG)
    52. file_handler.setLevel(logging.ERROR)
    53. # 日志输出格式
    54. pass
    55. # 日志输出格式
    56. file_formatter = logging.Formatter(
    57. fmt='[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
    58. datefmt='%Y-%m-%d %H:%M:%S'
    59. )
    60. console_formatter = colorlog.ColoredFormatter(
    61. fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> line:%(lineno)d %(funcName)s [%(levelname)s] : %(message)s',
    62. datefmt='%Y-%m-%d %H:%M:%S',
    63. log_colors=log_colors_config
    64. )
    65. console_handler.setFormatter(console_formatter)
    66. file_handler.setFormatter(file_formatter)
    67. # 重复日志问题:
    68. # 1、防止多次addHandler;
    69. # 2、loggername 保证每次添加的时候不一样;
    70. # 3、显示完log之后调用removeHandler
    71. if not self.logger.handlers:
    72. self.logger.addHandler(console_handler)
    73. self.logger.addHandler(file_handler)
    74. console_handler.close()
    75. file_handler.close()
    76. def debug(self, msg):
    77. """
    78. 定义输出的颜色debug--white,info--green,warning/error/critical--red
    79. :param msg: 输出的log文字
    80. :return:
    81. """
    82. self.logger.debug(msg)
    83. def info(self, msg):
    84. self.logger.info(msg)
    85. def warning(self, msg):
    86. self.logger.warning(msg)
    87. def error(self, msg):
    88. self.logger.error(msg)
    89. def critical(self, msg):
    90. self.logger.critical(msg)
    91. log = Logger()
    92. if __name__ == '__main__':
    93. log = Logger("test")
    94. log.logger.debug('debug')
    95. log.logger.info('info')
    96. log.logger.warning('warning')
    97. log.logger.error('error')
    98. log.critical('critical')

  • 相关阅读:
    LCR 002. 二进制求和
    云贝教育 |【DSI】Oracle数据库系列课-葵花宝典技术内幕实战课程
    Flutter高仿微信-第51篇-群聊-修改群名
    关于Spring-Boot配置加载顺序解读
    Hello-FPGA CoaXPress 2.0 FPGA HOST IP Core PCIe Demo User Manual
    来看看Python编码规范(PEP 8)
    Postman之接口测试
    第四十一章 持久对象和SQL - Storage
    003微信小程序云开发API数据库-新增集合-删除集合-获取集合信息
    即使密码正确,App Store可能也会不断询问密码,那么如何修复呢
  • 原文地址:https://blog.csdn.net/i_likechard/article/details/133696767