-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
50 lines (45 loc) · 1.3 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf } = format;
// Define the custom format for log messages
const myFormat = printf(({ level, message, timestamp, ...metadata }) => {
let msg = `${timestamp} [${level}]: ${message}`;
if (metadata) {
msg += ` ${JSON.stringify(metadata)}`;
}
return msg;
});
// Create the logger
const logger = createLogger({
level: 'info',
format: combine(
timestamp(),
myFormat
),
transports: [
new transports.Console(),
new transports.File({ filename: 'app.log' })
],
});
// Middleware to log user activities
const logUserActivity = (req, res, next) => {
const user = req.user || 'anonymous'; // Assuming req.user contains user info
const logMessage = {
method: req.method,
url: req.url,
user: user,
ip: req.ip,
userAgent: req.headers['user-agent']
};
logger.info('User activity', logMessage);
next();
};
// Function to log specific user actions
const logAction = (action, user) => {
const logMessage = {
action: action,
user: user,
timestamp: new Date().toISOString()
};
logger.info('User action', logMessage);
};
module.exports = { logger, logUserActivity, logAction };