fix: Address high-severity bandit issues
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
DSS Structured Logger - JSON-based logging for AI-consumable audit trails
|
||||
DSS Structured Logger - JSON-based logging for AI-consumable audit trails.
|
||||
|
||||
Provides structured, machine-readable logging in JSONL format (one JSON object per line).
|
||||
All DSS operations are logged with consistent fields for analysis, debugging, and compliance.
|
||||
@@ -27,11 +27,11 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
from contextlib import contextmanager
|
||||
import threading
|
||||
|
||||
# Thread-local storage for context
|
||||
_context = threading.local()
|
||||
@@ -51,7 +51,7 @@ class DSSJSONFormatter(logging.Formatter):
|
||||
"""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
"""Format log record as single-line JSON"""
|
||||
"""Format log record as single-line JSON."""
|
||||
|
||||
# Build base log entry
|
||||
log_entry = {
|
||||
@@ -100,8 +100,10 @@ class DSSLogger(logging.Logger):
|
||||
as keyword arguments for structured logging.
|
||||
"""
|
||||
|
||||
def _log_with_extra(self, level: int, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Internal method to log with extra structured data"""
|
||||
def _log_with_extra(
|
||||
self, level: int, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs
|
||||
):
|
||||
"""Internal method to log with extra structured data."""
|
||||
if extra:
|
||||
# Store extra data in a custom attribute
|
||||
extra_record = {"extra_data": extra}
|
||||
@@ -110,23 +112,23 @@ class DSSLogger(logging.Logger):
|
||||
super()._log(level, msg, (), **kwargs)
|
||||
|
||||
def debug(self, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Log DEBUG message with optional extra data"""
|
||||
"""Log DEBUG message with optional extra data."""
|
||||
self._log_with_extra(logging.DEBUG, msg, extra, **kwargs)
|
||||
|
||||
def info(self, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Log INFO message with optional extra data"""
|
||||
"""Log INFO message with optional extra data."""
|
||||
self._log_with_extra(logging.INFO, msg, extra, **kwargs)
|
||||
|
||||
def warning(self, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Log WARNING message with optional extra data"""
|
||||
"""Log WARNING message with optional extra data."""
|
||||
self._log_with_extra(logging.WARNING, msg, extra, **kwargs)
|
||||
|
||||
def error(self, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Log ERROR message with optional extra data"""
|
||||
"""Log ERROR message with optional extra data."""
|
||||
self._log_with_extra(logging.ERROR, msg, extra, **kwargs)
|
||||
|
||||
def critical(self, msg: str, extra: Optional[Dict[str, Any]] = None, **kwargs):
|
||||
"""Log CRITICAL message with optional extra data"""
|
||||
"""Log CRITICAL message with optional extra data."""
|
||||
self._log_with_extra(logging.CRITICAL, msg, extra, **kwargs)
|
||||
|
||||
|
||||
@@ -182,7 +184,9 @@ def get_logger(name: str, log_file: Optional[str] = None) -> DSSLogger:
|
||||
|
||||
|
||||
@contextmanager
|
||||
def LogContext(session_id: Optional[str] = None, tool: Optional[str] = None, operation: Optional[str] = None):
|
||||
def LogContext(
|
||||
session_id: Optional[str] = None, tool: Optional[str] = None, operation: Optional[str] = None
|
||||
):
|
||||
"""
|
||||
Context manager for adding structured context to log entries.
|
||||
|
||||
@@ -259,12 +263,15 @@ class PerformanceLogger:
|
||||
self.end_time = None
|
||||
|
||||
def start(self):
|
||||
"""Mark operation start time"""
|
||||
"""Mark operation start time."""
|
||||
self.start_time = datetime.now(timezone.utc)
|
||||
self.logger.debug(f"Started: {self.operation}", extra={
|
||||
"operation": self.operation,
|
||||
"start_time": self.start_time.isoformat(),
|
||||
})
|
||||
self.logger.debug(
|
||||
f"Started: {self.operation}",
|
||||
extra={
|
||||
"operation": self.operation,
|
||||
"start_time": self.start_time.isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
def end(self, extra: Optional[Dict[str, Any]] = None):
|
||||
"""
|
||||
@@ -276,7 +283,9 @@ class PerformanceLogger:
|
||||
self.end_time = datetime.now(timezone.utc)
|
||||
|
||||
if self.start_time is None:
|
||||
self.logger.warning(f"Performance logger end() called without start() for: {self.operation}")
|
||||
self.logger.warning(
|
||||
f"Performance logger end() called without start() for: {self.operation}"
|
||||
)
|
||||
return
|
||||
|
||||
duration_ms = (self.end_time - self.start_time).total_seconds() * 1000
|
||||
@@ -294,7 +303,9 @@ class PerformanceLogger:
|
||||
self.logger.info(f"Completed: {self.operation}", extra=perf_data)
|
||||
|
||||
|
||||
def configure_log_rotation(log_dir: Optional[Path] = None, max_bytes: int = 10 * 1024 * 1024, backup_count: int = 5):
|
||||
def configure_log_rotation(
|
||||
log_dir: Optional[Path] = None, max_bytes: int = 10 * 1024 * 1024, backup_count: int = 5
|
||||
):
|
||||
"""
|
||||
Configure log rotation for DSS log files.
|
||||
|
||||
@@ -325,19 +336,19 @@ def configure_log_rotation(log_dir: Optional[Path] = None, max_bytes: int = 10 *
|
||||
|
||||
# Add rotating file handler
|
||||
rotating_handler = RotatingFileHandler(
|
||||
str(log_file),
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8"
|
||||
str(log_file), maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8"
|
||||
)
|
||||
rotating_handler.setFormatter(DSSJSONFormatter())
|
||||
logger.addHandler(rotating_handler)
|
||||
|
||||
logger.info("Log rotation configured", extra={
|
||||
"max_bytes": max_bytes,
|
||||
"backup_count": backup_count,
|
||||
"log_file": str(log_file),
|
||||
})
|
||||
logger.info(
|
||||
"Log rotation configured",
|
||||
extra={
|
||||
"max_bytes": max_bytes,
|
||||
"backup_count": backup_count,
|
||||
"log_file": str(log_file),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# Example usage (can be removed in production)
|
||||
@@ -356,6 +367,7 @@ if __name__ == "__main__":
|
||||
perf.start()
|
||||
# Simulate work
|
||||
import time
|
||||
|
||||
time.sleep(0.1)
|
||||
perf.end(extra={"tokens_found": 100})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user