improvement: moved all console logs to pino

This commit is contained in:
canove
2021-01-07 20:52:51 -03:00
parent 0689b55453
commit 896f122cf7
16 changed files with 57 additions and 36 deletions

View File

@@ -16,6 +16,7 @@
"license": "MIT",
"dependencies": {
"@sentry/node": "5.27.0",
"@types/pino": "^6.3.4",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
@@ -28,6 +29,8 @@
"multer": "^1.4.2",
"mysql2": "^2.2.5",
"pg": "^8.4.1",
"pino": "^6.9.0",
"pino-pretty": "^4.3.0",
"qrcode-terminal": "^0.12.0",
"reflect-metadata": "^0.1.13",
"sequelize": "^5.22.3",

View File

@@ -10,6 +10,7 @@ import "./database";
import uploadConfig from "./config/upload";
import AppError from "./errors/AppError";
import routes from "./routes";
import { logger } from "./utils/logger";
Sentry.init({ dsn: process.env.SENTRY_DSN });
@@ -31,10 +32,15 @@ app.use(Sentry.Handlers.errorHandler());
app.use(async (err: Error, req: Request, res: Response, _: NextFunction) => {
if (err instanceof AppError) {
if (err.statusCode === 403) {
logger.warn(err);
} else {
logger.error(err);
}
return res.status(err.statusCode).json({ error: err.message });
}
console.error(err);
logger.error(err);
return res.status(500).json({ error: "Internal server error" });
});

View File

@@ -37,7 +37,6 @@ export const GetWbotMessage = async (
return msgFound;
} catch (err) {
console.log(err);
throw new AppError("ERR_FETCH_WAPP_MSG");
}
};

View File

@@ -1,6 +1,7 @@
import { getIO } from "../libs/socket";
import Message from "../models/Message";
import Ticket from "../models/Ticket";
import { logger } from "../utils/logger";
import GetTicketWbot from "./GetTicketWbot";
const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
@@ -18,9 +19,8 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
const wbot = await GetTicketWbot(ticket);
wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
} catch (err) {
console.log(
"Could not mark messages as read. Maybe whatsapp session disconnected?",
err
logger.warn(
`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`
);
}

View File

@@ -1,6 +1,7 @@
import socketIo, { Server as SocketIO } from "socket.io";
import { Server } from "http";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";
let io: SocketIO;
@@ -8,24 +9,24 @@ export const initIO = (httpServer: Server): SocketIO => {
io = socketIo(httpServer);
io.on("connection", socket => {
console.log("Client Connected");
logger.info("Client Connected");
socket.on("joinChatBox", ticketId => {
console.log("A client joined a ticket channel");
logger.info("A client joined a ticket channel");
socket.join(ticketId);
});
socket.on("joinNotification", () => {
console.log("A client joined notification channel");
logger.info("A client joined notification channel");
socket.join("notification");
});
socket.on("joinTickets", status => {
console.log(`A client joined to ${status} tickets channel.`);
logger.info(`A client joined to ${status} tickets channel.`);
socket.join(status);
});
socket.on("disconnect", () => {
console.log("Client disconnected");
logger.info("Client disconnected");
});
});
return io;

View File

@@ -3,6 +3,7 @@ import { Client } from "whatsapp-web.js";
import { getIO } from "./socket";
import Whatsapp from "../models/Whatsapp";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";
// import { handleMessage } from "../services/WbotServices/wbotMessageListener";
interface Session extends Client {
@@ -58,7 +59,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
wbot.initialize();
wbot.on("qr", async qr => {
console.log("Session:", sessionName);
logger.info("Session:", sessionName);
qrCode.generate(qr, { small: true });
await whatsapp.update({ qrcode: qr, status: "qrcode", retries: 0 });
@@ -75,7 +76,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
});
wbot.on("authenticated", async session => {
console.log("Session:", sessionName, "AUTHENTICATED");
logger.info("Session:", sessionName, "AUTHENTICATED");
await whatsapp.update({
session: JSON.stringify(session)
});
@@ -103,7 +104,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
});
wbot.on("ready", async () => {
console.log("Session:", sessionName, "READY");
logger.info("Session:", sessionName, "READY");
// syncUnreadMessages(wbot);
@@ -129,7 +130,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
resolve(wbot);
});
} catch (err) {
console.log(err);
logger.error(err);
}
});
};
@@ -151,6 +152,6 @@ export const removeWbot = (whatsappId: number): void => {
sessions.splice(sessionIndex, 1);
}
} catch (err) {
console.log(err);
logger.error(err);
}
};

View File

@@ -30,7 +30,10 @@ const isAuth = (req: Request, res: Response, next: NextFunction): void => {
profile
};
} catch (err) {
throw new AppError("Invalid token.", 403);
throw new AppError(
"Invalid token. We'll try to assign a new one on next request",
403
);
}
return next();

View File

