Play Nodejs Log Management Log4js (GO)

Source: Internet
Author: User

Transferred from: http://blog.fens.me/nodejs-log4js/

Objective

Logs are critical to any application. With the express framework in Nodejs and no log modules available, we can select Log4js to complete the logging function.

If used in Java log4j classmate, certainly to the log is not unfamiliar, learn log4js will be more handy.

Article directory:

    1. Default console Output
    2. Output logs via Log4js
    3. Configure LOG4JS and express Framework Integration
    4. According to the project configuration Log4js
    5. Optimizing the LOG4JS structure

1. Default console Output

When we use the Express framework, when the development mode launches the Nodejs app with node or supervisor, the console displays the following logs.

GET/CSS/BOOTSTRAP.MIN.CSS 3041msGET/CSS/MY.CSS 3040msGET/js/bootstrap.min.js 3044msGET/js/jquery-1.9.1.min.js 3046msGET/js/holder.js 3043msGET/cat/json/latest 2006msGET/cat/json/master 2004msGET/cat/json/classic 2002msGET/about 2006msGET/CSS/BOOTSTRAP.MIN.CSS 3042msGET/CSS/MY.CSS 3042msGET/js/bootstrap.min.js 3042msGET/js/jquery-1.9.1.min.js 3041msGET/js/holder.js 3041msGET/js/bootstrap.min.js 3041msGET/3046msGET/js/jquery-1.9.1.min.js 3042msGET/CSS/MY.CSS 3041msGET/CSS/BOOTSTRAP.MIN.CSS 3041msGET/js/bootstrap.min.js 3042msGET/js/holder.js 3042msGET/cat/json/latest 2003msGET/cat/json/master 2002msGET/cat/json/classic 2002msGET/admin/30413msGET/CSS/BOOTSTRAP.MIN.CSS 3043msGET/js/jquery-1.9.1.min.js 3042msGET/CSS/MY.CSS 3042msGET/js/bootstrap.min.js 3041msGET/js/holder.js 304 2ms

We can also print some console logs in the code, using Console.log ().

Modify Routes/index.js

