Last active
June 12, 2021 15:06
-
-
Save ManotLuijiu/b299332a4a60d7e269274b7d26642505 to your computer and use it in GitHub Desktop.
Log node.js project with winston and morgan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const favicon = require('serve-favicon'); | |
const path = require('path'); | |
const rfs = require('rotating-file-stream'); | |
require('dotenv').config(); // Put before logger.js | |
// const logger = require('./util/loggerEasy'); | |
const logger = require('./util/logger'); | |
const { stream } = logger; | |
const morgan = require('morgan'); | |
const app = express(); | |
app.set('view engine', 'pug'); | |
app.set('views', 'views'); | |
const adminRoutes = require('./routes/admin'); | |
const shopRoutes = require('./routes/shop'); | |
const accessLogStream = rfs.createStream('access.log', { | |
interval: '1d', | |
path: path.join(__dirname, 'logs'), | |
}); | |
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(bodyParser.json()); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
// Morgan | |
morgan.token('th-date', function (req, res) { | |
const date = new Date(); | |
return date; | |
}); | |
app.use(morgan('common', { stream: accessLogStream })); | |
app.use( | |
morgan( | |
':th-date :method[pretty] :url :status :res[content-length] - :response-time ms', | |
{ | |
stream: stream, | |
} | |
) | |
); | |
app.use('/admin', adminRoutes.routes); | |
app.use(shopRoutes); | |
app.use((req, res, next) => { | |
res.status(404).sendFile(path.join(__dirname, 'views', '404.html')); | |
}); | |
const port = process.env.PORT || 3000; | |
app.listen(port, (err) => { | |
if (err) throw err; | |
logger.info(`Ready Listening on port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment