Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/be/logger improvement #1058

Merged
merged 4 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions Server/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ const registerUser = async (req, res, next) => {
}

const newUser = await req.db.insertUser({ ...req.body }, req.file);

logger.info(successMessages.AUTH_CREATE_USER, {
logger.info({
message: successMessages.AUTH_CREATE_USER,
service: SERVICE_NAME,
userId: newUser._id,
details: newUser._id,
});

const userForToken = { ...newUser._doc };
Expand All @@ -102,9 +102,11 @@ const registerUser = async (req, res, next) => {
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error("Error sending welcome email", {
logger.error({
message: error.message,
service: SERVICE_NAME,
error: error.message,
method: "registerUser",
stack: error.stack,
});
});

Expand Down
6 changes: 4 additions & 2 deletions Server/controllers/inviteController.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ const issueInvitation = async (req, res, next) => {
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error("Error sending invite email", {
logger.error({
message: error.message,
service: SERVICE_NAME,
error: error.message,
method: "issueInvitation",
stack: error.stack,
});
});

Expand Down
70 changes: 34 additions & 36 deletions Server/controllers/monitorController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
getMonitorByIdQueryValidation,
getMonitorsByTeamIdValidation,
createMonitorBodyValidation,
getMonitorURLByQueryValidation,
getMonitorURLByQueryValidation,
editMonitorBodyValidation,
getMonitorsAndSummaryByTeamIdParamValidation,
getMonitorsAndSummaryByTeamIdQueryValidation,
Expand Down Expand Up @@ -270,32 +270,32 @@ const createMonitor = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/
const checkEndpointResolution = async (req, res, next) => {
try {
try {
await getMonitorURLByQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}

try {
let { monitorURL } = req.query;
monitorURL = new URL(monitorURL);
await new Promise((resolve, reject) => {
dns.resolve(monitorURL.hostname, (error) => {
if (error) {
reject(error);
}
resolve();
});
});
return res.status(200).json({
success: true,
msg: `URL resolved successfully`,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
}
}
try {
let { monitorURL } = req.query;
monitorURL = new URL(monitorURL);
await new Promise((resolve, reject) => {
dns.resolve(monitorURL.hostname, (error) => {
if (error) {
reject(error);
}
resolve();
});
});
return res.status(200).json({
success: true,
msg: `URL resolved successfully`,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
}
};

/**
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
Expand Down Expand Up @@ -325,14 +325,12 @@ const deleteMonitor = async (req, res, next) => {
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) {
logger.error(
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
{
method: "deleteMonitor",
service: SERVICE_NAME,
error: error.message,
}
);
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteMonitor",
stack: error.stack,
});
}
return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE });
} catch (error) {
Expand Down Expand Up @@ -365,12 +363,12 @@ const deleteAllMonitors = async (req, res, next) => {
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) {
logger.error(
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
{
method: "deleteAllMonitors",
}
);
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteAllMonitors",
stack: error.stack,
});
}
})
);
Expand Down Expand Up @@ -517,7 +515,7 @@ export {
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
checkEndpointResolution,
checkEndpointResolution,
deleteMonitor,
deleteAllMonitors,
editMonitor,
Expand Down
14 changes: 9 additions & 5 deletions Server/db/models/PageSpeedCheck.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from "mongoose";
import logger from "../../utils/logger.js";
const AuditSchema = mongoose.Schema({
id: { type: String, required: true },
title: { type: String, required: true },
Expand Down Expand Up @@ -90,19 +91,22 @@ PageSpeedCheck.pre("save", async function (next) {
const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor && monitor.status !== this.status) {
if (monitor.status === true && this.status === false) {
// TODO issue alert
console.log("Monitor went down");
logger.info({ message: "Monitor went down", monitorId: monitor._id });
}

if (monitor.status === false && this.status === true) {
// TODO issue alert
console.log("Monitor went up");
logger.info({ message: "Monitor went up", monitorId: monitor._id });
}
monitor.status = this.status;
await monitor.save();
}
} catch (error) {
console.log(error);
logger.error({
message: error.message,
service: "PageSpeedCheck",
method: "pre-save",
stack: error.stack,
});
} finally {
next();
}
Expand Down
5 changes: 4 additions & 1 deletion Server/db/models/User.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import logger from "../../utils/logger.js";

const UserSchema = mongoose.Schema(
{
Expand Down Expand Up @@ -81,7 +82,9 @@ UserSchema.methods.comparePassword = async function (submittedPassword) {
const User = mongoose.model("User", UserSchema);

User.init().then(() => {
console.log("User model initialized");
logger.info({
message: "User model initialized",
});
});

export default mongoose.model("User", UserSchema);
16 changes: 10 additions & 6 deletions Server/db/mongo/MongoDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,30 @@ const connect = async () => {
appSettings = new AppSettings({});
await appSettings.save();
}
logger.info("Connected to MongoDB", { service: SERVICE_NAME, method: "connect" });
logger.info({ message: "Connected to MongoDB" });
} catch (error) {
logger.error("failed to connect to MongoDB", {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "connect",
stack: error.stack,
});
throw error;
}
};

const disconnect = async () => {
try {
logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
logger.info({ message: "Disconnecting from MongoDB" });
await mongoose.disconnect();
logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
logger.info({ message: "Disconnected from MongoDB" });
return;
} catch (error) {
logger.error("failed to disconnect from MongoDB", {
logger.error({
message: error.message,
service: SERVICE_NAME,
errorMsg: error.message,
method: "disconnect",
stack: error.stack,
});
}
};
Expand Down
30 changes: 23 additions & 7 deletions Server/db/mongo/modules/checkModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ const createCheck = async (checkData) => {
const monitor = await Monitor.findById(monitorId);

if (!monitor) {
logger.error("Monitor not found", {
logger.error({
message: "Monitor not found",
service: SERVICE_NAME,
monitorId,
method: "createCheck",
details: `monitor ID: ${monitorId}`,
});
return;
}
Expand Down Expand Up @@ -77,7 +79,11 @@ const getChecksCount = async (req) => {
checksQuery.statusCode = 5000;
break;
default:
console.log("default");
logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecksCount",
});
break;
}
}
Expand Down Expand Up @@ -110,7 +116,7 @@ const getChecks = async (req) => {
if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
}
// Fitler checks by status
// Filter checks by status
if (filter !== undefined) {
checksQuery.status = false;
switch (filter) {
Expand All @@ -122,7 +128,11 @@ const getChecks = async (req) => {
checksQuery.statusCode = 5000;
break;
default:
console.log("default");
logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecks",
});
break;
}
}
Expand Down Expand Up @@ -170,7 +180,11 @@ const getTeamChecks = async (req) => {
checksQuery.statusCode = 5000;
break;
default:
console.log("default");
logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getTeamChecks",
});
break;
}
}
Expand Down Expand Up @@ -248,9 +262,11 @@ const updateChecksTTL = async (teamId, ttl) => {
try {
await Check.collection.dropIndex("expiry_1");
} catch (error) {
logger.error("Failed to drop index", {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "updateChecksTTL",
stack: error.stack,
});
}

Expand Down
1 change: 0 additions & 1 deletion Server/db/mongo/modules/maintenanceWindowModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
};

const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => {
console.log(maintenanceWindowData);
try {
const editedMaintenanceWindow = MaintenanceWindow.findByIdAndUpdate(
maintenanceWindowId,
Expand Down
28 changes: 19 additions & 9 deletions Server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,15 @@ const startApp = async () => {
//health check
app.use("/api/v1/healthy", (req, res) => {
try {
logger.info("Checking Health of the server.");
logger.info({ message: "Checking Health of the server." });
return res.status(200).json({ message: "Healthy" });
} catch (error) {
logger.error(error.message);
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "healthCheck",
stack: error.stack,
});
return res.status(500).json({ message: error.message });
}
});
Expand All @@ -106,7 +111,7 @@ const startApp = async () => {
// Create services
await db.connect();
app.listen(PORT, () => {
console.log(`server started on port:${PORT}`);
logger.info({ message: `server started on port:${PORT}` });
});
const settingsService = new SettingsService(AppSettings);

Expand All @@ -132,19 +137,21 @@ const startApp = async () => {

const cleanup = async () => {
if (cleaningUp) {
console.log("Already cleaning up");
logger.warn({ message: "Already cleaning up" });
return;
}
cleaningUp = true;
try {
console.log("Shutting down gracefully");
logger.info({ message: "shutting down gracefully" });
await jobQueue.obliterate();
await db.disconnect();
console.log("Finished cleanup");
logger.info({ message: "shut down gracefully" });
} catch (error) {
logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, {
logger.error({
message: error.message,
service: SERVICE_NAME,
errorMsg: error.message,
method: "cleanup",
stack: error.stack,
});
}
process.exit(0);
Expand All @@ -155,8 +162,11 @@ const startApp = async () => {
};

startApp().catch((error) => {
logger.error(error.message, {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "startApp",
stack: error.stack,
});
process.exit(1);
});
Loading