Node Log management Log4js "Go"

Source: Internet
Author: User

First, the 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 304 1msget/css/my.css 304 0msget/js/bootstrap.min.js 304 4msget/js/jquery-1.9.1.min.js 304 6  Msget/js/holder.js 304 3msget/cat/json/latest 6msget/cat/json/master 4msget/cat/json/classic 6MSGET/CSS/BOOTSTRAP.MIN.CSS 304 2msget/css/my.css 304 2msget/js/bootstrap.min.js 304 2msget/js/jquery-1.9.1.min. JS 304 1msget/js/holder.js 304 1msget/js/bootstrap.min.js 304 1msget/304 6msget/js/jquery-1.9.1.min.js 304 2msget/cs S/MY.CSS 304 1msget/css/bootstrap.min.css 304 1msget/js/bootstrap.min.js 304 2msget/js/holder.js 304 2msget/cat/json/l Atest 3msget/cat/json/master 2msget/cat/json/classic 2msget/admin/304 13msget/css/bootstrap.min.css 304 3 Msget/js/jquery-1.9.1.min.js 304 2msget/css/my.css 304 2msget/js/bootstrap.min.js 304 1msget/js/holder.js 304 2ms

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

Modify Routes/index.js

Exports.index = 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! get/304 19msget/css/bootstrap.min.css 304 4msget/css/my.css 304 2msget/js/jquery-1.9.1.min.js 304 38msget/js/holder. JS 304 29msget/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.

Second, the configuration Log4js and express framework Integration

1. Installation

npm install log4js

2, modify the project portal configuration file, such as log Analysis Project Express.js

var log4js = require (' Log4js '); Log4js.configure ({  appenders: [    {type: ' console '},//console output    {      type: ') File ',//files output      filename: ' Logs/log.log ',       maxlogsize:1024,      backups:3,      Category: ' Normal '     }  ]}); var logger = Log4js.getlogger (' normal '); Logger.setlevel (' INFO '); App.use (Log4js.connectlogger (logger, {level: Log4js.levels.INFO}); App.use (App.router);

The configuration of the LOG4JS is required in express.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.

Third, according to the project configuration Log4js
    1. Add Replaceconsole instead of Console.log () to add replaceconsole configuration, let all console output to the log, and [INFO] console instead of the console default style.

      var log4js = require (' Log4js '); Log4js.configure ({   appenders: [     {type: ' console '},{       type: ' file ',        filename: ' Logs/log.log ',        maxlogsize:1024,       backups:4,       Category: ' Normal '      }   ],   replaceconsole:true});
    2. Adjust the format of the log output

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

    3. Automatically adjust log output levels

      Log-level correspondence: HTTP responses 3xx, levels = WARN HTTP responses 4xx & 5xx, level = ERROR else, level = INFO  

      Set level to Auto:

        App.use (Log4js.connectlogger (logger, {level: ' auto ', format: ': Method:url '}));

Iv. Adjustment of LOG4JS structure

There is a problem when we configure LOG4JS. All of the above configuration information is done in express.js, logger is also directly defined here. If the controller (routes) wants to output with log4js, we can't get the logger handle now.

Newly established log.js

var log4js = require (' Log4js '); Log4js.configure ({    appenders: [        {            type: ' Console ',            Category: "Console "        },//console output        {            type:" File ",            filename: ' logs/log.log ',            pattern:" _yyyy-mm-dd ",            maxlogsize : 20480,            backups:3,            Category: ' Datefilelog '        }//date file format    ],    replaceconsole:true,   // Replace Console.log    levels:{        datefilelog: ' Debug ',        console: ' Debug '    }}); var datefilelog = Log4js.getlogger (' Datefilelog '); var consolelog = Log4js.getlogger (' console '); exports.logger = ConsoleLog; Exports.use = function (APP) {    app.use (Log4js.connectlogger (ConsoleLog, {level: ' INFO ', Format: ': Method:url '});}

We define the logger separately and expose it as an API, where development debugging is not using file output. This allows you to use the logger output log in other modules only as follows:

var logger = require ('.. /.. /log '). Logger;logger.debug ("collecttime=%s", collecttime);

We have already played log4js, if the deployment of production requires file output just modify the Log.js datefilelog level, and then set Exports.logger=datefilelog.

Original address: http://www.blogways.net/blog/2014/06/09/node-log4js.html, thank the original author to share.

Node 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.