winston
is very popular logger for Node.js, providing simple API to store and format the logs. It provides support for custom logging levels, streaming logs and custom transports to save the logs. Another useful feature is the ability to query the logs based on filters like duration and keywords.
In this post, we’ll explore how winston
can be used to log to the console as well as a file.
Install dependencies
Add winston
and winston-daily-rotate-file
as dependencies.
yarn add winston winston-daily-rotate-file
Configure the logger
Create a file src/helper/default.logger.ts
and add the following code.
// src/helper/default.logger.ts
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import { environment } from '../configuration/environment';
export const logger = winston.createLogger({
environment.logLevel,
level: winston.format.simple(),
format:
transports: [new winston.transports.Console(),
new DailyRotateFile({
environment.logFile,
filename: environment.logDir,
dirname: 'YYYY-MM-DD',
datePattern: true,
zippedArchive: '14d',
maxFiles: '20m'
maxSize:
})
] });
Here, we’ve configured winston
with two transports, Console
and DailyRotateFile
. DailyRotateFile
will write the logs to logs/app.log
file which’ll be rotated every day or if it exceeds the size of 20 MB. The logs will be kept for up to 14 days in zip archives.
To use the logger, import it and call the logging methods (info
, debug
, etc).
// import the logger
import { logger } from './helper/default.logger';
// other configurations and initializations
// server
app.listen(port, () => logger.info(`Server started at http://localhost:${port}`));
Start the application; you should see app.log
in logs
directory and the same logs printed on the console.