Encapsulating Log Recording in Pytest: Date-Based Log Files, Colored Levels, and Utility Functions
This article demonstrates how to encapsulate logging within the Pytest framework by creating daily log files, applying color-coded log levels, configuring flexible output formats, and providing a reusable ApiLog class for streamlined logging in API automation tests.
In interface automation testing, logging is essential for tracing execution, debugging, and analyzing results; this article explains how to encapsulate logging in the Pytest framework, including daily log file rotation and colored log levels for clearer console output.
Logging encapsulation goals : generate a separate log file for each day, assign distinct colors to different log levels, and allow flexible configuration of log level and format.
Implementation steps :
(1) Import logging libraries :
import logging
import colorlog
from datetime import datetime
import os(2) Define a logger :
logger = logging.getLogger(__name__)(3) Configure the logger – set up a log‑color map, create a logs directory, build a filename based on the current date, and create file and console handlers with appropriate formatters:
# Log color configuration
log_colors_config = {
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
log_path = os.path.join(os.path.dirname(__file__), 'logs')
if not os.path.exists(log_path):
os.mkdir(log_path)
log_file_name = datetime.now().strftime("%Y-%m-%d") + '.log'
log_file_path = os.path.join(log_path, log_file_name)
file_handler = logging.FileHandler(log_file_path, mode='a', encoding='utf-8')
file_formatter = logging.Formatter('[%(asctime)s] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
file_handler.setFormatter(file_formatter)
console_handler = logging.StreamHandler()
console_formatter = colorlog.ColoredFormatter('%(log_color)s[%(asctime)s] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S', log_colors=log_colors_config)
console_handler.setFormatter(console_formatter)
logger.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG)
file_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
logger.addHandler(file_handler)(4) Wrap logging calls in a utility class :
class ApiLog:
@staticmethod
def debug(message):
logger.debug(message)
@staticmethod
def info(message):
logger.info(message)
@staticmethod
def warning(message):
logger.warning(message)
@staticmethod
def error(message):
logger.error(message)
@staticmethod
def critical(message):
logger.critical(message)(5) Use the wrapper in test cases :
def test_example():
ApiLog.info("测试开始")
ApiLog.debug("执行测试步骤")
ApiLog.warning("这是一个警告")
ApiLog.error("这是一个错误")
ApiLog.critical("这是一个严重错误")By following these steps, developers can integrate a robust, color‑enhanced logging system into their Pytest‑based API automation framework, improving readability, maintainability, and debugging efficiency.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.