#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # @Version : Python 3.11.4 # @Software : Sublime Text 4 # @Author : StudentCWZ # @Email : StudentCWZ@outlook.com # @Date : 2023/10/28 18:21 # @File : format.py # @Description : """ import json def serialize(record: dict) -> str: """ Serializes the log record into a formatted JSON string. :param record: A dictionary that represents the log record. :return: A JSON string with the formatted log record. """ # Extract and format the timestamp from the record time_stamp = record["time"] time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S") # Construct a subset of the log record with desired fields subset = { "time": time_stamp, "message": record["message"], "level": record["level"].name.lower(), "tag": "{}:{}".format(record["file"].path, record["line"]), "field": {"data": record["extra"].get("data", {})}, } return json.dumps(subset, ensure_ascii=False) def patching(record: dict) -> str: """ Patches the log record by serializing it and adding it to the 'extra' field. :param record: A dictionary that represents the log record. :return: A string that represents the patched log record. """ record["extra"]["serialized"] = serialize(record) return "{extra[serialized]}\n"