Log management of Nodejs

Source: Internet
Author: User

When you develop a project, you can get operational information for the project through console output or Debug. When the project comes online, we need to analyze it through the logs. As in Java Log4j,nodejs, there are related log4js. The students who have used log4j should not be unfamiliar with it.

1. Log level

Log4js a total of 6 log levels, namely: Trace, Debug, info, warn, error, fatal. Weight from small to large, its initialization code is:

New Level (the "TRACE" new Level (10000, "DEBUG" new Level (20000, "INFO" new Level (30000, "WARN"New Level (40000, "ERROR" theNew level (50000, "FATAL"),    

If you set the default log level to info, then logs with a weight less than info will not be recorded, which means only the call to Log.info (), Log.warn (), Log.error (), or log.fatal () will trigger the logging. This part of the code is in Lib/logger.js.

function() {  var args = Array.prototype.slice.call (arguments)  , logLevel = Levels.tolevel ( Args.shift ())  , loggingevent;  if (thisnew loggingevent ("This.emit" ("Log", loggingevent);}};    
2. Integrated Express

Log4js can be used as a middleware for express. First, we need to introduce LOG4JS

var express = require ("Express");  var log4js = require ("Log4js");  var app = Express ();   

Then configure LOG4JS

Log4js.configure ({appenders: [   {type: ' Console ' },   {type: ' file ', FileName: ' Cheese.log ', Category: ' Chees E ' }  ]}); 

This configuration means that the console is the default Appender, and when using cheese this appender logs the log file with the log file name Cheese.log.

Then using use to connect to the middleware, we use the default is cheese this appender, level is info.

App.use (Log4js.connectlogger (Log4js.getlogger ("cheese"), {Level:log4js.levels.INFO});

Its output is similar to this:

[2014-07-04 20:27:21.205] [INFO] cheese-127.0.0.1--"get/http/1.1" 22896 "" "mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/31.0.1650.63 safari/537.36 "

......

3, then modify the middleware

The above approach is possible, but when there are too many middleware, it may feel ugly to write in the same file. So I tend to separate it out as a separate module, which is a separate file. Then expose the interface externally.

var path = require ("path");var log4js = require ("Log4js");/** * Log Configuration*/Exports.configure =function() {log4js.configure (Path.join (__dirname, "Log4js.json")); }/** * Exposed to the application's log interface, you must ensure that you have configure * @param name specifies the category in the Log4js configuration file before calling the method. Follow this to find the corresponding appender. * If Appender is not written in category, it is the default category. can have multiple * @returns {Logger}*/Exports.logger = function(name) { var datefilelog = Log4js.getlogger (name); Datefilelog.setlevel (Log4js.levels.INFO); return Datefilelog;} /* * for express middleware, you must ensure that you have configure * @returns {function|*} */ exports.uselog = Function before calling this method. () { return Log4js.connectlogger (Log4js.getlogger ("app"), {Level:log4js.levels.INFO});}  

Log4js.json file contents are as follows

{"    appenders": [        {            "type": "Console"        },        {            "type": "Datefile",            "filename ":" Logs/booklist.log ",            " pattern ":"-yyyy-mm-dd "True }]}     

Configuration is simple, configured with two Appender, one is the console, and the other is datefile, which means that a log file is generated every day. Note that I do not configure the category, so that when the corresponding Appender is not found, the two Appender is the default appender. Sometimes it seems that the configuration is not wrong, but the log file does not produce a log, often the problem is here.

And then in App.js we change to the following

var express = require ("Express");  This is our custom module var log4js = require ("./log");  var app = Express (); App.configure (); App.use (Log4js.uselog ());      
4. Single process and multi-process

OK, the above for single process is applicable, but if your NODEJS application is multi-process, using the above configuration you will see the output of the log is a bit strange, such as:

It feels a bit like a resource preemption.

The multiprocess configuration is given in the Log4js wiki. But there was also a problem when it was used, and there was no scrutiny. But someone in the community has built another way, and I'm using that. You can see this issue, please. Let's configure it here. Modify the Log module file that we modified above to change to:

var path = require ("path");var log4js = require ("Log4js");/** * Multi-process log configuration*/Exports.configure =function(mode) {if (mode = = = "Master"{Log4js.configure (Path.join (__dirname, "./log4js-master.json"))); }Else{//Multi-process configuration item log4js.configure (Path.join (__dirname, "./log4js-worker.json"));//Single-Process configuration items//Log4js.configure (Path.join (__dirname, "... /config/log4js.json "));}}/** * Exposed to the application's log interface, you must ensure that you have configure * @param name specifies the category in the Log4js configuration file before calling the method. Follow this to find the corresponding appender. * If Appender is not written in category, it is the default category. can have multiple * @returns {Logger}*/Exports.logger = function(name) { var datefilelog = Log4js.getlogger (name); Datefilelog.setlevel (Log4js.levels.INFO); return Datefilelog;} /* * for express middleware, you must ensure that you have configure * @returns {function|*} */ exports.uselog = Function before calling this method. () { return Log4js.connectlogger (Log4js.getlogger ("app"), {Level:log4js.levels.INFO});}   

The main change is the Configure method.

The contents of the Log4js-master.json are:

{"    appenders": [{        "type": "Clustered",        "Appenders": [            {                "type": "Console"             },            {                "type": "Datefile", "filename": "Logs/booklist.log", "pattern": "-yyyy-mm-dd"  True, "PollInterval": 1, "category": "Datefilelog" }]}]}       

The contents of the Log4js-worker.js are:

{    "appenders": [{        "type": "Clustered"    }]} 

Assuming that the contents of the main process are in the file master.js, the worker process is worker.js. The configuration content in Master.js is:

var log4js = require ("./lib/log"); Log4js.configure ("Master");

The worker.js is configured as follows:

var express = require ("Express");  This is our custom module var log4js = require ("./log");  var app = Express (); App.configure ("Worker"); App.use (Log4js.uselog ());       

So it was done.

We can do this when we need to record a log somewhere.

logger parameters in a random
...
Log.info ("..."); Log.error ("...")
5, written in the back

LOG4JS also has a lot of fun content, such as SMTP. This is a useful feature, such as when an item has an error and you want the program to send you an email informing you that the feature will come in handy.

In addition, I open source a project Booklist. The project is mainly to explore the Nodejs to establish the application needs or attention to the place, very look forward to your guidance and discussion, thank you!

Log management of Nodejs

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.