Logging requests for your Express App can be accomplished using Morgan. It is a simple to use package.
HOW TO INSTALL?
Install Morgan using Node Package Manager (NPM)
npm install --save morgan
HOW TO INCLUDE?
Include Morgan middleware in your application in the following way in the main app.js/server.js
const morgan = require('morgan');
HOW TO USE?
Finally use it as a middleware after creating express instance.
app.use(morgan('combined'));
On running your application, you will see logs being printed on server side console. One of the example of logs is as follows:
::1 - - [28/Jun/2019:06:07:27 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
SAVE LOGS TO FILE
Import fs module into your express app
const fs = require('fs');
Set a constant that will write incoming logs into a file named access.log
const accessLogStream = fs.createWriteStream(
path.join(__dirname, 'access.log'),
{ flags: 'a' }
);
accessLogStream is the constant
fs.createWriteStream writes to the file.
The first argument defines where to write, i.e. the file path.
Second argument { flags: 'a' } defines that the incoming logs to be appended.
Finally feed this file to morgan.
app.use(morgan('combined', { stream: accessLogStream }));
Comments
Post a Comment