removed log location detail

This commit is contained in:
Kaushik Narayan R 2025-03-12 15:22:49 -07:00
parent e6bff5a472
commit 04e1ba3804
12 changed files with 61 additions and 84 deletions

View File

@ -1,9 +1,7 @@
// TODO: rate limit module is busted (CJS types), do something for rate limiting // TODO: rate limit module is busted (CJS types), do something for rate limiting
import axios, { type AxiosInstance } from "axios"; import axios, { type AxiosInstance } from "axios";
import { baseAPIURL, accountsAPIURL } from "../constants.ts"; import { baseAPIURL, accountsAPIURL } from "../constants.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
const authInstance: AxiosInstance = axios.create({ const authInstance: AxiosInstance = axios.create({
baseURL: accountsAPIURL, baseURL: accountsAPIURL,

View File

@ -1,5 +1,4 @@
import { axiosInstance } from "./axios.ts"; import { axiosInstance } from "./axios.ts";
import curriedLogger from "../utils/logger.ts";
import { type AxiosResponse, type AxiosRequestConfig } from "axios"; import { type AxiosResponse, type AxiosRequestConfig } from "axios";
import type { import type {
@ -14,7 +13,7 @@ import type {
Res, Res,
} from "spotify_manager/index.d.ts"; } from "spotify_manager/index.d.ts";
const logger = curriedLogger(import.meta.filename); import logger from "../utils/logger.ts";
const logPrefix = "Spotify API: "; const logPrefix = "Spotify API: ";
enum allowedMethods { enum allowedMethods {

View File

@ -1,8 +1,7 @@
import { createClient } from "redis"; import { createClient } from "redis";
import { sleep } from "../utils/flake.ts"; import { sleep } from "../utils/flake.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
if (!process.env["REDIS_URI"]) if (!process.env["REDIS_URI"])
throw new TypeError("Redis connection URI not defined"); throw new TypeError("Redis connection URI not defined");

View File

@ -1,7 +1,6 @@
import type { SequelizeOptions } from "sequelize-typescript"; import type { SequelizeOptions } from "sequelize-typescript";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
type ConnConfigs = Record<string, SequelizeOptions>; type ConnConfigs = Record<string, SequelizeOptions>;

View File

@ -11,8 +11,7 @@ import type { RequestHandler } from "express";
import { generateRandString } from "../utils/generateRandString.ts"; import { generateRandString } from "../utils/generateRandString.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
/** /**
* Stateful redirect to Spotify login with credentials * Stateful redirect to Spotify login with credentials

View File

@ -30,8 +30,7 @@ import { redisClient } from "../config/redis.ts";
import Playlists from "../models/playlists.ts"; import Playlists from "../models/playlists.ts";
import Links from "../models/links.ts"; import Links from "../models/links.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
/** /**
* Sync user's Spotify data * Sync user's Spotify data

View File

@ -9,8 +9,7 @@ import type {
SimplifiedPlaylistObject, SimplifiedPlaylistObject,
} from "spotify_manager/index.d.ts"; } from "spotify_manager/index.d.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
/** /**
* Get user's playlists * Get user's playlists

View File

@ -22,8 +22,7 @@ import authRoutes from "./routes/auth.ts";
import playlistRoutes from "./routes/playlists.ts"; import playlistRoutes from "./routes/playlists.ts";
import operationRoutes from "./routes/operations.ts"; import operationRoutes from "./routes/operations.ts";
import curriedLogger from "./utils/logger.ts"; import logger from "./utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
const app = express(); const app = express();
@ -131,7 +130,7 @@ const cleanupFunc = (signal?: string) => {
Promise.allSettled([ Promise.allSettled([
redisClient.disconnect, redisClient.disconnect,
seqConn.close(), seqConn.close,
promisify(server.close), promisify(server.close),
]).then(() => { ]).then(() => {
logger.info("Cleaned up, exiting."); logger.info("Cleaned up, exiting.");

View File

@ -3,8 +3,7 @@ import type { RequestHandler } from "express";
import { sessionName } from "../constants.ts"; import { sessionName } from "../constants.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
export const isAuthenticated: RequestHandler = (req, res, next) => { export const isAuthenticated: RequestHandler = (req, res, next) => {
if (req.session.accessToken) { if (req.session.accessToken) {

View File

@ -6,8 +6,7 @@ import seqConfig from "../config/sequelize.ts";
import links from "./links.ts"; import links from "./links.ts";
import playlists from "./playlists.ts"; import playlists from "./playlists.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
if (!process.env["NODE_ENV"]) if (!process.env["NODE_ENV"])
throw new TypeError("Node environment not defined"); throw new TypeError("Node environment not defined");

View File

@ -2,75 +2,64 @@ import path from "path";
import { createLogger, transports, config, format, type Logger } from "winston"; import { createLogger, transports, config, format, type Logger } from "winston";
const { combine, label, timestamp, printf, errors } = format; const { combine, timestamp, printf, errors } = format;
const getLabel = (callingModuleName: string) => { const metaFormat = (meta: object) => {
if (!callingModuleName) return "repl"; const disallowedKeySets = [{ type: Error, keys: ["stack"] }];
const parts = callingModuleName.split(path.sep);
return path.join(
parts[parts.length - 2] ?? "",
parts[parts.length - 1] ?? ""
);
};
const allowedErrorKeys = ["name", "code", "message", "stack"];
const metaFormat = (meta: Record<string, unknown>) => {
if (Object.keys(meta).length > 0) if (Object.keys(meta).length > 0)
return "\n" + JSON.stringify(meta, null, "\t"); return (
"\n" +
JSON.stringify(
meta,
Object.getOwnPropertyNames(meta).filter((key) => {
for (const pair of disallowedKeySets) {
if (meta instanceof pair.type) {
return !pair.keys.includes(key);
}
}
return true;
}),
"\t"
)
);
return ""; return "";
}; };
const logFormat = printf(({ level, message, label, timestamp, ...meta }) => { const logFormat = printf(({ level, message, label, timestamp, ...meta }) => {
if (meta["error"]) { const errorObj: Error = meta["error"] as Error;
const sanitizedError = Object.fromEntries( if (errorObj) {
Object.entries(meta["error"]).filter(([key]) =>
allowedErrorKeys.includes(key)
)
);
const { stack, ...rest } = sanitizedError;
return ( return (
`${timestamp} [${label}] ${level}: ${message}${metaFormat(rest)}\n` + `${timestamp} [${level.toUpperCase()}]: ${message}${metaFormat(
`${stack ?? ""}` errorObj
)}\n` + `${errorObj["stack"] ?? ""}`
); );
} }
return `${timestamp} [${label}] ${level}: ${message}${metaFormat(meta)}`; return `${timestamp} [${level.toUpperCase()}]: ${message}${metaFormat(meta)}`;
}); });
const loggerCache = new Map<string, ReturnType<typeof createLogger>>(); const winstonLogger: Logger = createLogger({
const curriedLogger = (callingModuleName: string): Logger => {
if (loggerCache.has(callingModuleName)) {
return loggerCache.get(callingModuleName)!;
}
const winstonLogger = createLogger({
levels: config.npm.levels, levels: config.npm.levels,
format: combine( format: combine(
errors({ stack: true }), errors({ stack: true }),
label({ label: getLabel(callingModuleName) }),
timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
logFormat logFormat
), ),
transports: [ transports: [
new transports.Console({ level: "info" }), new transports.Console({ level: "info" }),
new transports.File({ new transports.File({
filename: import.meta.dirname + "/../logs/debug.log", filename: path.join(import.meta.dirname, "..", "logs", "debug.log"),
level: "debug", level: "debug",
maxsize: 10485760, maxsize: 10485760,
}), }),
new transports.File({ new transports.File({
filename: import.meta.dirname + "/../logs/error.log", filename: path.join(import.meta.dirname, "..", "logs", "error.log"),
level: "error", level: "error",
maxsize: 1048576, maxsize: 1048576,
}), }),
], ],
}); });
winstonLogger.on("error", (error) => winstonLogger.on("error", (error) =>
winstonLogger.error("Error inside logger", { error }) winstonLogger.error("Error inside logger", { error })
); );
loggerCache.set(callingModuleName, winstonLogger);
return winstonLogger;
};
export default curriedLogger; export default winstonLogger;

View File

@ -4,8 +4,7 @@ import type { RequestHandler } from "express";
import { getNestedValuesString } from "../utils/jsonTransformer.ts"; import { getNestedValuesString } from "../utils/jsonTransformer.ts";
import curriedLogger from "../utils/logger.ts"; import logger from "../utils/logger.ts";
const logger = curriedLogger(import.meta.filename);
/** Refer: https://stackoverflow.com/questions/58848625/access-messages-in-express-validator */ /** Refer: https://stackoverflow.com/questions/58848625/access-messages-in-express-validator */
export const validate: RequestHandler = (req, res, next) => { export const validate: RequestHandler = (req, res, next) => {