"""
JSON logging formatter module.

This module defines the JsonFormatter class, which formats log messages
as JSON objects. It adds metadata such as timestamps, log levels, event
IDs, categories, and scopes.

Classes:
    JsonFormatter(logging.Formatter): Formats log records as JSON objects.
"""


import json
import logging

from datetime import datetime, UTC

from jt_logger import _util


class JsonFormatter(logging.Formatter):
    """
    A Python logging formatter that formats log records as JSON objects.
    """

    def format(self, record):
        """
        Format a log record as a JSON object.

        Args:
            record (logging.LogRecord): The log record to format.

        Returns:
            str: A JSON-formatted string representing the log record.
        """

        log_record = {
            'Timestamp': datetime.fromtimestamp(record.created, UTC).isoformat(),
            'EventId': record.__dict__.get('event_id', 0),
            'LogLevel': record.levelname,
            'Category': _util._get_category(),
            'Message': record.getMessage(),
            'State': record.__dict__.get('state', {}),
            'Scopes': _util._get_scope_stack()
        }
        return json.dumps(log_record, default=str)


# That's all folks...
