In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article shows you how to deal with the log in node, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
I. Technology selection
Three mainstream technologies are selected for comparison:
1.1 log4js
Log4js is a node log management tool that can export logs in custom formats to various channels. For the log output of the console, the color log can be presented, and for the log output of file mode, the log can be cut according to the file size or date.
Developers familiar with java will find that log4js is very similar to log4j, a commonly used java logging tool. Yes, log4js is the JavaScript version of log4j and is used in a similar way.
1.2 winston
Winston is also a very popular node log management tool that supports multiple transfers. The default output format is json, or you can customize the output format. If you want to cut the log, you also need to use the winston-daily-rotate-file module.
1.3 PM2
PM2 is actually a node process management tool, with performance monitoring, process daemon, load balancing, log management and other functions. Using PM2 for log management requires only the addition of console method calls to the project, without the need to add additional code. To cut the log, you need to use pm2-logrotate.
Since many of the server-side systems within the team are based on java, most of these systems use log4j to generate logs. Log management related log collection system and log query system support the log in log4j format better, so I finally choose the JavaScript version of log4j log4js to generate logs, the following will introduce the basic use of log4js.
II. Basic concept 2.1 Log level
The default logging level for log4js is divided into 9 levels, arranged from lowest to highest priority as follows:
ALL
< TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF 当日志级别为ALL时,会输出所有级别的日志 当日志级别为OFF时,则会关闭日志,不会有任何日志输出 用户还可以根据自己的需要自定义日志级别 2.2 appender appender 主要是用来定义以怎样的方式输出,输出到哪里。可以将日志写入到文件、发送电子邮件、通过网络发送数据等。可以通过配置对象的appenders属性定义多个appender。 appender的常用类型有: console:控制台输出 file:文件输出 dateFile:按日期切割的文件输出 2.3 category category 是日志的类型,指定一个或者多个appender为某种类型的日志,不同类型的日志可以指定不同的日志级别。可以通过配置对象的categories属性定义多个category。必须指定default类型,用来获取默认的Logger实例,还可以通过类型名来获取指定类型的Logger实例。 综上所诉,appender 定义了日志输出到哪里,category 将appender 进行了分类,不同类型指定不同的日志级别。 三、使用log4js3.1 安装 npm install log4js --save 或者 yarn add log4js 3.2 简单使用 下面示例利用log4js创建日志对象logger,通过调用logger.debug、logger.info、logger.warn、logger.error 等方法将日志输出到控制台和日志文件。 util/log4jsLogger.js const path = require('path');const log4js = require('log4js');// 配置log4jslog4js.configure({ appenders: { // 控制台输出 console: { type: 'console' }, // 日志文件 file: { type: 'file', filename: path.join(__dirname, '../../logs/server.log')} }, categories: { // 默认日志 default: { appenders: [ 'file', 'console' ], level: 'debug' }, }});// 获取默认日志const logger = log4js.getLogger();module.exports = logger; server.js 再通过调用logger. info 输出INFO 级别的日志,这里web开发框架使用的Koa。 const Koa = require('koa');const router = require('./router');const logger = require('./util/log4jsLogger');const port = 3000;const app = new Koa() .use(router.routes()) .use(router.allowedMethods());app.listen(port, () =>{logger.info (`log ${port} `);}); 3.3log format
Log4js sets the log format through layout. The built-in layout includes:
Basic: basic log format including timestamp, log level, and log type
Colored: the format is the same as that of basic, except that different levels of logs show different colors
Dummy: only outputs the contents of the first parameter, without timestamp, log level, log classification and other information
Pattern: layout with customizable format
Example:
Default log format:
[2020-04-01T11:33:43.317] [INFO] default-Server running on port 3000
Custom log format:
2020-04-01 11 3343.317 [INFO] Server running on port 3000
Code:
/ / Custom log format const layout = {type: 'pattern', pattern:'% d {yyyy-MM-dd hh:mm:ss.SSS} [% p]% m'} Log4js.configure ({appenders: {/ / console output console: {type: 'console'}, / / log file Set the log format by setting layout: file: {type: 'file', filename: path.join (_ _ dirname,'.. / logs/server.log'), layout}}, categories: {/ / default log default: {appenders: ['file',' console'], level: 'debug'},}}) 3.4 Log cutting
If all the logs are output to one file, the log files will become larger and larger, resulting in inconvenient backup and viewing of the logs. It is possible to slice logs by date by specifying appender as the dateFile type.
/ / log4js.configure log configuration ({appenders: {/ / console output console: {type: 'console'}, / / log file file: {type:' dateFile', filename: path.join (_ _ dirname,'.. / logs/server.log') / / File name suffix format pattern: '.log}}, categories: {/ / default log default: {appenders: [' file', 'console'], level:' debug'},}})
If the service is deployed on April 1, the log will be output to the service.log file, and by April 2, the service.log will be renamed to server.log.2020-04-01, then a new service.log file will be created, and the new log will continue to be exported to the service.log file.
3.5 Export multiple files
The following example outputs logs at the level of error or above to server-error.log in addition to the full log to server.log.
Util/log4jsLogger.js
Const path = require ('path'); const log4js = require (' log4js') / / configure log4jslog4js.configure ({appenders: {/ / console output console: {type: 'console'}, / / all log files allFile: {type:' file', filename: path.join (_ _ dirname,'.. / logs/server.log')}, / / error log file errorFile: {type: 'file' Filename: path.join (_ _ dirname,'.. /.. / logs/server-error.log')}}, categories: {/ / default log Output debug and above log default: {appenders: ['allFile',' console'], level: 'debug'}, / / error log, output error and above log error: {appenders: [' errorFile'], level: 'error'},}}) / / get default log const defaultLogger = log4js.getLogger (); / / get error level log const errorLogger = log4js.getLogger ('error'); / / log agent, calling both default log and error log const loggerProxy = {}; const levels = log4js.levels.levels;levels.forEach (level = > {const curLevel = level.levelStr.toLowerCase (); loggerProxy [curLevel] = (... params) = > {defaultLogger [curLevel] (... params)) ErrorLogger [curLevel] (.. params);}}); module.exports = loggerProxy;3.6 override console
Because you need to call logger.debug, logger.info, logger.warn, logger.error and other methods to use log4js, for projects that have called the console method to output the log, all the projects that have called the logger method will call the logger method, which is troublesome to change. You can use log4js to output the log by overriding the log4js method.
/ * create log agent method * @ param logLevel log level * @ param logger log object * @ return {function} * / function createLogProxy (logLevel, logger) {return (... param) = > {logger [logLevel] (.. param);};} console.log = createLogProxy ('debug', logger); console.info = createLogProxy (' info', logger); console.warn = createLogProxy ('warn', logger) Console.error = createLogProxy ('error', logger); the above is how to deal with logs in node. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
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.