| 34 | * @implements {ICompactTransport} |
| 35 | */ |
| 36 | export class CompactTransport implements ICompactTransport { |
| 37 | private sessionStart: number |
| 38 | private lastTimestamp: number |
| 39 | private filePath?: string |
| 40 | private initialized: boolean = false |
| 41 | |
| 42 | /** |
| 43 | * Creates a new CompactTransport instance |
| 44 | * @param config - Optional transport configuration |
| 45 | */ |
| 46 | constructor(readonly config: CompactTransportConfig = DEFAULT_CONFIG) { |
| 47 | this.sessionStart = Date.now() |
| 48 | this.lastTimestamp = this.sessionStart |
| 49 | |
| 50 | if (config.fileOutput?.enabled) { |
| 51 | this.filePath = config.fileOutput.path |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Ensures the log file is initialized with proper directory structure and session start marker |
| 57 | * @private |
| 58 | * @throws {Error} If file initialization fails |
| 59 | */ |
| 60 | private ensureInitialized(): void { |
| 61 | if (this.initialized || !this.filePath) return |
| 62 | |
| 63 | try { |
| 64 | mkdirSync(dirname(this.filePath), { recursive: true }) |
| 65 | writeFileSync(this.filePath, "", { flag: "w" }) |
| 66 | |
| 67 | const sessionStart = { |
| 68 | t: 0, |
| 69 | l: "info", |
| 70 | m: "Log session started", |
| 71 | d: { timestamp: new Date(this.sessionStart).toISOString() }, |
| 72 | } |
| 73 | writeFileSync(this.filePath, JSON.stringify(sessionStart) + "\n", { flag: "w" }) |
| 74 | |
| 75 | this.initialized = true |
| 76 | } catch (err) { |
| 77 | throw new Error(`Failed to initialize log file: ${(err as Error).message}`) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Writes a log entry to configured outputs (console and/or file) |
| 83 | * @param entry - The log entry to write |
| 84 | */ |
| 85 | write(entry: CompactLogEntry): void { |
| 86 | const deltaT = entry.t - this.lastTimestamp |
| 87 | this.lastTimestamp = entry.t |
| 88 | |
| 89 | const compact = { |
| 90 | ...entry, |
| 91 | t: deltaT, |
| 92 | } |
| 93 |
nothing calls this directly
no outgoing calls
no test coverage detected