Node.js Log Processing Module log4js_node.js

Source: Internet
Author: User

Log4js is one of the most node.js in log processing. This is an advantage over console or TJ's debug, especially for node.js projects that are put into production:

    1. Log rating
    2. Log category
    3. Log Drop Disk

This article will give you a comprehensive introduction of the LOG4JS, so that you can use the LOG4JS in the project, development and debugging easy, online better monitoring or troubleshooting problems.

His experiment

The following three lines of code show you the simplest use of LOG4JS:

File:simplest.js
var log4js = require (' Log4js ');
var logger = Log4js.getlogger ();
Logger.debug ("Time:", New Date ());

Call. GetLogger () to obtain the Logger instance of LOG4JS, which is consistent with the console and can be invoked with the. Debug (also,. info,. Error, etc.) to output the log.

Run node Simplest.js, 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, preceded by a specifier [2016-08-21 00:01:24.852] [DEBUG] [default] after the table.

Is it also easy to use, well, before we dive into LOG4JS advanced usage, let's familiarize ourselves with the concepts in several log4js.

Level

This is not difficult to understand, is the classification of the log. The log has a rating, LOG4JS can better show us the log (different levels of log in the console using different colors, such as the error is usually red), in the production can have a choice of the log, such as to avoid some belong to. The sensitive information used by debug is leaked.

The LOG4JS log is divided into nine levels, with the names and weights of each level 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")
}

Last diagram:

All two levels are not used directly in the business code. The remaining seven are the seven methods corresponding to the Logger instance respectively,. Trace. Debug. Info .... In other words, when you call these methods, you are setting the level of these logs. Therefore, DEBUG in the previous [2016-08-21 00:01:24.852] [debug] [default]-time:2016-08-20t16:01:24.852z is the level of this log.

Type

LOG4JS also has a concept of category (type), you can set a type of Logger instance, according to another dimension to distinguish the log:

File:set-catetory.js
var log4js = require (' Log4js ');
var logger = Log4js.getlogger (' example ');
Logger.debug ("Time:", New Date ());

When you get a Logger instance through GetLogger, the only argument you can pass is loggercategory (such as ' example '), which specifies which category the Logger instance belongs to. This is the same as TJ's debug:

var debug = require (' Debug ') (' worker ');

SetInterval (function () {
 debug (' Doing some work ');
1000);

The ' worker ' in debug is also classified as a log. Okay, come back. Run node Set-catetory.js:

[2016-08-21 01:16:00.212] [DEBUG] example-time:2016-08-20t17:16:00.212z
The only difference from the previous [2016-08-21 00:01:24.852] [DEBUG] [default]-time:2016-08-20t16:01:24.852z is that [default] became example.

What is the use of that category, which is more flexible than the level, provides a second dimension for logging, for example, you can set different category for each file, such as in Set-catetory.js:

File:set-catetory.js
var log4js = require (' Log4js ');
var logger = Log4js.getlogger (' set-catetory.js ');
Logger.debug ("Time:", New Date ());

You can see from the log [2016-08-21 01:24:07.332] [DEBUG] set-catetory.js-time:2016-08-20t17:24:07.331z that this log comes from the Set-catetory.js file. Alternatively, use different category for different node package to distinguish which module the log originates from.

Appender

OK, now the log has a level and category, solve the log at the entrance grading and classification issues, and in the LOG4JS, the log export problem (that is, where the log output) by the Appender to solve.

Default Appender

The following is the LOG4JS internal default Appender setting:

Log4js.js
defaultconfig = {
 appenders: [{
  type: ' Console '
 }]
}

As you can see, the log is exported to the console by default when no configuration is made on the LOG4JS.

Set up your own Appender

We can set the Appender we want by log4js.configure.

File:custom-appender.js
var log4js = require (' Log4js ');
Log4js.configure ({
 appenders: [{
  type: ' file ',
  filename: ' Default.log '
 }]
})
var logger = Log4js.getlogger (' Custom-appender ');
Logger.debug ("Time:", New Date ());

In the example above, we output the log to a file, run code, LOG4JS creates a file named Default.log in the current directory, [2016-08-21 08:43:21.272] [DEBUG] Custom-appender-time: 2016-08-21T00:43:21.272Z output to the file.

The Appender provided by LOG4JS

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

Datefile: Log output to file, log file can be a specific date mode scrolling, such as today output to default-2016-08-21.log, tomorrow output to Default-2016-08-22.log;
SMTP: output log to mail;
Mailgun: Through the Mailgun API output log to Mailgun;
Levelfilter can be filtered by level;
And so on some other appender, you can see all the lists here.

Filtering levels and Categories

We can adjust the configuration of the Appender and filter the levels and categories of the logs:

File:level-and-category.js
var 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 ());

Running, adds a log to the Default.log:

[2016-08-21 10:08:21.630] [DEBUG] category1-time:2016-08-21t02:08:21.629z
Take a look at the code:

Use Loglevelfilter and level to filter the levels of the logs, which are significant or equal to the DEBUG log will be output. This is also the meaning of the log level weights mentioned before;
By category to select the category to output the log, Category2 the following log is filtered out and the configuration accepts an array, such as [' Category1 ', ' category2 '], so that all two categories of logs will be exported to the file.

Layout

Layout is an advanced feature provided by LOG4JS, which allows us to customize the format of each output log by Layout. LOG4JS has four types of formats built in:

Messagepassthrough: Only output the contents of the log;
Basic: In front of the contents of the log will be added time, log level and category, usually the default layout log;
Colored/coloured: On the basis of basic to add color to the log, Appender Console is the default use of this layout;
Pattern: This is a special type that can be used to define whatever format you want.
An example of pattern:

File:layout-pattern.js
var 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 a built-in log4js containing specifier that can be used to export some meta information, more details, and refer to LOG4JS documentation.

A picture to illustrate the positioning of Logger, Appender and Layout.

Combat: Output Node application ACCESS log Access.log

In order to facilitate the search problem, in the production environment will often record the application request access log. How to use the LOG4JS how to achieve it, directly on the code:

File:server.js
var 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 (' front-end Foreign Periodical Review ');
App.listen (5000);

Look at the things we've done:

A appender is configured, from which the category is selected as Access log and exported to a scrolling file;
Log4js.getlogger (' Access ') gets a Logger instance of access, which is passed to the Log4js.connectlogger middleware, which collects access information and is typed through this instance.
Start the server, Access http://localhost:5000, you will find a directory of more than a file called Access.log-2016-08-21.log, which has two logs:

[2016-08-21 14:34:04.752] [INFO] Access-:: 1--"get/http/1.1" "" 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 "
[2016-08-21 14:34:05.002] [INFO] Access-:: 1--"Get/favicon.ico http/1.1" 404 "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 classification and Appender functions of the Log4js log, we output the access log to a rolling update file.

Summarize

This article provides a comprehensive introduction to the use of LOG4JS, compared with console or simple log tools, LOG4JS is more complex to use, of course, more powerful, suitable for the use of production-level applications. If you are interested, please leave a message to tell the foreign periodical gentleman, next May introduce how to do the configuration management in the Node application.

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.