A brief analysis of how the Node.js+Winston library builds a simple logging function

青灯夜游
Release: 2021-10-20 10:01:21
forward
1581 people have browsed it

This article will introduce to you how to use the Winston library to build a simple logging function inNode.js. I hope it will be helpful to everyone!

A brief analysis of how the Node.js+Winston library builds a simple logging function

Winstonis one of the powerful and flexibleNode.jsopen source log libraries. In theory,Winstonis a logger that can record all information. This is a highly intuitive tool that is easy to customize. The logic behind it can be adjusted by changing a few lines of code. It makes logging to persistent storage locations such as databases or files simple and easy. [Recommended learning: "nodejs Tutorial"]

WinstonProvides the following functions:

  • Centralized control of logging And time: Change the code in one place to
  • Control where logs are sent: Save logs to multiple destinations synchronously (such as Elasticsearch, MongoDB, Postgres, etc.).
  • Customized log format: With prefixes such as timestamp, color log level, JSON format, etc.

winston practice

The practice code will add the logging function to the projectpretender-service, and install the dependencies:

npm install winston --save
Copy after login

The next step is to initializelogger, since there is already alogger.jsfile in the project, create anotherwinstonLogger.jshere, the code is as follows:

const { createLogger, format, transports } = require("winston"); module.exports = createLogger({ transports: [ new transports.File({ filename: "logs/server.log", level: "info", format: format.combine( format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }), format.align(), format.printf( (info) => `${info.level}: ${[info.timestamp]}: ${info.message}` ) ), }), ], });
Copy after login

Passed Call thecreateLoggerfunction in thewinstonlibrary to initialize the logger. In thetransportsobject, you can provide a filename to store the logs in a file. By default, logging is unformatted and printed as a JSON string with two parameters, the log message and the level.

Next, modify the previousloggerand add thewinstonlogger. Please refer to the code for the specific modification method. Here is how to use it:

const winlogger = require("./winstonLogger"); winlogger.info("日志内容");
Copy after login

After executing the program, the corresponding log file can be generated in the root directorylogs/server.log

A brief analysis of how the Node.js+Winston library builds a simple logging function

You can also change the log level, Modifyloggerand only usewinstoninconsole.errormode:

A brief analysis of how the Node.js+Winston library builds a simple logging function

records the database connection Error messages, the above information is for demonstration only.

Multiple transports

winstonAllows setting multipletransport, changecreateLogger# inwinstonLogger.js## The function is as follows:

const { createLogger, format, transports } = require("winston"); module.exports = createLogger({ format: format.combine( format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }), format.align(), format.printf((i) => `${i.level}: ${[i.timestamp]}: ${i.message}`) ), transports: [ new transports.File({ filename: "logs/info.log", level: "info", format: format.combine( format.printf((i) => i.level === "info" ? `${i.level}: ${i.timestamp} ${i.message}` : "" ) ), }), new transports.File({ filename: "logs/error.log", level: "error", }), ], });
Copy after login

Execute the program again, you will see the

error.logandinfo.logfiles, because inloggerinfois not set in , so the content ofinfo.logis empty, and the content oferror.logis the same as above.

Multiple loggers

winstonAllows the setting of multipleloggers. In actual projects, a logger can be created for each modulelogger, the following code creates a user logger and login verification recorder:

const { createLogger, format, transports } = require("winston"); const customFormat = format.combine( format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }), format.align(), format.printf((i) => `${i.level}: ${[i.timestamp]}: ${i.message}`) ); const globalLogger = createLogger({ format: customFormat, transports: [ new transports.File({ filename: "logs/info.log", level: "info", format: format.combine( format.printf((i) => i.level === "info" ? `${i.level}: ${i.timestamp} ${i.message}` : "" ) ), }), new transports.File({ filename: "logs/error.log", level: "error", }), ], }); const authLogger = createLogger({ transports: [ new transports.File({ filename: "logs/authLog.log", format: customFormat, }), ], }); module.exports = { globalLogger: globalLogger, authLogger: authLogger, };
Copy after login

The modified code creates a global logger

globalLoggerand an authentication loggerauthLogger, corresponding modificationlogger.js:

const { globalLogger } = require("./winstonLogger"); globalLogger.error(message);
Copy after login

Daily rolling log file

As mentioned in the best practices introduced earlier, according to the specific Split the log file according to the conditions, usually according to date and size, and set the number of days to save the log. In order to realize these requirements, it is necessary to install a

Winstonrelated dependency library.

npm install winston-daily-rotate-file --save
Copy after login

After the installation is complete, use the following code to update to the

winstonLogger.jsfile:

const { createLogger, format, transports } = require("winston"); require("winston-daily-rotate-file"); const customFormat = format.combine( format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }), format.align(), format.printf((i) => `${i.level}: ${[i.timestamp]}: ${i.message}`) ); const defaultOptions = { format: customFormat, datePattern: "YYYY-MM-DD", zippedArchive: true, maxSize: "20m", maxFiles: "14d", }; const globalLogger = createLogger({ format: customFormat, transports: [ new transports.DailyRotateFile({ filename: "logs/info-%DATE%.log", level: "info", ...defaultOptions, }), new transports.DailyRotateFile({ filename: "logs/error-%DATE%.log", level: "error", ...defaultOptions, }), ], }); const authLogger = createLogger({ transports: [ new transports.DailyRotateFile({ filename: "logs/authLog-%DATE%.log", ...defaultOptions, }), ], }); module.exports = { globalLogger: globalLogger, authLogger: authLogger, };
Copy after login
Run the project and you can see the log file:

A brief analysis of how the Node.js+Winston library builds a simple logging function

At this point, the basic usage guide of

Winstonhas been introduced. The above can basically meet the needs of daily projects.

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of A brief analysis of how the Node.js+Winston library builds a simple logging function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!