import json import logging import hashlib from util import setup_logging from constants import ENTITY_TITLE class JsonFormatter(logging.Formatter): def format(self, record): """ Formats the log record as a JSON string. """ log_record = { 'created': f"{record.created:.6f}", # Using a formatted string to match '%(created)f' 'pid': record.process, 'asctime': self.formatTime(record, self.datefmt), 'name': record.name, 'logtype': "telemetry" } # Check if the message is a dictionary and merge it into log_record if isinstance(record.msg, dict): log_record.update(record.msg) else: log_record['message'] = record.getMessage() try: return json.dumps(log_record) except TypeError as e: logging.error(f"Failed to serialize log record to JSON: {e}") return str(log_record) def get_json_logger(formatter=JsonFormatter()): return setup_logging.get_logger( name="sa-itsi-at-recommendations-telemetry", level=logging.INFO, formatter=formatter ) # Set up logger with a custom JSON formatter logger = get_json_logger() def hash_value(value: str) -> str: """ Hashes using SHA-256 and returns the hexadecimal representation """ if value is None: return "" return hashlib.sha256(value.encode('utf-8')).hexdigest() def log_telemetry(**kwargs): """ Logs telemetry data directly as a dictionary at the info level. If the `entity_title` key exists in the telemetry data, its value will be hashed. """ if ENTITY_TITLE in kwargs and kwargs[ENTITY_TITLE] is not None: kwargs[ENTITY_TITLE] = hash_value(kwargs[ENTITY_TITLE]) logger.info(kwargs) # Pass dictionary directly to logger