function (req, res) {    Console.log ("This was an index page!" );    Res.render (' index ', {          title:' home page |moive.me ',          page:' index '      }) ;

To access the page, the results are as follows.

This is an index page!  /304/css/bootstrap.min.css 304/css/my.css 304 /js/jquery-1.9.1.min.js 304 /js/holder.js 304/js/bootstrap.min.js 304 28ms

The result of this output is displayed on the console, and once the server restarts the log is lost. For program development, this output is sufficient. But in a production environment, we want to be able to save the console output to a file, and need more information, not just the default simplified log information.

Since the express framework does not have a log function, we need to introduce the LOG4JS package to complete this function.

2. Output logs via Log4js

Let's take a look at what the log output through the Log4js looks like, and the next section describes the specific configuration.

This is an index page!GET/30417ms[2013-06-19 17:45:55.981] [INFO] normal-127.0.0.1--"get/http/1.1" 304-"http://localhost:3000/admin/" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/CSS/BOOTSTRAP.MIN.CSS 30410ms[2013-06-19 17:45:56.015] [INFO] normal-127.0.0.1--"Get/css/bootstrap.min.css http/1.1" 304-"Http://localhost:3000/admin/crawler/youku" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/CSS/MY.CSS 3048ms[2013-06-19 17:45:56.017] [INFO] normal-127.0.0.1--"Get/css/my.css http/1.1" 304-"Http://localhost:3000/admin/crawler/youku" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/js/jquery-1.9.1.min.js 30419ms[2013-06-19 17:45:56.031] [INFO] normal-127.0.0.1--"Get/js/jquery-1.9.1.min.js http/1.1" 304-"http://localhost:3000/admin/" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/js/bootstrap.min.js 30413ms[2013-06-19 17:45:56.037] [INFO] normal-127.0.0.1--"Get/js/bootstrap.min.js http/1.1" 304-"http://localhost:3000/admin/"" mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36 "GET/js/holder.js 30420ms[2013-06-19 17:45:56.040] [INFO] normal-127.0.0.1--"Get/js/holder.js http/1.1" 304-"http://localhost:3000/admin/"" mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36 "

The same request, the console outputs a lot more results, the full Web server log format.
This is what the production environment needs! The information is richer and is in the same format as Nginx and Apache.

3. Configure LOG4JS and express Framework Integration

Download LOG4JS Package

~ npm install log4js[email protected] node_modules\log4js├── [email protected]├── [email protected]├── [email protected]└── [email protected]

Modify App.js

~VI app.jsvarLOG4JS = require (' Log4js ')); Log4js.configure ({appenders: [{type:' Console '},//Console Output{type:' File ',//file OutputFileName: ' Logs/access.log ', Maxlogsize:1024, Backups:3, Category:' Normal '     }  ]});varLogger = Log4js.getlogger (' normal ')); Logger.setlevel (' INFO ');...//app.use (...)//app.use (...)App.use (Log4js.connectlogger (logger, {Level:log4js.levels.INFO})); App.use (app.router);

I need to configure the LOG4JS in App.js.

The appenders is configured with two outputs, one for the console output and one for the file output.

Appenders.type=file object that specifies the file output location and file size, and automatically generates a new file when the Maxlogsize size is exceeded. Logs the file directory to be created manually.
Level:log4js.levels.INFO, setting the default log output level is INFO.

Log4js Output Level 6 : Trace, Debug, info, warn, error, fatal

    • Logger.trace (' Entering cheese testing ');
    • Logger.debug (' Got cheese. ');
    • Logger.info (' Cheese is Gouda. ');
    • Logger.warn (' Cheese is quite smelly. ');
    • Logger.error (' Cheese is too ripe! ');
    • Logger.fatal (' Cheese was breeding ground for listeria. ');

If the output level is info, the log trace,debug below the info level is not printed and only info,warn,error,fatal is printed. The advantage of this is that in a production environment we may only be concerned with exceptions and errors, and do not care about debugging information. This greatly reduces the output of the log and can reduce disk writes. In the development environment, we can print very much information to help developers locate errors and debug code.

Another benefit is that the code can be mixed with a variety of log printing code. As long as we modify the output level in a single configuration file, the log output changes, without modifying all of the code. If all the places are Console.log (), then on-line, it takes a lot of time to change this thing.

4. According to the project configuration Log4js

In the previous section, LOG4JS and express integration were described. However, the default configuration may not be appropriate for our project, and some adjustments to the parameters of the log4js are required.

1. Replace Console.log ()
Increase the Replaceconsole configuration so that all console outputs are in the log and the [INFO] console replaces the console default style.

~ vi app.jsvar log4js = require (' Log4js '); Log4js.configure ({  appenders: [    ' Console ' },{      ' file ',       ' Logs/access.log ',       1024x768,      backups: 4,      ' normal '     }  ],  true});

To view the results of the output:

[2013-06-19 18:18:41.997] [INFO] Console-this is an index page!GET/30415ms[2013-06-19 18:18:42.010] [INFO] normal-127.0.0.1--"get/http/1.1" 304-"http://localhost:3000/admin/" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/CSS/BOOTSTRAP.MIN.CSS 3045ms[2013-06-19 18:18:42.042] [INFO] normal-127.0.0.1--"Get/css/bootstrap.min.css http/1.1" 304-"Http://localhost:3000/admin/crawler/youku" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/CSS/MY.CSS 30411ms[2013-06-19 18:18:42.051] [INFO] normal-127.0.0.1--"Get/css/my.css http/1.1" 304-"Http://localhost:3000/admin/crawler/youku" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/js/jquery-1.9.1.min.js 30435ms[2013-06-19 18:18:42.089] [INFO] normal-127.0.0.1--"Get/js/jquery-1.9.1.min.js http/1.1" 304-"http://localhost:3000/admin/" "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36"GET/js/holder.js 30442ms[2013-06-19 18:18:42.098] [INFO] normal-127.0.0.1--"Get/js/holder.js http/1.1" 304-"http://localhost:3000/admin/"" mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36 "GET/js/bootstrap.min.js 30411ms[2013-06-19 18:18:42.101] [INFO] normal-127.0.0.1--"Get/js/bootstrap.min.js http/1.1" 304-"http://localhost:3000/admin/"" mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/27.0.1453.110 safari/537.36 "

2. Adjust the format of the log output

App.use (Log4js.connectlogger (logger, {level:level:log4js.levels.INFO, Format: ': Method:url '}));

Output Result:

[2013-06-19 18:23:25.230] [INFO] Console-this is an index page!GET/30428ms[2013-06-19 18:23:25.251] [INFO] Normal-get/GET/CSS/BOOTSTRAP.MIN.CSS 3045ms[2013-06-19 18:23:25.287] [INFO] normal-get/css/Bootstrap.min.cssGET/CSS/MY.CSS 3043ms[2013-06-19 18:23:25.292] [INFO] normal-get/css/My.cssget/js/jquery-1.9.1.min.js 30415ms[2013-06-19 18:23:25.310] [INFO] normal-get/js/jquery-1.9.1. Min.jsget/js/holder.js 3049ms[2013-06-19 18:23:25.321] [INFO] normal-get/js/Holder.jsget/js/bootstrap.min.js 30417ms[2013-06-19 18:23:25.338] [INFO] Normal-get/js/bootstrap.min.js

3. Automatically adjust the log output level

Log level corresponding rules:
HTTP responses 3xx, level = WARN
HTTP Responses 4xx & 5xx, level = ERROR
else, level = INFO

Set level to Auto

 app.use(log4js.connectLogger(logger, {level: ‘auto‘, format:‘:method :url‘}));

The following log in order to compare the convenience I played a few more lines.

[2013-06-19 18:24:56.040] [INFO] Console-this is an index page!GET/30416ms[2013-06-19 18:24:56.053] [WARN] Normal-get/GET/CSS/BOOTSTRAP.MIN.CSS 3049ms[2013-06-19 18:24:56.086] [WARN] normal-get/css/Bootstrap.min.cssGET/CSS/MY.CSS 3049ms[2013-06-19 18:24:56.097] [WARN] normal-get/css/My.cssget/js/jquery-1.9.1.min.js 30426ms[2013-06-19 18:24:56.128] [WARN] normal-get/js/jquery-1.9.1. Min.jsget/js/holder.js 30432ms[2013-06-19 18:24:56.164] [WARN] normal-get/js/Holder.jsget/js/bootstrap.min.js 3041ms[2013-06-19 18:24:56.166] [WARN] normal-get/js/bootstrap.min.js[2013-06-19 18:24:56.204] [info] normal-get/cat/json/latestget/cat/json/latest 10ms[2013-06-19 18:24:56.211] [info ] Normal-get/cat/json/masterget/cat/json/master 4ms[2013-06-19 18:24:56.219] [INFO] Normal-get/cat/json/classic Get/cat/json/classic 9msget/img/movie/emptysmall.png 304 1ms[2013-06-19 18:24:56.263] [WARN] Normal-get/img/movie /emptysmall.png

5. Optimize LOG4JS structure

There should be a classmate found that we have a problem when configuring LOG4JS. Is that all configuration information is done in app.js, and logger is defined directly here. If the controller (routes) wants to output with log4js, we can't get the logger handle now.

Modify App.js,

~VI app.jsvarLOG4JS = require (' Log4js ')); Log4js.configure ({appenders: [{type:' Console '},{Type:' File ', FileName:' Logs/access.log ', Maxlogsize:1024, Backups:4, Category:' Normal '}], Replaceconsole:true});//var logger = Log4js.getlogger (name);//logger.setlevel (' INFO ');..... app.use (Log4js.connectlogger ( This. Logger (' normal '), {level: ' auto ', format: ': Method:url '})); .... exports.logger=function(name) {varLogger =Log4js.getlogger (name); Logger.setlevel (' INFO '); returnlogger;}

We define the logger separately and expose it as an API.

Using the logger output in Index.js

~ VI routes/index.jsvar logger = require ('.. /app '). Logger (' index 'function(req, res) {    Console.log ("This was an index page!" );    Logger.info ("This was an index page! --Log4js ");    Res.render (' index ', {          title:' home page |moive.me ',          page:' index '      }) ;

Print out results

[2013-06-19 18:56:51.924] [INFO] Console-this is an index page![2013-06-19 18:56:51.925] [INFO] index-this is an index page! --Log4jsget/30417ms[2013-06-19 18:56:51.938] [WARN] [default]-GET/GET/CSS/BOOTSTRAP.MIN.CSS 3045ms[2013-06-19 18:56:51.978] [WARN] [default]-get/css/Bootstrap.min.cssGET/CSS/MY.CSS 3042ms[2013-06-19 18:56:51.981] [WARN] [default]-get/css/My.cssget/js/jquery-1.9.1.min.js 3042ms[2013-06-19 18:56:51.984] [WARN] [default]-get/js/jquery-1.9.1. Min.jsget/js/holder.js 3043ms[2013-06-19 18:56:51.989] [WARN] [default]-get/js/Holder.jsget/js/bootstrap.min.js 3049ms[2013-06-19 18:56:52.002] [WARN] [default]-Get/js/bootstrap.min.js

So we have been playing log4js, for the deployment to the production environment, do a good job of log preparation.

Play Nodejs Log Management Log4js (GO)

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.