Files
lst_v3/backend/logger/db.transport.ts

70 lines
1.7 KiB
TypeScript

import build from "pino-abstract-transport";
import { db } from "../db/db.controller.js";
import { logs } from "../db/schema/logs.schema.js";
import { tryCatch } from "../utils/trycatch.utils.js";
const pinoLogLevels: Record<number, string> = {
10: "trace",
20: "debug",
30: "info",
40: "warn",
50: "error",
60: "fatal",
};
// Create a custom transport function
export default async function () {
//const {username, service, level, msg, ...extra} = log;
try {
return build(async (source) => {
for await (const obj of source) {
// convert to the name to make it more easy to find later :P
const levelName = pinoLogLevels[obj.level] || "unknown";
const res = await tryCatch(
db.insert(logs).values({
level: levelName,
module: obj?.module?.toLowerCase(),
subModule: obj?.subModule?.toLowerCase(),
hostname: obj?.hostname?.toLowerCase(),
message: obj.msg,
stack: obj?.stack,
}),
);
if (res.error) {
console.error(res.error);
}
}
});
} catch (err) {
console.error("Error inserting log into database:", err);
}
}
// export const dbStream = {
// write: async (logString: string) => {
// try {
// const obj = JSON.parse(logString);
// const levelName = pinoLogLevels[obj.level] || "unknown";
// const res = await tryCatch(
// db.insert(logs).values({
// level: levelName,
// module: obj?.module?.toLowerCase(),
// subModule: obj?.subModule?.toLowerCase(),
// hostname: obj?.hostname?.toLowerCase(),
// message: obj.msg,
// stack: obj?.stack,
// }),
// );
// if (res.error) {
// console.error("DB log error:", res.error);
// }
// } catch (err) {
// console.error("Error parsing/inserting log:", err);
// }
// },
// };