@@ -1,10 +1,11 @@
import gracefulShutdown from "http-graceful-shutdown";
import app from "./app";
import { initIO } from "./libs/socket";
import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
const server = app.listen(process.env.PORT, () => {
console.log(`Server started on port: ${process.env.PORT}`);
logger.info(`Server started on port: ${process.env.PORT}`);
});
initIO(server);

View File

@@ -13,7 +13,6 @@ const CheckIsValidContact = async (number: string): Promise<void> => {
throw new AppError("invalidNumber");
}
} catch (err) {
console.log(err);
if (err.message === "invalidNumber") {
throw new AppError("ERR_WAPP_INVALID_CONTACT");
}

View File

@@ -1,6 +1,7 @@
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import { getWbot } from "../../libs/wbot";
import Contact from "../../models/Contact";
import { logger } from "../../utils/logger";
const ImportContactsService = async (): Promise<void> => {
const defaultWhatsapp = await GetDefaultWhatsApp();
@@ -12,10 +13,7 @@ const ImportContactsService = async (): Promise<void> => {
try {
phoneContacts = await wbot.getContacts();
} catch (err) {
console.log(
"Could not get whatsapp contacts from phone. Check connection page.",
err
);
logger.error(`Could not get whatsapp contacts from phone. Err: ${err}`);
}
if (phoneContacts) {

View File

@@ -30,7 +30,6 @@ const SendWhatsAppMedia = async ({
return sentMessage;
} catch (err) {
console.log(err);
throw new AppError("ERR_SENDING_WAPP_MSG");
}
};

View File

@@ -37,7 +37,6 @@ const SendWhatsAppMessage = async ({
await ticket.update({ lastMessage: body });
return sentMessage;
} catch (err) {
console.log(err);
throw new AppError("ERR_SENDING_WAPP_MSG");
}
};

View File

@@ -3,6 +3,7 @@ import Whatsapp from "../../models/Whatsapp";
import { wbotMessageListener } from "./wbotMessageListener";
import { getIO } from "../../libs/socket";
import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
export const StartWhatsAppSession = async (
whatsapp: Whatsapp
@@ -20,6 +21,6 @@ export const StartWhatsAppSession = async (
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {
console.log(err);
logger.error(err);
}
};

View File

@@ -20,6 +20,7 @@ import { getIO } from "../../libs/socket";
import AppError from "../../errors/AppError";
import ShowTicketService from "../TicketServices/ShowTicketService";
import CreateMessageService from "../MessageServices/CreateMessageService";
import { logger } from "../../utils/logger";
interface Session extends Client {
id?: number;
@@ -176,7 +177,8 @@ const verifyMedia = async (
"base64"
);
} catch (err) {
console.log(err);
Sentry.captureException(err);
logger.error(err);
}
const messageData = {
@@ -303,7 +305,7 @@ const handleMessage = async (
await verifyMessage(msg, ticket, contact);
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.error(err);
}
};
@@ -334,13 +336,12 @@ const handleMsgAck = async (msg: WbotMessage, ack: MessageAck) => {
});
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.log(err);
}
};
const wbotMessageListener = (wbot: Session): void => {
wbot.on("message_create", async msg => {
// console.log(msg);
handleMessage(msg, wbot);
});

View File

@@ -3,6 +3,7 @@ import { Client } from "whatsapp-web.js";
import { getIO } from "../../libs/socket";
import Whatsapp from "../../models/Whatsapp";
import { logger } from "../../utils/logger";
import { StartWhatsAppSession } from "./StartWhatsAppSession";
interface Session extends Client {
@@ -18,12 +19,12 @@ const wbotMonitor = async (
try {
wbot.on("change_state", async newState => {
console.log("Monitor session:", sessionName, newState);
logger.info("Monitor session:", sessionName, newState);
try {
await whatsapp.update({ status: newState });
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.error(err);
}
io.emit("whatsappSession", {
@@ -34,7 +35,7 @@ const wbotMonitor = async (
wbot.on("change_battery", async batteryInfo => {
const { battery, plugged } = batteryInfo;
console.log(
logger.info(
`Battery session: ${sessionName} ${battery}% - Charging? ${plugged}`
);
@@ -42,7 +43,7 @@ const wbotMonitor = async (
await whatsapp.update({ battery, plugged });
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.error(err);
}
io.emit("whatsappSession", {
@@ -52,12 +53,12 @@ const wbotMonitor = async (
});
wbot.on("disconnected", async reason => {
console.log("Disconnected session:", sessionName, reason);
logger.info("Disconnected session:", sessionName, reason);
try {
await whatsapp.update({ status: "OPENING", session: "" });
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.error(err);
}
io.emit("whatsappSession", {
@@ -69,7 +70,7 @@ const wbotMonitor = async (
});
} catch (err) {
Sentry.captureException(err);
console.log(err);
logger.error(err);
}
};

View File

@@ -0,0 +1,9 @@
import pino from "pino";
const logger = pino({
prettyPrint: {
ignore: "pid,hostname"
}
});
export { logger };