Use logging to a file
Fri Apr 14 2023 09:05:57 GMT+0000 (Coordinated Universal Time)
Saved by
@mindplumber
#javascript
#uuid
#guid
// Here's how you can set up logging to a file:
// Install the winston package by running the following command in your terminal:
npm install winston
// Create a logger.js file in your project directory with the following code:
// This creates a logs folder in the same directory as your logger.js module,
// and places the log files inside it. You can adjust the logsDir variable
// to specify a different directory if desired.
const path = require('path');
const winston = require('winston');
const { createLogger, format, transports } = winston;
const { combine, timestamp, printf } = format;
const logFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const logsDir = path.join(__dirname, 'logs');
const logger = createLogger({
level: 'info',
format: combine(
timestamp(),
logFormat
),
transports: [
new transports.Console(),
new transports.File({
filename: path.join(logsDir, 'error.log'),
level: 'error',
maxsize: 5242880, // 5MB
maxFiles: 5,
tailable: true
}),
new transports.File({
filename: path.join(logsDir, 'combined.log'),
maxsize: 5242880, // 5MB
maxFiles: 5,
tailable: true
})
]
});
module.exports = logger;
content_copyCOPY
Comments