Add debug logger for MongoDB

This commit is contained in:
Alexander Ungar 2023-03-21 23:56:05 +01:00
parent 06e3fafe15
commit a8b6009c7c
3 changed files with 22 additions and 1 deletions

3
env/development.env vendored
View file

@ -1,4 +1,5 @@
## Server ##
PORT=3000
NODE_ENV=development
DATABASE_CONNECTION_STRING=mongodb://localhost:27017
DATABASE_CONNECTION_STRING=mongodb://localhost:27017
LOG_LEVEL=debug

View file

@ -1,5 +1,7 @@
import mongoose from "mongoose";
import environment from "./environment.js";
import logger from "../logging/logger.js";
import * as util from "util";
const connect = async (): Promise<void> => {
await mongoose.connect(environment.DATABASE_CONNECTION_STRING, {
@ -7,4 +9,20 @@ const connect = async (): Promise<void> => {
});
};
if (environment.LOG_LEVEL === "debug") {
// https://dev.to/sw360cab/mongoose-debug-messages-with-a-custom-logging-library-or-style-1hk4
mongoose.set("debug", (collectionName, methodName, ...methodArgs) => {
const msgMapper = (m: any): string => {
return util
.inspect(m, false, 10, true)
.replace(/\n/g, "")
.replace(/\s{2,}/g, " ");
};
logger.debug(
`\x1B[0;36mMongoose:\x1B[0m: ${collectionName}.${methodName}` +
`(${methodArgs.map(msgMapper).join(", ")})`
);
});
}
export default { connect };

View file

@ -1,7 +1,9 @@
import expressWinston from "express-winston";
import winston from "winston";
import environment from "../config/environment.js";
const expressLogger = expressWinston.logger({
level: environment.LOG_LEVEL,
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.colorize(),