You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.4 KiB
51 lines
1.4 KiB
import json
|
|
import logging
|
|
|
|
from logger import get_logger
|
|
|
|
TELEMETRY_LOG_NAME = 'sa-itsi-driftdetection-telemetry'
|
|
|
|
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 get_logger(
|
|
name=TELEMETRY_LOG_NAME,
|
|
level=logging.INFO,
|
|
formatter=formatter
|
|
)
|
|
|
|
|
|
# Set up logger with a custom JSON formatter
|
|
logger = get_json_logger()
|
|
|
|
|
|
def log_telemetry(**kwargs):
|
|
"""
|
|
Logs telemetry data directly as a dictionary at the info level.
|
|
"""
|
|
logger.info(kwargs) # Pass dictionary directly to logger
|