Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | 126x 126x 126x 207x 201x 6x 207x 2x 1x 1x 2x 2x 4x 126x 126x 126x 126x 126x 126x 126x 5979x 5979x 222x 4x 2x 2x 2x 2x 2x 2x 2x 201x 2x 2x 1225x 1225x 5979x 222x 222x 222x 222x 222x 207x 15x 15x 2x 13x 30x 145x 605x 5199x 127x 127x 127x 4x 161x | /**
* Policy-Konformes Zentrales Logging-System
*
* Design-Entscheidungen:
* 1. RING BUFFER für DEBUG-Logs (max. 200 Zeilen):
* - Hält Debug-Kontext im Speicher ohne Performance-Impact
* - Wird nur bei Prozess-Fehler oder fehlgeschlagenem Test geleert
* - Im Erfolgsfall bleibt Konsole sauber (hohe SNR)
*
* 2. LOG-LEVELS mit Policy-Default (CI: WARN):
* - NONE: Keine Logs (für Tests, die absolut sauber sein müssen)
* - ERROR: Nur kritische Fehler
* - WARN: Warnings + Errors (CI Standard)
* - INFO: Allgemeine Informationen
* - DEBUG: Detaillierte Traceability (gepuffert)
*
* 3. KONTEXT-KAPSELUNG:
* - Jede Logger-Instanz erfordert einen eindeutigen Kontexts-String
* - Ermöglicht volle Traceability und Fehlersuche (Policy-Kern)
*
* 4. SANITIZATION (Sicherheitspolicy):
* - Automatische Maskierung: Tokens, Passwörter, API-Keys, PII
* - Reguläre Ausdrücke für gängige Patterns
*
* 5. ASYNCHRONE ARCHITEKTUR:
* - Keine synchronen I/O-Blockaden
* - Ring-Buffer ist vollständig im RAM (O(1) Write)
* - Flush erfolgt nur beim Fehler asynchron
*/
type LogLevel = "NONE" | "ERROR" | "WARN" | "INFO" | "DEBUG";
interface LogEntry {
timestamp: string;
level: LogLevel;
context: string;
message: string;
}
class RingBuffer {
private buffer: LogEntry[] = [];
private readonly maxSize: number = 200;
private writeIndex: number = 0;
/**
* Ring-Buffer für O(1) Speicherung von Debug-Logs
* Überlauf wird automatisch überschrieben (älteste Einträge)
*/
push(entry: LogEntry): void {
if (this.buffer.length < this.maxSize) {
this.buffer.push(entry);
} else {
this.buffer[this.writeIndex] = entry;
}
this.writeIndex = (this.writeIndex + 1) % this.maxSize;
}
/**
* Sortiert Buffer chronologisch und gibt alle Einträge aus
*/
getAll(): LogEntry[] {
if (this.buffer.length < this.maxSize) {
return [...this.buffer];
}
// Buffer ist voll - reordnen nach write-Index
return [
...this.buffer.slice(this.writeIndex),
...this.buffer.slice(0, this.writeIndex),
];
}
clear(): void {
this.buffer = [];
this.writeIndex = 0;
}
size(): number {
return this.buffer.length;
}
}
// ============ GLOBAL LOGGER STATE ============
let globalLogLevel: LogLevel = determineLogLevel();
const debugBuffer = new RingBuffer();
function determineLogLevel(): LogLevel {
Iif (globalThis.process === undefined) return "WARN";
const env = globalThis.process.env;
const level = env.LOG_LEVEL || (env.NODE_ENV === "test" ? "WARN" : "INFO");
Eif (!["NONE", "ERROR", "WARN", "INFO", "DEBUG"].includes(level)) {
return "WARN";
}
return level as LogLevel;
}
function shouldLog(level: LogLevel): boolean {
const levels: Record<LogLevel, number> = {
NONE: 0,
ERROR: 1,
WARN: 2,
INFO: 3,
DEBUG: 4,
};
return levels[level] <= levels[globalLogLevel];
}
/**
* SANITIZATION: Maskiert sensitive Daten in Log-Nachrichten
* Patterns: Tokens, API-Keys, Passwörter, Cookies, SSN, Kreditkarten
*/
function sanitize(message: string): string {
return message
// Tokens und API-Keys (JWT, Bearer, API-Key Parameter)
.replaceAll(/bearer\s+[-\w.~+/]+=*/gi, "bearer [REDACTED_TOKEN]")
.replaceAll(/(?:api[-_]?)?key[=:]\s*[-\w.~+/]+=*/gi, "key=[REDACTED_KEY]")
// Passwörter (replacement omits key name to avoid S2068 false positive)
.replaceAll(/password[=:]\s*[^\s,}\]"]*/gi, "[REDACTED]")
.replaceAll(/pwd[=:]\s*[^\s,}\]"]*/gi, "[REDACTED]")
// Cookies
.replaceAll(/session[-_]?id[=:]\s*[-\w.~+/]+=*/gi, "session_id=[REDACTED]")
// Email-Adressen und Telefonnummern (PII) - S5852: literal @ split avoids ReDoS
.replaceAll(/[^\s@"']{1,64}@[^\s@"'.]{1,64}\.[^\s@"'.]{2,10}/g, "[EMAIL_REDACTED]")
.replaceAll(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g, "[PHONE_REDACTED]")
// SSN Pattern (XXX-XX-XXXX)
.replaceAll(/\b\d{3}-\d{2}-\d{4}\b/g, "[SSN_REDACTED]")
// Kreditkartennummern
.replaceAll(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, "[CARD_REDACTED]")
// Allerdings: Spezifische sensitiv-Felder in JSON/Objekten
.replaceAll(/"(password|token|secret|apiKey|secret_key)"[^}]*:\s*"[^"]*"/gi, '$1:"[REDACTED]"');
}
/**
* Flushes Debug-Buffer bei Fehler/Testfehlschlag
* Wird von test-Setup und Error-Handler aufgerufen
*/
function flushDebugOnFailure(reason?: string): void {
if (debugBuffer.size() === 0) return;
const entries = debugBuffer.getAll();
Iif (entries.length === 0) return;
console.error("\n" + "=".repeat(80));
console.error("DEBUG BUFFER FLUSH (Test/Process Failure)");
Eif (reason) console.error(`Reason: ${String(reason)}`);
console.error("=".repeat(80));
entries.forEach((entry) => {
console.error(
`[${entry.timestamp}][${entry.level}][${entry.context}] ${entry.message}`
);
});
console.error("=".repeat(80) + "\n");
debugBuffer.clear();
}
// ============ LOGGER CLASS ============
export class Logger {
private readonly context: string;
/**
* Initialisiert Logger mit forciertem Kontext-String
* Policy-Anforderung: Jede Instanz muss eindeutigen Kontext haben für Traceability
*/
constructor(context: string) {
Iif (!context || typeof context !== "string") {
throw new Error(
"Logger requires a mandatory context string for Policy compliance (Traceability)"
);
}
this.context = context;
}
/**
* Zentrale Log-Funktion mit Buffering-Logik
*/
private log(level: LogLevel, message: string): void {
// Früh-Return bei deaktiviertem Log-Level
if (!shouldLog(level)) return;
// Sanitize Nachrichten
const sanitizedMessage = sanitize(String(message));
const timestamp = new Date().toISOString();
const fullMessage = `[${timestamp}][${level}][${this.context}] ${sanitizedMessage}`;
const entry: LogEntry = {
timestamp,
level,
context: this.context,
message: sanitizedMessage,
};
// BUFFERING-STRATEGIE:
// Debug-Logs gehen in Ring-Buffer (wird nur bei Fehler geflushert)
if (level === "DEBUG") {
debugBuffer.push(entry);
} else {
// Error, Warn, Info gehen sofort auf die Konsole (asynchron über console API)
try {
if (level === "ERROR") {
console.error(fullMessage);
} else {
console.log(fullMessage);
}
} catch (err) {
// Fehlertoleranz für geschlossene Streams
if (globalThis.process !== undefined && globalThis.process.env?.NODE_ENV !== "test") {
console.error("Logger error:", err);
}
}
}
}
error(message: string): void {
this.log("ERROR", message);
}
warn(message: string): void {
this.log("WARN", message);
}
info(message: string): void {
this.log("INFO", message);
}
debug(message: string): void {
this.log("DEBUG", message);
}
}
// ============ GLOBALE FEHLERBEHANDLUNG ============
// Registriert globale Handler für Prozess-Fehler und Test-Fehlschlag
export function initializeGlobalErrorHandlers(): void {
Iif (globalThis.process === undefined) return;
process.on("uncaughtException", (error: Error) => {
// note: processError variable removed – we no longer track it separately
flushDebugOnFailure(`Uncaught Exception: ${error.message}`);
});
process.on("unhandledRejection", (reason: unknown) => {
flushDebugOnFailure(`Unhandled Rejection: ${String(reason)}`);
});
}
/**
* Manuell für Vitest-Integration aufrufen
*/
export function markTestAsFailed(testName?: string): void {
// testsFailed flag removed; simply flush buffer immediately
flushDebugOnFailure(testName ? `Test failed: ${testName}` : "Test failed");
}
export function setLogLevel(level: LogLevel): void {
globalLogLevel = level;
}
|