This is probably the first in a series of Node.js tutorials.

Log4js is one of the leading modules in Node.js logging. Debug has advantages over Console or TJ debug, especially for production Node.js projects:

  • Log classification
  • Classification of log
  • Log trading

This article will give you a comprehensive introduction to Log4JS, so that you can use log4JS in your projects with ease, development and debugging, and better monitoring and troubleshooting online.

The wheel test

The following three lines of code show you how to use log4js in its simplest form:

// file: simplest.js
var log4js = require('log4js');
var logger = log4js.getLogger();
logger.debug("Time:".new Date());Copy the code

Call.getLogger() to get an instance of Log4js Logger, which is used in the same way as console. You can call.debug (also.info,.error, etc.) to output logs.

Run node hunter.js and the output looks like this:

$nodeHttps://hunter.css [2016-08-21 00:01:24.852] [DEBUG] [default] - Time: 2016-08-20T16:01:24.852z Https://hunter.css [2016-08-21 00:01:24.852] [DEBUG] [default] - Time: 2016-08-20T16:01:24.85zCopy the code

Time: 2016-08-20T16:01:24.852z [2016-08-21 00:01:24.852] [DEBUG] [default] [2016-08-21 00:01:24.852] [DEBUG] [default]

Well, before we dive into the more advanced uses of Log4JS, let’s familiarize ourselves with a few concepts in log4JS.

Level

This is easy to understand, is the log classification. With the classification of logs, log4JS can better display logs for us (different levels of logs are in different colors in the console, for example error is usually red), and can selectively produce logs in order to prevent sensitive information belonging to.debug from being leaked.

Log4js logs are divided into nine levels. Each level has the following names and weights:

{
  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")}Copy the code

On a graph:

The ALL OFF levels are not used directly in business code. The remaining seven are the seven methods that correspond to Logger instances,.trace.debug.info… . In other words, when you call these methods, you level the logs. Therefore, the previous [2016-08-21 00:01:24.852] [DEBUG] [default] Time: 2016-08-20T16:01:24.852Z indicates the DEBUG level of this log.

type

Another concept of log4JS is the category (type). You can set the type of a Logger instance to separate logs by another dimension:

// file: set-catetory.js
var log4js = require('log4js');
var logger = log4js.getLogger('example');
logger.debug("Time:".new Date());Copy the code

When getting a Logger instance from 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 debug:

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

setInterval(function(){
  debug('doing some work');
}, 1000);Copy the code

In debug, ‘worker’ is also used to classify logs. Ok, go back to node set-catetory.js:

[2016-08-21 01:16:00.212] [DEBUG] Example - Time: 2016-08-20T17:16:00.212zCopy the code

[2016-08-21 00:01:24.852] [DEBUG] [default] Time: 2016-08-20T16:01:24.852z The only difference is that [default] becomes example.

For example, you can set a different category for each file, 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());Copy the code

[2016-08-21 01:24:07.332] [DEBUG] set-catetory. js-time: 2016-08-20T17:24:07.331z This log is generated in the set-catetory.js file. Or use different categories for different Node packages to distinguish which module the logs come from.

Appender

Ok, now that logs have levels and categories, the problem of classifying and classifying logs at the entry level is solved, whereas in Log4JS, the problem of exporting logs (i.e. where to output logs) is solved by the Appender.

The default appender

Here are the default log4JS appender Settings:

// log4js.js
defaultConfig = {
  appenders: [{
    type: "console"}}]Copy the code

As you can see, logs are output to the console by default when log4JS is not configured in any way.

Set up your own appender

We can set up the desired appender with 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());Copy the code

Log4js creates a default.log file in the current directory [2016-08-21 08:43:21.272] [DEBUG] custom-appender-time: [2016-08-21 08:43:21.272] 2016-08-21T00:43:21.272z Is output to this file.

Log4js appender

Console and File are log4JS appenders.

  • DateFile: Logs are output to a file that can be rolled to a specific date mode, such as todaydefault-2016-08-21.log, will be exported to tomorrowdefault-2016-08-22.log;
  • SMTP: outputs logs to emails.
  • Mailgun: Logs are output to Mailgun through the Mailgun API.
  • LevelFilter can be filtered by level.
  • And other appenders, you can see the full list here.

Filter level and category

We can adjust the appender configuration to filter log levels and categories:

// 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());Copy the code

Run to add a log to default.log:

[2016-08-21 10:08:21.630] [DEBUG] Category1 - Time: 2016-08-21T02:08:21.629zCopy the code

Take a look at the code:

  • uselogLevelFilterlevelTo filter log levels, ownership is greater than or equal toDEBUGThe log will be output. This is also the point of logging level weights mentioned earlier;
  • throughcategoryTo select the type of log to output,category2The following logs are filtered out, and the configuration also accepts an array, for example['category1', 'category2']So that logs of both categories are output to a file.

Layout

Layout is an advanced function provided by Log4JS. With Layout, you can customize the format of each output log. Log4js has four built-in formats:

  • MessagePassThrough: outputs only log content.
  • Basic: Add time, log level, and log type in front of the log content.
  • Colored/Coloured: Coloured logs based on basic. This layout is used by appender Console by default.
  • Pattern: This is a special type that can be used to define any 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.5 p %]] - % m % n'}}}])var logger = log4js.getLogger('layout-pattern');
logger.debug("Time:".new Date());Copy the code

%r %p $m $n is a built-in include specifier for log4js, which can be used to output meta information. For more details, refer to the log4js documentation.

Logger, Appender, and Layout locations.

Field: Output Node application ACCESS log access.log

To facilitate troubleshooting, application requests in and out are often logged in the production environment. How to use log4JS to do this?

// 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 external Review');
});
app.listen(5000);Copy the code

Look at what we did:

  • An appender is configured to select the category from the log asaccessTo a scrolling file;
  • log4js.getLogger('access')Gets a category ofaccessLogger instance passed tolog4js.connectLoggerThe middleware, which collects access information, is routed through this instance.

Start the server, go to http://localhost:5000, you will find an additional directory named access.log-2016-08-21.log, which contains two logs:

[2016-08-21 14:34:04.752] [INFO] Access - ::1 -"The GET/HTTP / 1.1" 200 18 "" "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 -"The GET/favicon. Ico HTTP / 1.1"24 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"Copy the code

With log4JS log classification and appender functionality, we output access logs to a rolling update file.

conclusion

This article gives you a comprehensive overview of log4JS, which is more complex to use than console or simple logging tools, and certainly more powerful for production-grade applications. If you are interested, please leave a comment and we will probably show you how to do configuration management in The Node application.