In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "Node.js+Winston library how to build a simple log function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Node.js+Winston library how to build a simple log function" bar!
Winston is one of the powerful and flexible Node.js open source log libraries. In theory, Winston is a logger that can record all information. This is a highly intuitive tool that is easy to customize. You can adjust the logic behind it by changing a few lines of code. It makes it easy to log to persistent storage locations such as databases or files. [recommended: "nodejs tutorial"]
Winston provides the following features:
Centrally control the way and time of logging: change the code in one place
Control where logs are sent: synchronize logs to multiple destinations (such as Elasticsearch, MongoDB, Postgres, etc.).
Custom log format: prefixed with timestamp, color log level, JSON format, etc.
Winston practice
The practice code will add logging to the project pretender-service and install dependencies:
Npm install winston-save
Next, you need to initialize logger. Since a logger.js file already exists in the project, create another winstonLogger.js here, 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}`)),}),],})
Initialize the logger by calling the createLogger function in the winston library. In the transports object, you can provide a file name to store the log in the file. By default, log records are not formatted and printed as JSON strings with two parameters, log messages, and levels.
The following is to modify the previous logger and add the winston logger to it. For more information on how to modify it, please see the code. Here is how to use it:
Const winlogger = require (". / winstonLogger"); winlogger.info ("log content")
After executing the program, the corresponding log file logs/server.log can be generated in the root directory.
You can also change the log level, modify logger, and use winston only in console.error mode:
The database connection error message is recorded, and the above information is for demonstration purposes only.
Multiple transports
Winston allows you to set multiple transport. Change the createLogger function in winstonLogger.js 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",}),],})
When you execute the program again, you will see the error.log and info.log files. Since info is not set in logger, the content of info.log is empty and the content of error.log is the same as above.
Multiple loggers
Winston allows you to set up multiple logger. In a real project, you can create a logger logger for each module, as shown in the following code to create a user logger and login authentication logger:
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,}
The modified code creates a global logger globalLogger and an authentication logger authLogger, corresponding to the modified logger.js:
Const {globalLogger} = require (". / winstonLogger"); globalLogger.error (message); daily scrolling log file
As mentioned in the best practices described earlier, log files are segmented according to specific conditions, usually by date and size, and by setting the number of days to save the log. To meet these requirements, it is necessary to have an installation of a Winston-related dependent library.
Npm install winston-daily-rotate-file-save
Update to the winstonLogger.js file after the installation is complete with the following code:
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,}
Running the project, you can see the log file:
Thank you for reading, the above is the content of "how to build simple logging function in Node.js+Winston library". After the study of this article, I believe you have a deeper understanding of how to build simple logging function in Node.js+Winston library. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.