The log management module in Log4js-node.js is used with encapsulation

Source: Internet
Author: User

In the process of development, logging is an essential thing, especially in production systems often unable to debug, so the log becomes an important source of debugging information.

node. js, already has open source log module, is LOG4JS, source address: Click to open the link

Project Reference method: NPM Install Log4js

1, configuration instructions (only for the common Datefile log type example, more instructions refer to Log4js-wiki):

{   "Appenders": [   //the following line should be used to output the Web request URL log with Express{"Type": "Console", "category": "Console"},   //Define a logger  {          "Type": "Datefile",//log file type, you can use the date as a placeholder for the file name"FileName": "e:/weblogs/logs/",//log file name, you can set the relative path or absolute path"Pattern": "Debug/yyyymmddhh.txt",//placeholder, immediately following the filename"Absolute":true,//filename is an absolute path"Alwaysincludepattern":true,//whether the file name always contains placeholders"category": "Loginfo"//Logger name  } ],  "Levels": {"Loginfo": "DEBUG"}//sets the default display level of the logger, which is below this level of logging and does not output}

The placeholder description that pattern can use is not part of the following placeholder format, and is output as a file name (note: a single m, D, H, m) are not supported:
YY two-bit year
YYYY four-bit year
MM Two-bit month
DD Two-bit date
HH two-bit hours, by 24-hour system
MM Two-bit fractional number
SS two-bit seconds
SSS three-bit milliseconds
o time zone, capital letter O, placeholder output result is +0800

Assuming that the current June 2014 is 20 months and 15 points, then the above configuration will eventually be recorded in the E:\weblogs\logs\debug\2014062015.txt file.

2, the output of the log code, first please save the above configuration code as a Log4js.json file, for code to load the configuration from the file (configuration independent also easy to modify and publish):
Note: The JSON file does not support any form of comment//or/**/, so the comments in the configuration code above are removed, otherwise the error will be compiled

var log4js = require (' Log4js '); // Note: The log directory in the configuration must be created before the configuration can be loaded, otherwise the exception will be log4js.configure ("./log4js.json"); var loginfo = Log4js.getlogger (' loginfo '); Loginfo.info ("test log Information");

The above configuration and code, relatively simple, I refer to the previous C # version of the logging class, re-encapsulates the LOG4JS, defines a loghelper.js

1, Log4js.json configuration file contents (defined 4 loggers, respectively written to a different log directory, and custom 2 properties, some common properties extracted into the custom properties):

{    "Custombasedir": "e:/weblogs/logs/",    "Customdefaultatt" :{        "Type": "Datefile",        "Absolute":true,        "Alwaysincludepattern":true    },    "Appenders": [            {"Type": "Console", "category": "Console"},            {"Pattern": "Debug/yyyymmddhh.txt", "category": "Logdebug"},            {"Pattern": "Info/yyyymmddhh.txt", "category": "Loginfo"},            {"Pattern": "Warn/yyyymmddhh.txt", "category": "Logwarn"},            {"Pattern": "Err/yyyymmddhh.txt", "category": "LogErr"}        ],        "Replaceconsole":true,        "Levels": {"Logdebug": "Debug", "Loginfo": "Debug", "Logwarn": "Debug", "LogErr": "Debug"}}

2, loghelper.js package of file content:

varHelper ={};exports.helper=Helper;varLOG4JS = require (' Log4js '));varFS = require ("FS");varPath = require ("path");//Load configuration filevarObjconfig = Json.parse (Fs.readfilesync ("Log4js.json", "UTF8"));//checks if the directory required by the configuration file exists and does not exist when creatingif(objconfig.appenders) {varBaseDir = objconfig["Custombasedir"]; varDefaultatt = objconfig["Customdefaultatt"];  for(vari= 0, J=objconfig.appenders.length; i<j; i++){        varitem =Objconfig.appenders[i]; if(item["type"] = = "Console")            Continue; if(Defaultatt! =NULL){             for(varAttinchDefaultatt) {                if(Item[att] = =NULL) Item[att]=Defaultatt[att]; }        }        if(BaseDir! =NULL){            if(item["filename"] = =NULL) item["FileName"] =BaseDir; Elseitem["filename"] = baseDir + item["filename"]; }        varfilename = item["filename"]; if(FileName = =NULL)            Continue; varPattern = item["pattern"]; if(Pattern! =NULL) {FileName+=pattern; }        varCategory = item["category"]; if(!isabsolutedir (FileName))//Path.isabsolute (fileName))            Throw NewError (The path of the "configuration section" + Category + "is not an absolute path:" +fileName); varDIR =Path.dirname (fileName);    Checkandcreatedir (dir); }}//The directory is created before the configuration is loaded, otherwise it will be abnormallog4js.configure (objconfig);varLogdebug = Log4js.getlogger (' Logdebug '));varLoginfo = Log4js.getlogger (' Loginfo '));varLogwarn = Log4js.getlogger (' Logwarn '));varLogErr = Log4js.getlogger (' LogErr ')); Helper.writedebug=function(msg) {if(msg = =NULL) msg= ""; Logdebug.debug (msg);}; Helper.writeinfo=function(msg) {if(msg = =NULL) msg= ""; Loginfo.info (msg);}; Helper.writewarn=function(msg) {if(msg = =NULL) msg= ""; Logwarn.warn (msg);}; Helper.writeerr=function(MSG, exp) {if(msg = =NULL) msg= ""; if(exp! =NULL) msg+ = "\ r \ n" +exp; Logerr.error (msg);};//ways to work with ExpressExports.use =function(APP) {//page request log, level with auto, the default is warnApp.use (Log4js.connectlogger (Loginfo, {level: ' Debug ', Format: ': Method:url ')}));}//to determine if the log directory exists and does not exist when creating the log directoryfunctionCheckandcreatedir (dir) {if(!Fs.existssync (dir))    {Fs.mkdirsync (dir); }}//Specifies whether the string is an absolute pathfunctionIsabsolutedir (path) {if(Path = =NULL)        return false; varLen =path.length; variswindows = Process.platform = = = ' Win32 '; if(iswindows) {if(Len <= 1)            return false; returnPATH[1] = = ":"; }Else{        if(Len <= 0)            return false; returnPath[0] = = "/"; }}

3. Code Call:

var logger = require ("./loghelper"). Helper;logger.writeinfo ("haha 1 start logging"); Logger.writeerr ( "What the hell is wrong with You");

4, with express integration, you can output the client get or post URL (if it is not useful, or do not need to record the URL, this code is ignored):

// Add the following code in App.js to output the URL request in the log, and put it in front of the other app.use due to the loading order var app = Express (); var log = require ('./loghelper '); Log.use (app);

The log management module in Log4js-node.js is used with encapsulation

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.