All files / log / file_handler.ts

100.00% Branches 8/8
100.00% Lines 81/81
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
272
273
274
275
276
277
 
x24
 
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
 
 
 
 
x24
 
 
 
 
x47
 
 
 
 
 
x47
 
 
 
 
 
x47
 
 
 
 
 
x47
 
 
 
 
 
x47
 
 
 
 
 
x47
x47
x48
x24
 
 
 
 
 
 
 
x24
x47
x47
 
x47
x47
x47
x47
x47
x47
x47
x47
x47
x47
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
x46
x46
x46
 
x46
 
x46
x46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
x337
 
 
x337
x339
x339
x337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
x350
x350
x358
x358
x350
x354
x350
x672
x672
x672
x350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
x69
x94
x94
x94
x94
 
x94
x94
x94
x69
 
x24
x70
x70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
x49
x49
x49
x49
x49
x24



















































































































































































































































































// Copyright 2018-2025 the Deno authors. MIT license.
import { type LevelName, LogLevels } from "./levels.ts";
import type { LogRecord } from "./logger.ts";
import { BaseHandler, type BaseHandlerOptions } from "./base_handler.ts";
import { writeAllSync } from "@std/io/write-all";
import {
  bufSymbol,
  encoderSymbol,
  filenameSymbol,
  fileSymbol,
  modeSymbol,
  openOptionsSymbol,
  pointerSymbol,
} from "./_file_handler_symbols.ts";

/** Supported log modes for FileHandlerOptions {@linkcode FileHandlerOptions.mode}. */
export type LogMode = "a" | "w" | "x";

/** Options for {@linkcode FileHandler}. */
export interface FileHandlerOptions extends BaseHandlerOptions {
  /**
   * The filename to output to.
   */
  filename: string;
  /**
   * Log mode for the handler. Behavior of the log modes is as follows:
   *
   * - `'a'` - Default mode. Appends new log messages to the end of an existing log
   *   file, or create a new log file if none exists.
   * - `'w'` - Upon creation of the handler, any existing log file will be removed
   *   and a new one created.
   * - `'x'` - This will create a new log file and throw an error if one already
   *   exists.
   *
   * @default {"a"}
   */
  mode?: LogMode;
  /**
   * Buffer size for writing log messages to file, in bytes.
   *
   * @default {4096}
   */
  bufferSize?: number;
}

/**
 * A file-based log handler that writes log messages to a specified file with buffering and optional modes.
 * The logs are buffered for optimized performance, writing to the file only
 * when the buffer is full, on manual .flush() call, during logging of a critical message or when process ends.
 * It is important to note that the file can grow indefinitely.
 *
 * This handler requires `--allow-write` permission on the log file.
 *
 * @example Usage
 * ```ts no-assert
 * import { FileHandler } from "@std/log/file-handler";
 *
 * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
 * handler.setup();
 * handler.log('Hello, world!'); // Buffers the message, or writes it to the file depending on buffer state
 * handler.flush(); // Manually flushes the buffer
 * handler.destroy(); // Closes the file and removes listeners
 * ```
 */
