Hello here is my problem, recently, I deployed a server on 2021/10/01 where I save access logs. I am using the morgan library to do this and rotating-file-stream for the file rotation. However, after a few days of activity, I realized that the rotation was not done correctly.
Here is my code:
const morgan = require('morgan');
const rfs = require('rotating-file-stream');
const path = require('path');
const { format } = require('date-fns');
function logFilename() {
return `${format(new Date(), 'yyyy-MM-dd')}-access.log`;
}
const accessLogStream = rfs.createStream(logFilename, {
interval: '1d', // rotate daily
path: path.resolve(__dirname, '..', 'log'),
});
morgan.token('ip', (req) => req.headers['x-forwarded-for'] || req.connection.remoteAddress);
morgan.token('user', (req) => {
if (req.user) return req.user;
return '-';
});
module.exports = morgan(':ip ":user" [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"', { stream: accessLogStream });
here are examples of what I can find in my log files (it is at the date level that you have to look).
2021-10-03-access.log
:ip ":user" [01/Oct/2021:07:30:52 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [02/Oct/2021:23:56:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
2021-10-04-access.log
:ip ":user" [03/Oct/2021:00:01:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [03/Oct/2021:23:56:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
2021-10-05-access.log
:ip ":user" [04/Oct/2021:00:01:26 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
...
...
:ip ":user" [05/Oct/2021:06:03:02 +0000] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
I saw that on the rotating-file-stream doc that if we put "1d" in interval argument, that will do rotates at every midnight but maybe i forgot something.
thanks in advance for attention and future answers.
i had forgot one condition and one parameter for the file name generator
function logFilename(time) {
if (!time) return 'access.log';
return `${format(time, 'yyyy-MM-dd')}-access.log`;
}