DEV Community

Discussion on: Node.js Morgan Guide

Collapse
 
mirzaleka profile image
Mirza Leka

I went ahead to try it myself using a local server and nodemon and I found it a bit disappointing that your code doesn't even run. Instead it prints an error:

TypeError: Router.use() requires a middleware function but got a Object

After short investigation I figured what the problem is. Rather than passing options Object to a morgan middleware, you passed it as a separate entity to app.use (as if it's a middleware).

app.use(morgan('dev'), { stream: rfsStream });

The correct code looks like this (with options passed as a second param to morgan)

app.use(morgan('dev', { stream: rfsStream }))

With that out of the way, I set interval to only 2 minutes and ran the app locally to see what happens.

const rfsStream = rfs.createStream("log.txt", {
   size: '10M', // rotate every 10 MegaBytes written
   interval: '2m', // rotate after 2 minutes
})

app.use(morgan('dev', { stream: rfsStream }))
Enter fullscreen mode Exit fullscreen mode

The end result is very interesting.

Every log that occurs will be written in log.txt file. When the timer runs out, the RFS library creates a new log file with timestamp as prefix 20220108-1214-01-log.txt and stores all of the logs from the previous period in the newly created file.
As for the original, RFS wipes the content inside it and populates it with new logs.

The process is then repeated again and again until you shutdown the server or increase the interval.

And that's how it works 😎

Thread Thread
 
paras594 profile image
Paras 🧙‍♂️

Nice one. Congrats that you get it to run.
Thank you for pointing out the error, I will update the code :)