Skip to content

Commit

Permalink
feat(logger): added logging
Browse files Browse the repository at this point in the history
  • Loading branch information
HoseaCodes committed Aug 30, 2021
1 parent 52ba4f7 commit 86909d3
Show file tree
Hide file tree
Showing 7 changed files with 460 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# production
/build
/logs

# misc
.DS_Store
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ The user is brought to the home page where they can navigate to my [portfolio](w
- /login
- /refresh_token

### Logger

- [Winston](https://github.com/winstonjs/winston)

## APIs

- [Send Grid](https://app.sendgrid.com/)
Expand Down
70 changes: 57 additions & 13 deletions controllers/article.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Articles = require("../models/article")

const Articles = require("../models/article");
const Logger = require('../logger');
const logger = new Logger('articles')


const articleCrtl = {
Expand All @@ -12,14 +13,18 @@ const articleCrtl = {
async function getArticle(req, res) {
try {
const articles = await Articles.find()


logger.info("Returning the list of articles");

res.json({
status: 'success',
articles: articles,
result: articles.length,

})
} catch (err) {

logger.error(err);

return res.status(500).json({ msg: err.message })
}
}
Expand All @@ -28,43 +33,82 @@ async function createArticle(req, res) {
try {

const { article_id, title, subtitle, markdown, description, images, category } = req.body;
if (!images) return res.status(400).json({ msg: "No image upload" })

const article = await Articles.findOne({ article_id })
if (article) return res.status(400).json({ msg: "This article already exists." })

if (!images) {

logger.error("No image provided.");

return res.status(400).json({ msg: "No image upload" });
}

const article = await Articles.findOne({ article_id });

if (article) {

logger.error("Article already exist.");

return res.status(400).json({ msg: "This article already exists." })
}

const newArticle = new Articles({
article_id, title, subtitle, markdown, description, images, category
})

await newArticle.save()

res.json({ msg: "Created a new article" })

logger.info(`New article ${title} has been created`);

res.json({ msg: "Created a new article" });
} catch (err) {

logger.error(err)

return res.status(500).json({ msg: err.message })
}
}

async function deleteArticle(req, res) {
try {

logger.info(`Deleted article ${req.params.id} has been deleted`);

await Articles.findByIdAndDelete(req.params.id)

res.json({ msg: "Deleted a article" })

} catch (err) {

logger.error(err)

return res.status(500).json({ msg: err.message })
}
}

async function updateArticle(req, res) {
try {
const { title, subtitle, description, content, images, category } = req.body;
if (!images) return res.status(400).json({ msg: "No image upload" })


if (!images) {

logger.error("No image provided.");

return res.status(400).json({ msg: "No image upload" })
}

let originalBody = req.body

await Articles.findOneAndUpdate({ _id: req.params.id }, {
title: title.toLowerCase(), subtitle, description, content, images, category
})

let preparedLog = `Changing the following: ${originalBody} to ${req.body} for the article ${title}`;

logger.info(preparedLog);

res.json({ msg: 'Updated a article' })
} catch (err) {

logger.error(err)

return res.status(500).json({ msg: err.message })
}
}
Expand Down
71 changes: 71 additions & 0 deletions logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//Bringing Winston in
const winston = require("winston");

//Simple function to return the current date and time
const timeStamp = () => {
return new Date(Date.now()).toUTCString();
};

//Here we create our Custom Logger class
class CustomLogger {

//We want to attach the service route to each instance, so when we call it from our services it gets attached to the message
constructor(service) {
this.log_data = null;
this.service = service;

const logger = winston.createLogger({
transports: [
//Here we declare the winston transport, and assign it to our file: allLogs.log
new winston.transports.File({
filename: `./logs/allLogs.log`,
}),
],

format: winston.format.printf((info) => {

//Here is our custom message
let message = `${timeStamp()} | ${info.level}${info.message} | From: ${service} controller `;

return message;
}),
});

this.logger = logger;
}

setLogData(log_data) {
this.log_data = log_data;
}

async info(message) {
this.logger.log("info", message);
}

async info(message, obj) {
this.logger.log("info", message, {
obj,
});
}

async debug(message) {
this.logger.log("debug", message);
}

async debug(message, obj) {
this.logger.log("debug", message, {
obj,
});
}

async error(message) {
this.logger.log("error", message);
}
async error(message, obj) {
this.logger.log("error", message, {
obj,
});
}
}

module.exports = CustomLogger;
Loading

0 comments on commit 86909d3

Please sign in to comment.