export class FileHandler extends BaseHandler {
  /** Opened file to append logs to.
   *
   * @private
   */
  [fileSymbol]: Deno.FsFile | undefined;
  /** Buffer used to write to file.
   *
   * @private
   */
  [bufSymbol]: Uint8Array;
  /**
   * Current position for pointer.
   *
   * @private
   */
  [pointerSymbol] = 0;
  /**
   * Filename associated with the file being logged.
   *
   * @private
   */
  [filenameSymbol]: string;
  /**
   * Current log mode.
   *
   * @private
   */
  [modeSymbol]: LogMode;
  /**
   * File open options.
   *
   * @private
   */
  [openOptionsSymbol]: Deno.OpenOptions;
  /**
   * Text encoder.
   *
   * @private
   */
  [encoderSymbol]: TextEncoder = new TextEncoder();
  #unloadCallback = (() => {
    this.destroy();
  }).bind(this);

  /**
   * Constructs a new FileHandler instance.
   *
   * @param levelName The level name to log messages at.
   * @param options Options for the handler.
   */
  constructor(levelName: LevelName, options: FileHandlerOptions) {
    super(levelName, options);
    this[filenameSymbol] = options.filename;
    // default to append mode, write only
    this[modeSymbol] = options.mode ?? "a";
    this[openOptionsSymbol] = {
      createNew: this[modeSymbol] === "x",
      create: this[modeSymbol] !== "x",
      append: this[modeSymbol] === "a",
      truncate: this[modeSymbol] !== "a",
      write: true,
    };
    this[bufSymbol] = new Uint8Array(options.bufferSize ?? 4096);
  }

  /**
   * Sets up the file handler by opening the specified file and initializing resources.
   *
   * @example Usage
   * ```ts no-assert
   * import { FileHandler } from "@std/log/file-handler";
   *
   * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
   * handler.setup(); // Opens the file and prepares the handler for logging.
   * handler.destroy();
   * ```
   */
  override setup() {
    this[fileSymbol] = Deno.openSync(
      this[filenameSymbol],
      this[openOptionsSymbol],
    );
    this.#resetBuffer();

    addEventListener("unload", this.#unloadCallback);
  }

  /**
   * Handles a log record and flushes the buffer if the log level is higher than error.
   *
   * @param logRecord Log record to handle.
   *
   * @example Usage
   * ```ts
   * import { FileHandler } from "@std/log/file-handler";
   * import { assertInstanceOf } from "@std/assert/instance-of";
   * import { LogLevels } from "./levels.ts";
   * import { LogRecord } from "./logger.ts";
   *
   * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
   * handler.setup();
   *
   * // Flushes the buffer immediately and logs "CRITICAL This log is very critical indeed." into the file.
   * handler.handle(
   *   new LogRecord({
   *     msg: "This log is very critical indeed.",
   *     args: [],
   *     level: LogLevels.CRITICAL,
   *     loggerName: "INFO",
   *   }),
   * );
   * handler.destroy();
   *
   * assertInstanceOf(handler, FileHandler);
   * ```
   */
  override handle(logRecord: LogRecord) {
    super.handle(logRecord);

    // Immediately flush if log level is higher than ERROR
    if (logRecord.level > LogLevels.ERROR) {
      this.flush();
    }
  }

  /**
   * Logs a message by adding it to the buffer, with flushing as needed.
   *
   * @param msg The message to log.
   *
   * @example Usage
   * ```ts
   * import { FileHandler } from "@std/log/file-handler";
   * import { assertInstanceOf } from "@std/assert/instance-of";
   *
   * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
   * handler.setup();
   * handler.log('Hello, world!');
   * handler.flush();
   * handler.destroy();
   *
   * assertInstanceOf(handler, FileHandler);
   * ```
   */
  log(msg: string) {
    const bytes = this[encoderSymbol].encode(msg + "\n");
    if (bytes.byteLength > this[bufSymbol].byteLength - this[pointerSymbol]) {
      this.flush();
    }
    if (bytes.byteLength > this[bufSymbol].byteLength) {
      writeAllSync(this[fileSymbol]!, bytes);
    } else {
      this[bufSymbol].set(bytes, this[pointerSymbol]);
      this[pointerSymbol] += bytes.byteLength;
    }
  }

  /**
   * Immediately writes the contents of the buffer to the previously opened file.
   *
   * @example Usage
   * ```ts
   * import { FileHandler } from "@std/log/file-handler";
   * import { assertInstanceOf } from "@std/assert/instance-of";
   *
   * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
   * handler.setup();
   * handler.log('Hello, world!');
   * handler.flush(); // Writes buffered log messages to the file immediately.
   * handler.destroy();
   *
   * assertInstanceOf(handler, FileHandler);
   * ```
   */
  flush() {
    if (this[pointerSymbol] > 0 && this[fileSymbol]) {
      let written = 0;
      while (written < this[pointerSymbol]) {
        written += this[fileSymbol].writeSync(
          this[bufSymbol].subarray(written, this[pointerSymbol]),
        );
      }
      this.#resetBuffer();
    }
  }

  #resetBuffer() {
    this[pointerSymbol] = 0;
  }

  /**
   * Destroys the handler, performing any cleanup that is required and closes the file handler.
   *
   * @example Usage
   * ```ts
   * import { FileHandler } from "@std/log/file-handler";
   * import { assertInstanceOf } from "@std/assert/instance-of";
   *
   * const handler = new FileHandler("INFO", { filename: "./_tmp/logs.txt" });
   * handler.setup();
   * handler.destroy();
   *
   * assertInstanceOf(handler, FileHandler);
   * ```
   */
  override destroy() {
    this.flush();
    this[fileSymbol]?.close();
    this[fileSymbol] = undefined;
    removeEventListener("unload", this.#unloadCallback);
  }
}