Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import { RotatingFileSink } from "@t3tools/shared/logging";
6import { afterEach, describe, expect, it } from "vitest";
7
8const tempRoots: string[] = [];
9
10function makeTempDir(): string {
11 const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
12 tempRoots.push(dir);
13 return dir;
14}
15
16afterEach(() => {
17 for (const dir of tempRoots.splice(0)) {
18 fs.rmSync(dir, { recursive: true, force: true });
19 }
20});
21
22describe("RotatingFileSink", () => {
23 it("rotates when writes exceed max bytes", () => {
24 const dir = makeTempDir();
25 const logPath = path.join(dir, "desktop-main.log");
26 const sink = new RotatingFileSink({
27 filePath: logPath,
28 maxBytes: 10,
29 maxFiles: 3,
30 });
31
32 sink.write("12345");
33 sink.write("67890");
34 sink.write("abc");
35
36 expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
37 expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
38 });
39
40 it("retains only maxFiles backups", () => {
41 const dir = makeTempDir();
42 const logPath = path.join(dir, "server-child.log");
43 const sink = new RotatingFileSink({
44 filePath: logPath,
45 maxBytes: 4,
46 maxFiles: 2,
47 });
48
49 sink.write("aaaa");
50 sink.write("bbbb");
51 sink.write("cccc");
52 sink.write("dddd");
53
54 expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
55 expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
56 expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
57 });
58
59 it("prunes stale backups above maxFiles on startup", () => {
60 const dir = makeTempDir();
61 const logPath = path.join(dir, "desktop-main.log");
62 fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
63 fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
64
65 const sink = new RotatingFileSink({
66 filePath: logPath,
67 maxBytes: 16,
68 maxFiles: 2,
69 });
70 sink.write("hello");
71
72 expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
73 });
74});