Node. js log processing module log4js

Source: Internet
Author: User
Today, we will share with you a common third-party package for writing logs in Node. js: Log4js. Next we will discuss in detail. log4js is one of the most popular log processing modules in Node. js. It has advantages over console or TJ debug, especially for the Node. js projects that are put into production. The following are indispensable:

Log Classification

Log category

Log storage

This article will give you a comprehensive introduction to log4js, so that you can easily use log4js in your project, make development and debugging easy, and better monitor or troubleshoot problems online.

Knife Test

The following three lines of code demonstrate the simplest use of log4js:

// file: simplest.jsvar log4js = require('log4js');var logger = log4js.getLogger();logger.debug("Time:", new Date());

Call. getLogger () can obtain the Logger instance of log4js. The usage of this instance is consistent with that of the console and can be called. debug (also has. info ,. to output logs.

Run node simplest. js and the output is as follows:

$node simplest.js[2016-08-21 00:01:24.852] [DEBUG] [default] - Time: 2016-08-20T16:01:24.852Z

Time: 2016-08-20T16: 01: 24.852Z is the content we want to output. The preceding content includes the description [00:01:24. 852] [DEBUG] [default] And then returns to the table.

Is it easy to use? Well, before we go deep into the advanced usage of log4js, let's familiarize ourselves with several concepts in log4js.

Level

This is not difficult to understand, that is, the log classification. After logs are classified, log4js can better display logs for US (logs of different levels are in different colors on the console, for example, errors are usually red ), you can select disk logging during production. sensitive information used by debug is leaked.

Log4js logs are classified into nine levels. The names and weights of each level are as follows:

{ ALL: new Level(Number.MIN_VALUE, "ALL"), TRACE: new Level(5000, "TRACE"), DEBUG: new Level(10000, "DEBUG"), INFO: new Level(20000, "INFO"), WARN: new Level(30000, "WARN"), ERROR: new Level(40000, "ERROR"), FATAL: new Level(50000, "FATAL"), MARK: new Level(9007199254740992, "MARK"), // 2^53 OFF: new Level(Number.MAX_VALUE, "OFF")}

Previous figure:

The two levels of all off are not directly used in the Business Code. The remaining seven are the seven methods corresponding to the Logger instance, respectively. trace. debug. info .... That is to say, when you call these methods, it is equivalent to setting a level for these logs. Therefore, the DEBUG in [00:01:24. 852] [DEBUG] [default]-Time: 2016-08-20T16: 01: 24.852Z is the level of this log.

Type

Another concept of log4js is category (type). You can set the type of a Logger instance to differentiate logs by another dimension:

// file: set-catetory.jsvar log4js = require('log4js');var logger = log4js.getLogger('example');logger.debug("Time:", new Date());

When getLogger is used to obtain a Logger instance, the only parameter that can be passed is loggerCategory (for example, 'example '). This parameter is used to specify the category of the Logger instance. This is the same as TJ debug:

var debug = require('debug')('worker'); setInterval(function(){ debug('doing some work');}, 1000);

In debug, The 'worker' is also a log classification. Okay, back to run node set-catetory.js:

[01:16:00. 212] [DEBUG] example-Time: 2016-08-20T17: 16: 00.212Z
The only difference between [00:01:24. 852] [DEBUG] [default]-Time: 2016-08-20T16: 01: 24.852Z is that [default] is changed to example.

What is the use of the category? It is more flexible than the level, providing a second dimension for the log, for example, you can set different category for each file, for example in a set-catetory.js:

// file: set-catetory.jsvar log4js = require('log4js');var logger = log4js.getLogger('set-catetory.js');logger.debug("Time:", new Date());

You can see from the log [01:24:07. 332] [DEBUG] set-catetory.js-Time: 2016-08-20T17: 24: 07.331Z, this log is from the set-catetory.js file. Or use different category for different node packages, which can distinguish the module where logs come from.

Appender

Now the log has the level and category, which solves the log grading and classification problems at the entrance. In log4js, the log export problem (that is, where the log is output) it is solved by Appender.

Default appender

The default appender settings in log4js are as follows:

// log4js.jsdefaultConfig = { appenders: [{  type: "console" }]}

As you can see, logs are output to the console by default when no configuration is made for log4js.

Set your own appender

We can set the desired appender through log4js. configure.

// file: custom-appender.jsvar log4js = require('log4js');log4js.configure({ appenders: [{  type: 'file',  filename: 'default.log' }]})var logger = log4js.getLogger('custom-appender');logger.debug("Time:", new Date());

In the preceding example, we output logs to a file and run the code. log4js creates a file named default in the current directory. log File, [08:43:21. 272] [DEBUG] custom-appender-Time: 2016-08-21T00: 43: 21.272Z is output to this file.

Appender provided by log4js

Both the Console and File are the appender provided by log4js, in addition to the following:

DateFile: the log output to the file, the log file can be customized date mode scroll, for example, output to default-2016-08-21.log today, output to default-2016-08-22.log tomorrow;
SMTP: outputs logs to emails;
Mailgun: Output logs to Mailgun through the Mailgun API;
LevelFilter can be filtered by level;
And some other appender. You can see all the list here.

Filter level and category

We can adjust the appender configuration to filter the log level and category:

// file: level-and-category.jsvar log4js = require('log4js');log4js.configure({ appenders: [{  type: 'logLevelFilter',  level: 'DEBUG',  category: 'category1',  appender: {   type: 'file',   filename: 'default.log'  } }]})var logger1 = log4js.getLogger('category1');var logger2 = log4js.getLogger('category2');logger1.debug("Time:", new Date());logger1.trace("Time:", new Date());logger2.debug("Time:", new Date());

Run, add a log in default. log:

[10:08:21. 630] [DEBUG] category1-Time: 2016-08-21T02: 08: 21.629Z
Let's take a look at the Code:

LogLevelFilter and level are used to filter the log level. logs with major ownership or equal to DEBUG will be output. This is also the significance of the previously mentioned log-level weight;
Use category to select the log category to be output. logs under category2 are filtered out. This configuration also accepts an array, for example, ['category1', 'category2']. in this way, logs of both categories are output to the file.

Layout

Layout is an advanced function provided by log4js. With layout, We can customize the format of each output log. Log4js has four built-in formats:

MessagePassThrough: only the log Content is output;
Basic: add the time, log level, and category before the log Content. Generally, the default log layout is used;
Colored/colored: add color to the log based on basic. This layout is used by default in the appender Console;
Pattern: this is a special type that can be used to define any format you want.
Example of a pattern:

// file: layout-pattern.jsvar log4js = require('log4js');log4js.configure({ appenders: [{  type: 'console',  layout: {   type: 'pattern',   pattern: '[%r] [%[%5.5p%]] - %m%n'  } }]})var logger = log4js.getLogger('layout-pattern');logger.debug("Time:", new Date());

% R % p $ m $ n is the built-in include specifier of log4js. You can use this to output some meta information. For more details, refer to the log4js documentation.

The following figure illustrates how Logger, Appender, and Layout are located.

Practice: output the ACCESS log access. log of the Node Application

For ease of problem query, application request access logs are often recorded in the production environment. Then, how can I use log4js to implement it? directly add the Code:

// File: server. jsvar log4js = require ('log4js'); var express = require ('express '); log4js. configure ({appenders: [{type: 'datefile', filename: 'Access. log', pattern: '-yyyy-MM-dd.log', alwaysIncludePattern: true, category: 'access'}]}); var app = express (); app. use (log4js. connectLogger (log4js. getLogger ('access'), {level: log4js. levels. INFO}); app. get ('/', function (req, res) {res. send ('frontend publication comments ');}); app. listen (0, 5000 );

Let's see what we have done:

An appender is configured to select access logs from logs and output them to a rolling file;
Log4js. getLogger ('access') obtains a Logger instance of the access type and passes it to log4js. connectLogger middleware. This middleware collects access information and uses this instance to output it.
Start the server, access http: // localhost: 5000, you will find a file named access. log-2016-08-21.log in the directory, there are two logs:

[14:34:04. 752] [INFO] access-: 1--"GET/HTTP/1.1" 200 18 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) appleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
[14:34:05. 002] [INFO] access-: 1--"GET/favicon. ico HTTP/1.1 "404 24" http: // localhost: 5000/"" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) chrome/52.0.2743.116 Safari/537.36"

Through the log4js log classification and appender function, we output the access log to a rolling update file.

Summary

This article provides a comprehensive introduction to the use of log4js. Compared with the console or a simple log tool, log4js is more complex to use, of course, more powerful, and suitable for production-level applications. If you are interested, please leave a message to inform the magazine. Next, we may introduce you to how to perform configuration management in the Node application.

For more articles about the Node. js log processing module log4js, refer to the PHP Chinese website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.