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 262 263 264 265 266 267 268 269 270 271 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1103x 1103x 1103x 1103x 1103x 1103x 1103x 1103x 1037x 1037x 13x 13x 13x 13x 9x 9x 25x 25x 6x 6x | import fs, { type WriteStream } from 'fs';
import * as path from 'path';
import CoreLogger from '../../classes/CoreLogger';
import type { ICoreKernel } from '../../lib';
import { DefaultLogger, type DefaultLogMode } from './DefaultLogger';
import { XUtil } from '../../utils';
export type AdvancedLoggerMode = 'string' | 'json';
export type AdvancedLoggerOptions = {
fileFormat?: AdvancedLoggerMode;
logLevel?: string;
/** Name of the active log file. Default: `main.log` */
fileName?: string;
/** Rotate once the active file passes this size in bytes. Default: 10 MiB */
maxFileSize?: number;
/** How many rotated files to keep (main.1.log … main.N.log). Default: 5 */
maxFiles?: number;
};
export type AdvancedJsonLog = {
ts: string;
mode: DefaultLogMode;
channel: string;
msg: unknown[];
};
/** Hard cap on lines buffered while a rotation is in flight. */
const MAX_QUEUE = 10_000;
function logReplacer(_: string, value: unknown): unknown {
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Error) {
return { name: value.name, message: value.message, stack: value.stack };
}
return value;
}
function toJsonLine(data: Omit<AdvancedJsonLog, 'ts'>): string {
try {
return JSON.stringify({ ts: XUtil.getTimeStamp(), ...data }, logReplacer);
} catch {
return JSON.stringify({
ts: XUtil.getTimeStamp(),
...data,
msg: ['<unserializable>'],
});
}
}
export class AdvancedLogger extends CoreLogger {
logPath: string;
consoleLog: DefaultLogger;
fileFormat: AdvancedLoggerMode;
stream: WriteStream;
private readonly fileName: string;
private readonly maxFileSize: number;
private readonly maxFiles: number;
private size = 0;
private fileDisabled = false;
private rotating = false;
private queue: string[] = [];
constructor(
kernel: ICoreKernel<any>,
options: AdvancedLoggerMode | AdvancedLoggerOptions = 'string',
logLevel?: string,
) {
const opts: AdvancedLoggerOptions =
typeof options === 'string' ? { fileFormat: options, logLevel } : options;
super(opts.logLevel ?? logLevel);
this.consoleLog = new DefaultLogger(opts.logLevel ?? logLevel);
this.fileFormat = opts.fileFormat ?? 'string';
this.fileName = opts.fileName ?? 'main.log';
this.maxFileSize = opts.maxFileSize ?? 10 * 1024 * 1024;
this.maxFiles = Math.max(1, opts.maxFiles ?? 5);
const store = kernel.getConfigStore();
const lPath = store.get('GLOBAL_PATH_LOG');
const basePath = lPath || store.get('GLOBAL_PATH_TEMP');
Iif (!basePath) {
throw new Error('No log path');
}
XUtil.createFolderIfNotExist(basePath);
this.logPath = basePath;
this.stream = this.openStream();
// A file left over from the last run counts towards the limit, otherwise a
// process that restarts often would never rotate.
Iif (this.size >= this.maxFileSize) {
this.rotate();
}
}
private activePath(): string {
return path.join(this.logPath, this.fileName);
}
private rotatedPath(index: number): string {
const ext = path.extname(this.fileName);
const base = path.basename(this.fileName, ext);
return path.join(this.logPath, `${base}.${index}${ext}`);
}
private openStream(): WriteStream {
const target = this.activePath();
try {
this.size = fs.statSync(target).size;
} catch {
this.size = 0;
}
const stream = fs.createWriteStream(target, { flags: 'a' });
// An unhandled 'error' on a stream is an uncaught exception - a full disk
// must not take down the process, so fall back to console-only logging.
stream.on('error', (e) => {
this.fileDisabled = true;
this.queue = [];
this.consoleLog.error('AdvancedLogger', 'log file write failed', e);
});
this.stream = stream;
return stream;
}
/**
* main.4.log -> main.5.log, ... , main.log -> main.1.log
* The oldest file is dropped.
*/
private shiftFiles(): void {
for (let i = this.maxFiles; i >= 1; i -= 1) {
const src = this.rotatedPath(i);
if (!fs.existsSync(src)) {
// eslint-disable-next-line no-continue
continue;
}
if (i === this.maxFiles) {
fs.unlinkSync(src);
} else {
fs.renameSync(src, this.rotatedPath(i + 1));
}
}
if (fs.existsSync(this.activePath())) {
fs.renameSync(this.activePath(), this.rotatedPath(1));
}
}
private rotate(): void {
if (this.rotating || this.fileDisabled) {
return;
}
this.rotating = true;
const old = this.stream;
// end() flushes everything still queued in the stream before 'finish',
// so no line is lost and no rename happens on a file with pending writes
// (which would fail on Windows).
old.end(() => {
try {
this.shiftFiles();
} catch (e) {
this.consoleLog.error('AdvancedLogger', 'log rotation failed', e);
}
try {
this.openStream();
} catch (e) {
this.fileDisabled = true;
this.consoleLog.error('AdvancedLogger', 'reopening log failed', e);
}
this.rotating = false;
const pending = this.queue;
this.queue = [];
pending.forEach((line) => this.writeLine(line));
});
}
private writeLine(line: string): void {
Iif (this.fileDisabled) {
return;
}
Iif (this.rotating) {
if (this.queue.length < MAX_QUEUE) {
this.queue.push(line);
}
return;
}
this.size += Buffer.byteLength(line, 'utf-8');
this.stream.write(line, 'utf-8');
Iif (this.size >= this.maxFileSize) {
this.rotate();
}
}
private writeToFile(
mode: DefaultLogMode,
channel: string,
...args: unknown[]
) {
Iif (this.fileDisabled) {
return;
}
const line =
this.fileFormat === 'string'
? this.consoleLog.format(mode, channel, ...args)
: toJsonLine({ mode, channel, msg: args });
this.writeLine(`${line}\n`);
}
/** Force a rotation regardless of the current file size. */
rotateNow(): void {
this.rotate();
}
/** Flush and close the active stream, e.g. on kernel shutdown. */
close(): Promise<void> {
return new Promise((resolve) => {
this.fileDisabled = true;
this.queue = [];
this.stream.end(() => resolve());
});
}
debug(channel: string, ...ags: unknown[]): void {
this.consoleLog.debug(channel, ...ags);
this.writeToFile('D', channel, ...ags);
}
error(channel: string, ...ags: unknown[]): void {
this.consoleLog.error(channel, ...ags);
this.writeToFile('E', channel, ...ags);
}
info(channel: string, ...ags: unknown[]): void {
this.consoleLog.info(channel, ...ags);
this.writeToFile('I', channel, ...ags);
}
log(channel: string, ...ags: unknown[]): void {
this.consoleLog.log(channel, ...ags);
this.writeToFile('L', channel, ...ags);
}
verbose(channel: string, ...ags: unknown[]): void {
this.consoleLog.verbose(channel, ...ags);
this.writeToFile('V', channel, ...ags);
}
warn(channel: string, ...ags: unknown[]): void {
this.consoleLog.warn(channel, ...ags);
this.writeToFile('W', channel, ...ags);
}
}
|