UNPKG

kaven-utils

Version:

Utils for Node.js.

85 lines (84 loc) 2.59 kB
/******************************************************************** * @author: Kaven * @email: kaven@wuwenkai.com * @website: http://blog.kaven.xyz * @file: [Kaven-Utils] /src/KavenLoggerFile.ts * @create: 2022-06-26 01:49:21.007 * @modify: 2023-12-06 11:15:47.866 * @version: 5.4.0 * @times: 22 * @lines: 99 * @copyright: Copyright © 2022-2023 Kaven. All Rights Reserved. * @description: [description] * @license: [license] ********************************************************************/ import { LogLevel } from "kaven-basic"; import { createWriteStream } from "node:fs"; import { dirname } from "node:path"; import { GetEntryDirectory } from "./KavenUtility.Constant.js"; import { AppendPathToDirectory, MakeDirectory } from "./KavenUtility.FileSystem.js"; /** * @since 4.3.0 * @version 2023-12-05 */ export class KavenLoggerFile { file; levels = Object.values(LogLevel); stream; constructor(options) { this.file = AppendPathToDirectory(GetEntryDirectory(), options.file); if (options.levels) { if (options.levels.length === 0) { throw new Error("Invalid log levels"); } this.levels = options.levels; } this.SaveWithAnsiColor = options.saveWithAnsiColor; } SaveWithAnsiColor; get Options() { return { file: this.file, levels: this.levels, saveWithAnsiColor: this.SaveWithAnsiColor, }; } get File() { return this.file; } get Stream() { return this.stream; } Has(level) { return this.levels.includes(level); } async Open() { if (this.stream) { throw new Error(`file already opened: ${this.file}`); } await MakeDirectory(dirname(this.file)); this.stream = createWriteStream(this.file, { flags: "a" }); } async Close() { await new Promise((resolve, reject) => { if (this.stream) { this.stream.close(err => { /* istanbul ignore next */ if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); this.stream = undefined; } ToString() { return `Levels:${this.levels.join("|")}, SaveWithAnsiColor:${this.SaveWithAnsiColor}, ${this.file}`; } }