网站做压测,广东新闻头条最新消息,电商详情页设计模板,网上推广的平台有哪些前言#xff1a;
Python的logging模块是内建的、功能强大的日志系统#xff0c;可通过简单的配置#xff0c;就能满足基本到复杂的日志管理需求。它可以让你以各种方式记录错误、调试信息、以及其他运行时的信息#xff0c;这些都是应用程序健壯性、可维护性的关键。
1 基…前言
Python的logging模块是内建的、功能强大的日志系统可通过简单的配置就能满足基本到复杂的日志管理需求。它可以让你以各种方式记录错误、调试信息、以及其他运行时的信息这些都是应用程序健壯性、可维护性的关键。
1 基础概念
在深入了解之前先理解logging模块的几个基本概念 Logger应用程序代码直接使用的接口。 Handler用于将日志记录log record发送到合适的目的地。 Formatter用于配置日志信息的最终顺序、结构和内容。 Level日志级别如DEBUG、INFO、WARNING、ERROR、CRITICAL等用于区分日志的重要性。 debug: 用于开发者调试显示变量等详细信息; 正常版本不应包含 info: 通知用户关键的正常行为如“主库添加成功”;用简单、明确的语言记录 warning:不正常或偏离预期的行为; 不会立即影响系统但具有潜在风险 critical:未知的不正常行为超出已知容错可能会影响程序未来运行 error: 无法修复的严重错误必须立即处理并可能需要停止程序。
1.1 简单的示例
#!/usr/bin/env python
# codingutf-8# Time : 2024/4/8
# Author : Summer
# File : logger.py
# describe:import logging# 配置日志等级为INFO日志格式等
logging.basicConfig(levellogging.INFO, format%(asctime)s - %(name)s - %(levelname)s - %(message)s)# 获取logger对象
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.)
logger.critical(This is a critical message.)对于简单的脚本或小型项目basicConfig方法的配置足够使用。但是对于更复杂的日志需求可能需要配置多个handler、formatter并灵活地应用不同的日志级别。
2 彩色日志
logging模块默认不支持彩色日志。要实现彩色日志可以自定义Formatter在输出的文本中加入终端色彩代码。一个简单的方式是使用colorlog包它是一个允许彩色配置输出的第三方库。 colorlog的使用
#!/usr/bin/env python
# codingutf-8# Time : 2024/4/8
# Author : Summer
# File : logger.py
# describe:import colorlog
import logging# 创建logger对象
logger logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)# 创建handler
ch logging.StreamHandler()# 创建带颜色的formatter
formatter colorlog.ColoredFormatter(%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s,datefmtNone,resetTrue,log_colors{DEBUG: cyan,INFO: green,WARNING: yellow,ERROR: red,CRITICAL: red,bg_white,},secondary_log_colors{},style%
)# 设置handler的formatter
ch.setFormatter(formatter)# 将handler添加到logger中
logger.addHandler(ch)# 记录示例日志
logger.debug(Debug message)
logger.info(Info message)
logger.warning(Warning message)
logger.error(Error message)
logger.critical(Critical message) 在这里ColoredFormatter允许指定日志级别的颜色改善日志的可读性。上述例子在日志级别、消息文本周围加入了颜色。 这只是logging模块以及如何实现彩色日志输出的一个简介。根据不同的日志策略和复杂性logging模块提供的灵活性和功能可以大大帮助提升应用程序的质量和可维护性。
3 完整代码
下面给大家提供一个完整的封装希望对大家有用
#!/usr/bin/env python
# codingutf-8# Time : 2024/4/8
# Author : Summer
# File : logger.py
# describe:import logging
import os
import time# ANSI escape codes for colors in terminal
class TerminalColor:RED \033[91mGREEN \033[92mYELLOW \033[93mRESET \033[0mBLUE \033[94mMAGENTA \033[95mCYAN \033[96mWHITE \033[97mclass ColorFormatter(logging.Formatter):COLORS {logging.DEBUG: TerminalColor.CYAN,logging.INFO: TerminalColor.GREEN,logging.WARNING: TerminalColor.YELLOW,logging.ERROR: TerminalColor.RED,logging.CRITICAL: TerminalColor.RED TerminalColor.WHITE}def format(self, record):level_color self.COLORS.get(record.levelno)reset_color TerminalColor.RESETmessage super(ColorFormatter, self).format(record)return level_color message reset_colorlog_path os.path.join(os.path.dirname(__file__), logs)
if not os.path.exists(log_path):os.mkdir(log_path)class Log(object):def __init__(self, log_name):self.log_name log_nameself.logname os.path.join(log_path, %s_%s.log % (self.log_name, time.strftime(%Y_%m_%d)))self.logger logging.getLogger()self.logger.setLevel(logging.DEBUG)formatter ColorFormatter([%(asctime)s] - %(filename)s] - %(levelname)s: %(message)s)# Create file handlerfh logging.FileHandler(self.logname, a, encodingutf-8)fh.setLevel(logging.DEBUG)fh.setFormatter(formatter)# Create console handler with color supportch logging.StreamHandler()ch.setLevel(logging.DEBUG)ch.setFormatter(formatter)self.logger.addHandler(fh)self.logger.addHandler(ch)def debug(self, message):self.logger.debug(message)def info(self, message):self.logger.info(message)def warning(self, message):self.logger.warning(message)def error(self, message):self.logger.error(message)def critical(self, message):self.logger.critical(message)if __name__ __main__:log Log(Confluence)log.info(---测试开始----)log.info(操作步骤1,2,3)log.warning(----测试结束----)log.error(----测试中有错误----)log.critical(----测试中有致命错误----) 注意日志颜色通常只在兼容ANSI颜色代码的终端内生效而在日志文件中是不可见的。此外某些操作系统或终端可能不支持或默认关闭了颜色输出这就需要相应地配置环境或更换支持颜色的终端。