Add log4js fileSync logger module and formatError helper
This commit is contained in:
22
src/server/log-format.test.ts
Normal file
22
src/server/log-format.test.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { formatError } from "./log-format";
|
||||
|
||||
describe("formatError", () => {
|
||||
it("returns stack for Error", () => {
|
||||
const e = new Error("boom");
|
||||
expect(formatError(e)).toBe(e.stack);
|
||||
});
|
||||
it("falls back to message when stack missing", () => {
|
||||
const e = new Error("boom");
|
||||
e.stack = undefined as unknown as string;
|
||||
expect(formatError(e)).toBe("boom");
|
||||
});
|
||||
it("stringifies non-Error primitives", () => {
|
||||
expect(formatError("oops")).toBe("oops");
|
||||
expect(formatError(42)).toBe("42");
|
||||
});
|
||||
it("handles null / undefined", () => {
|
||||
expect(formatError(null)).toBe("Unknown error");
|
||||
expect(formatError(undefined)).toBe("Unknown error");
|
||||
});
|
||||
});
|
||||
11
src/server/log-format.ts
Normal file
11
src/server/log-format.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* 把任意错误/值格式化为带堆栈的字符串,用于日志记录。
|
||||
* - Error:优先 stack,缺则 message
|
||||
* - null/undefined:'Unknown error'
|
||||
* - 其它:String(value)
|
||||
*/
|
||||
export function formatError(err: unknown): string {
|
||||
if (err instanceof Error) return err.stack || err.message;
|
||||
if (err === null || err === undefined) return "Unknown error";
|
||||
return String(err);
|
||||
}
|
||||
20
src/server/logger.ts
Normal file
20
src/server/logger.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import log4js from "log4js";
|
||||
|
||||
// fileSync = 同步写:进程 OOM/被杀前日志已落盘,满足崩溃诊断刚需。
|
||||
log4js.configure({
|
||||
appenders: {
|
||||
app: {
|
||||
type: "fileSync",
|
||||
filename: "logs/app/app.log",
|
||||
maxLogSize: 10 * 1024 * 1024, // 10MB
|
||||
backups: 5,
|
||||
layout: { type: "pattern", pattern: "[%d{ISO8601}] [%p] [%c] %m" },
|
||||
},
|
||||
},
|
||||
categories: { default: { appenders: ["app"], level: "info" } },
|
||||
});
|
||||
|
||||
export { formatError } from "./log-format";
|
||||
|
||||
export const apiLogger = log4js.getLogger("api");
|
||||
export const exportLogger = log4js.getLogger("export");
|
||||
Reference in New Issue
Block a user