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!
Winstonis one of the powerful and flexibleNode.js
open 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:
The practice code will add the logging function to the projectpretender-service, and install the dependencies:
npm install winston --save
The next step is to initializelogger
, since there is already alogger.js
file in the project, create anotherwinstonLogger.js
here, 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}` ) ), }), ], });
Passed Call thecreateLogger
function in thewinston
library to initialize the logger. In thetransports
object, 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 previouslogger
and add thewinston
logger. Please refer to the code for the specific modification method. Here is how to use it:
const winlogger = require("./winstonLogger"); winlogger.info("日志内容");
After executing the program, the corresponding log file can be generated in the root directorylogs/server.log
You can also change the log level, Modifylogger
and only usewinston
inconsole.error
mode:
records the database connection Error messages, the above information is for demonstration only.
winston
Allows setting multipletransport
, changecreateLogger# in
winstonLogger.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", }), ], });
error.logand
info.logfiles, because in
loggerinfo
is not set in , so the content of
info.logis empty, and the content of
error.logis the same as above.
winstonAllows the setting of multiple
loggers. In actual projects, a logger can be created for each module
logger, 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, };
globalLoggerand an authentication logger
authLogger, corresponding modification
logger.js:
const { globalLogger } = require("./winstonLogger"); globalLogger.error(message);
Winstonrelated dependency library.
npm install winston-daily-rotate-file --save
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, };
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!