Application Tracing

Payload Builder

This is a detailed and didactic documentation of the PayloadBuilder class, designed to standardize telemetry and logging in Python applications.

On this page

    #Overview

    The PayloadBuilder class acts as a factory of messages and data structures. Its main goal is to ensure that, no matter where a log is generated in the system, it has a consistent structure.

    It solves the common problem of disorganized logs, allowing the developer to generate both a human-friendly string (console) and a structured JSON object for NoSQL databases (such as MongoDB), keeping traceability through IDs and metadata.

    #Execution Flow

    The typical flow of using the class follows these steps:

    1. Instantiation: The object is created, usually receiving the global context (log ID, file name or category flags).
    2. Metadata Processing: When recording an event, the class evaluates whether there is extra data (metadata) and how it should be displayed (formatted as indented JSON or as a simple string).
    3. Message Composition: The build_message method concatenates the parts (function, message, context) using a delimiter (|).
    4. Structuring for Persistence: If the log needs to be saved to a database, the build_mongo_payload method organizes the same information into a Python dictionary with precise timestamps.

    #Methods Summary

    MethodResponsibility
    __init__Sets up the builder's context (ID, file, flags and format preferences).
    format_metadata_payloadHandles the display of extra dictionaries, converting them into strings or indented JSON.
    build_messageGenerates the final formatted string for display in console logs or text files.
    build_mongo_payloadCreates a structured dictionary with date/time for insertion into databases.

    #Architecture and Insights

    • Separation of Concerns: The class separates the formatting logic from the transport logic (sending to the database). It does not "log" anything, it only "builds the payload".
    • Traceability (Observability): Using the log_id makes it possible to correlate different log entries that belong to the same request or process.
    • Resilience: The formatting method has a try/except block to ensure that, even if JSON serialization fails, the log does not break the application, falling back to a simple string.

    #Class Details

    #PayloadBuilder Class

    Description

    Responsible for centralizing the composition of log messages, metadata handling and the organization of contextual information to ensure standardization across different outputs (console and database).

    Arguments

    • log_id (str, optional): Unique identifier of the transaction or process.
    • flag (str, optional): Tag for categorization (e.g. "SISTEMA_PAGAMENTO").
    • file_name (str, optional): Name of the Python file where the log occurred.
    • format_metadata (bool): If True, formats metadata dictionaries with JSON indentation.

    #Methods

    #1. format_metadata_payload()

    Description

    Formats the metadata dictionary into a string representation.

    Arguments

    • metadata (Dict[str, Any]): Additional data to include in the log.
    • show_metadata (bool): Flag that authorizes or not the inclusion of the data in the output.

    Returns

    • Optional[str]: Formatted string or None if the data should not be displayed.

    Raises

    • None: Catches exceptions internally and returns the raw string representation (str(metadata)) in case of error.

    Examples

    # Com format_metadata=True na classe
    builder.format_metadata_payload({"status": 200}, True)
    # Retorna: "\n{\n    "status": 200\n}\n"`

    #2. build_message()

    Description

    Assembles the final log string, joining the components with a vertical separator (|).

    Arguments

    • func_name (str): Name of the originating function.
    • message (str): Explanatory text of the log.
    • metadata (Dict): Extra data.
    • show_metadata (bool): Whether the extra data should appear in this message.

    Returns

    • str: Complete, formatted log line.

    Raises

    • ValueError: If no parameter is provided (empty message).

    Examples

    builder.build_message("process_data", "Sucesso", {"items": 5}, True)
    # Retorna: 'process_data() | Sucesso | metadata={'items': 5} | log_id=...'

    #3. build_mongo_payload()

    Description

    Prepares an object ready to be inserted into MongoDB collections or similar databases.

    Arguments

    • level (str): Log level (DEBUG, INFO, ERROR, etc).
    • func_name (str): Originating function.
    • message (str): Log content.
    • metadata (Dict): Structured data.

    Returns

    • Dict[str, Any]: Dictionary containing standardized fields and a timestamp.

    Raises

    • ValueError: If the level is not provided.

    Examples

    builder.build_mongo_payload("error", "save_user", "Falha de conexão", {"db": "prod"})
    # Retorna: {'log_id': '...', 'level': 'ERROR', 'time': '2026-03-18...', ...}

    Source: src/tracing/payload_builder.py

    Esc
    ↑↓navigate Enteropen