Skip to content
Snippets Groups Projects
Commit b2975f4b authored by matthiak00's avatar matthiak00
Browse files

Merge branch 'Matthias/winstonLogging' into 'master'

Added winston as logging framework

See merge request swp-unisport/team-nodejs/unisport-backend!1
parents f44b2b3f 0b440915
No related branches found
No related tags found
No related merge requests found
import express, { Request, Response } from 'express'
import * as bookController from './controllers/bookController'
import { connectMongoDB } from './database'
import { AddressInfo } from 'node:net'
import logger from './logger'
import { Server } from 'node:http'
// Our Express APP config
const app = express()
......@@ -9,6 +13,18 @@ app.set('port', 5000)
app.use(express.urlencoded({ extended: false })) // Parses urlencoded bodies
app.use(express.json()) // Send JSON responses
// logs all requests on http level => could later be saved into "access.log" for example
app.use((req, res, next) => {
logger.http(req.url)
const start = Date.now()
res.on('finish', () => {
logger.http(
`Finished ${req.url} | ${res.statusCode} [${Date.now() - start}ms]`
)
})
next()
})
app.get('/', (req, res) => {
res.send('The sedulous hyena ate the antelope!')
})
......@@ -20,20 +36,23 @@ app.post('/book', bookController.addBook)
app.put('/book/:id', bookController.updateBook)
app.delete('/book/:id', bookController.deleteBook)
async function startExpress(): Promise<void> {
async function startExpress(): Promise<Server> {
return new Promise((resolve, reject) => {
app.listen(app.get('port'), () => {
const server = app
.listen(app.get('port'), () => {
console.log(
'App is running on http://localhost:%d',
app.get('port')
)
resolve()
}).on('error', reject)
resolve(server)
})
.on('error', reject)
})
}
// main startup
;(async () => {
await Promise.all([startExpress(), connectMongoDB()])
console.log('server running and database connected')
const [server, _] = await Promise.all([startExpress(), connectMongoDB()])
const addr = server.address() as AddressInfo
logger.info(`Server started on http://localhost:${addr.port}`)
})()
import winston from 'winston'
const logFormat = winston.format.printf(({ level, message }) => {
return `${new Date().toISOString()}-${level}: ${JSON.stringify(
message,
null,
4
)}\n`
})
const logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: 'debug',
format: winston.format.combine(winston.format.colorize(), logFormat)
})
]
})
export default logger
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment