Nodejs Write log _log4js use detailed

Source: Internet
Author: User
Tags file copy system log

Share with you today a common third-party package that writes logs in Nodejs: Log4js.

Following the main features of the blog, the basic information of the next log4js is introduced briefly. Before introducing LOG4JS, you need to say that log4***,log4*** is a multi-platform multi-lingual log writing extension package provided by Apache, the purpose is simple is to make log writing more convenient and concise, At the same time, the different business logs can be flexible sub-file records, but also contains a detailed hierarchical configuration, for the subsequent hierarchical output, retrieval, and automatic resolution of the program to provide more convenient support (opinion, unofficial description, the spirit of understanding). log4*** has a lot of language implementation, such as log4cpp,log4j,log4net and so on, look at the name to know what the corresponding support. And the log4js we're going to talk about today is log4*** implementation package for Nodejs language, In addition to the basic functionality, a subset of the features added specifically for Nodejs are expanded. This is not discussed in detail because there is no in-depth study.

OK, go to the point, below our main focus on LOG4JS in the actual combat in detail use.

First, Log4js quick to get started to build log storage directory:

Win+r enter CMD to open a command prompt, then switch to D-disk, mkdir logs create a new logs folder in the D drive. Then, under Logs folder, execute the following command in turn:

To create a project:

Create a new project using Webstrom, and add the following two files Logconf.json and testlog.js in the project root directory, where Logconf.json is the LOG4JS configuration file and Testlog.js is the startup file for the test program.

Run NPM install LOG4JS under the project directory

Logconf.json file:

{  "Appenders":  [    {      ' Type ': ' Console ',      "Category": "Console"    },    {      "category": "Log_file",      ' type ': ' File ',      "FileName": "/logs/log_file/file.log",      "Maxlogsize": 104800,      "Backups": 100    },    {      "category": "Log_date",      "Type": "Datefile",      "FileName": "/logs/log_date/date",      "Alwaysincludepattern":true,      "Pattern": "-yyyy-mm-dd.log"    }  ],  "Replaceconsole":true,  "Levels":  {    "Log_file": "All",    "Console": "All",    "Log_date": "All"  }}

Testlog.js file:

varLOG4JS = require ("Log4js");varLog4js_config = require ("./logconf.json"); log4js.configure (log4js_config); Console.log ("Log_start start!");varLogFile = Log4js.getlogger (' log_file ')); Logfile.trace (' This is a log4js-test '); Logfile.debug (' We Write Logs with Log4js '); Logfile.info (' Can find logs-files in the Log-dir '); Logfile.warn (' Log-dir is a configuration-item in the Log4js.json '); Logfile.error (' In this Test log-dir is: \ './logs/log_test/\ ');/*var datefile = Log4js.getlogger (' log_date ');d atefile.info ("This is the console data1");d Atefile.info ("This is the console Data2 ");d Atefile.info (" This is the console data3 ");*/

Output Result:

A file File.log was generated under the d:/logs/log_file/directory. The contents are as follows:

[2015-01-24 16:38:32.332] [TRACE] Log_file-this is a log4js-test[ with log4js[ in the log-dir[in the log4js.json[2015-01-24 16:38:32.333] [ERROR] log_file-in this Test log-dir is: './logs/log_test/'
Summary: The use of LOG4JS is very simple:

1. installation package (NPM install LOG4JS)

2. Create a log directory (./logs/log_fie/)

3. Add a log Output rule configuration file (Log4js.json) (This also has the default, but often the default configuration is not satisfied with the use of the demand)

4. Load the LOG4JS in the code and get the configuration file to the call configuration method (Log4js.configure (Cfg.json))

5. Write Log log4js.getlogger (' Log_test '). Debug ("Write a log!!!")

Two. Detailed configuration of the LOG4JS

for the quick on the hands of the project, we will analyze in detail the role of the various properties of LOG4JS and the use of distribution, here only for the discussion of usage, the realization of the principle and performance of in-depth research interested can directly look at the source code.

1.appenders Properties

Appenders is the first-level property of a profile: its role is to configure the output source. The object that we actually output the log is the output source of the subordinate of Log4js. For example, say this pattern: an organization to clean up, then the organization itself is an institution can not clean the health, Only by the employees in the organization to do cleaning. The whole log4js can be understood as an organization responsible for the output of the log, then the real log output is to rely on the employees are appenders arrays, each object in the appenders is a log output staff, based on such a structure, It's not hard for us to come up with the idea that each employee has its own characteristics, and that the log rules they output are different. I continue to discuss appenders properties.

1.1 Category Configuration

category translation comes in the form of a category. It is actually easier to understand the name of the employee who wrote the journal.
When we have multiple employees we rely on this field to differentiate, in the previous example, before writing the log there is a line code:
Log4js.getlogger (' Log_file '). Debug (...);
The parameter of this GetLogger () is the configuration content of category, can be any string (spit slot: I do not have experimental Chinese or special symbols are supported, because no Zuo no die, for the design of Zuo I have always avoided rather than to verify whether it can zuo!)

1.2 Type configuration

The Type field is what types of control log output objects are, and the more commonly used configurations are three:

A. " Type ":" Console ":

The type is configured as console to represent the console, which in this configuration is often used when debugging. See the description in 2.replaceConsole for details.

B. " Type ":" File ":

The type is configured as file to indicate that the log output is normal, and in this configuration, the log is output to the destination file of the target folder and automatically files as the file size changes.
The specific generation file method in this mode:
Relevant valid configurations include: Maxlogsize,backups,filename
Related invalid configuration includes: Pattern,alwaysincludepattern
Help:

C. " Type ":" Datefile "

The type is configured as datefile to output a log of time-divided files, in which case the log is output to the target directory and named in the time format, and, over time, a file that is named in time format is automatically created if it does not already exist.
The specific generation file method in this mode:
Relevant valid configurations include: Pattern,alwaysincludepattern,filename
Related invalid configuration includes: maxlogsize,backups
Help:
In datefile mode, I temporarily did not find the same time when the file is too large to automatically divide the file method. In the type file mode, I temporarily did not find a naming method that could append a timestamp.
This demand is very practical, I personally think LOG4JS should achieve such a demand, but at present I did not find. If the friend in-depth understanding log4js can tell me how to configure the method, or explicitly tell me not to support this configuration, thank you very much!

1.3 FileName Configuration

A.filename is a directory plus the file name, and the path is the path where the log file is stored.
B. This path can either be a relative path or an absolute path, when it is relative to a path, is relative to the engineering root directory.
C. Whether it is a relative path or an absolute path, all folders in the path process must be manually created in advance and LOG4JS will not be created automatically, such as an error if the path does not exist.
D. The final filename is the name of the output file template, the real name will be modified,
D1:type:datefile time tags, such as [Log-2015-01-24, log-2015-01-25]
D2:type:file when a file is too large, a numbered label is added to the file. [Log.1 log.2 log.3 ...]

1.4 Maxlogsize Configuration

This only works in Type:file mode. Indicates how large the file is before the next file is created, in bytes. The actual setting is based on the business, but is not recommended to be greater than 100Mb.

1.5 Pattern Configuration

This is only valid in Type:datefile mode. Represents a time-named pattern for a file. In the makefile, a time string is appended to the file end of filename to name the file in the build file. Last Example:

Configuration file Contents:

{    "category": "Log_date",    "type": "Datefile",    "filename": "./logs/log_date /date ",    true,    " pattern ":"-yyyy-mm-dd-hh:mm:ss.log "}

The file name that is generated at this time is Date-2015-01-24-14:24:12.log
Pattern precision to SS (seconds) is one second a file, accurate to MM (minutes) is a single file, one analogy: hh (hours), DD (days), MM (months), yyyy (year), YY (year two), pay attention to the case!
The pattern is configured by default and the default configuration is ". Yyyy-mm-dd"

1.6 Alwaysincludepattern:

This only works in Type:datefile mode.
This is a switch configuration ture (the default) is open Pattern,false is not open pattern, when not on Datefile file will have no time suffix, will not sub-file.

1.7 Backups Configuration

This only works in Type:file mode, which indicates the number of files to be backed up, and the oldest ones if too many files are deleted.
Naming rules for LOG4JS in Type:file mode: The file being written is called the file name configured in filename, the file is too large to append a number such as Log.1 log.2 log.3, until the number of files reached backups will be the oldest deleted.
When a new file is created, LOG4JS will postpone all previous file's. Numeric numbers, and finally append the large file that just appeared. 1; This mode should pay attention to the impact of large file copy on the naming, so maxlogsize do not set too large.

2.replaceConsole Configuration

This configuration indicates whether to replace the console output. When Type:console is configured in Appenders in the configuration file, and replaceconsole:true, the console output in the code (console.log CONSOLE.ERROR) will be exported to the console in LOG4JS format.
Again a very useful tip: Log4js Debug output:
When we put the actual production environment Log4js.json configuration, in the debugging phase, the log will be output to each file, try to debug it is not convenient, then we can the individual log output employee type configured as console, so that the log information will be all summarized to the console output.
If you add another log employee configuration as follows, the NODEJS system-supplied Console.log in the code is also output to the console.

{    "type": "Console",    "category": "Console" }

The category name must be called the console, otherwise invalid,
Replaceconsole:ture If this line is not added, the contents of the Console.log () output provided by the NODEJS system will not be displayed
I'll re-paste the configuration of this part of the content:
The configuration is as follows:

{    "Appenders":        [            {                ' Type ': ' Console ',                "Category": "Console"            },            {                "category": "Log_file",                ' Type ': ' Console ',                "FileName": "./logs/log_file/file.log",                "Maxlogsize": 104800,                "Backups": 100            },            {                "category": "Log_date",                ' Type ': ' Console ',                "FileName": "./logs/log_date/date",                "Alwaysincludepattern":true,                "Pattern": "-yyyy-mm-dd-hh.log"            }        ],    "Replaceconsole":true,    "Levels":    {        "Log_file": "All",        "Console": "All",        "Log_date": "All"    }}

Log output:

/usr/local/bin/node log_start.js[2015-01-24 15:20:53.395] [INFO] Console-log_start start![2015-01-24 15:20:53.401] [TRACE] Log_file-this is a log4js-test[2015-01-24 15:20:53.402] [DEBUG] log_file-we Write Logs withlog4js[2015-01-24 15:20:53.402] [INFO] log_file-you can find Logs-filesinchThe log-dir[2015-01-24 15:20:53.402] [WARN] Log_file-log-dir is a configuration-iteminchThe log4js.json[2015-01-24 15:20:53.402] [ERROR] log_file-in this Test log-dir is: './logs/log_test/'[2015-01-24 15:20:53.402] [INFO] Console-log_start end!Process finished withExit Code 0

Webstrom see this part of the log is color! very convenient!!!

3.levels Configuration

The levels configuration is also a first-level attribute that controls the output level of the log. In the published program, if it is stable, some unimportant logs need to be hidden, but when the debugging phase or the environment is abnormal, we need to reproduce all the processes, we need a comprehensive log.
The levels structure is configured with several attributes, typically corresponding to employees in the Appenders, where the property name is the employee name in Appenders (that is, the category value), and the property value is a string representing the rank.
Log4js's levels configuration is divided into 8 levels (that is, the log level), from low to High, respectively: all TRACE DEBUG INFO WARN ERROR FATAL OFF.
Only information that is greater than or equal to the log configuration level can be output.
For example, we have modified the Log_file log loss level to error.
Then the final output of the log is as follows:

/usr/local/bin/node log_start.js[2015-01-24 15:24:27.537] [INFO] Console-log_start start! [2015-01-24 15:24:27.540] [ERROR] log_file-in this Test log-dir is: './logs/log_test/'[2015-01-24 15:24:27.540] [INFO] Console-log_sta RT End!   with exit code 0

Only the error output comes out. (The two lines on the error are not output by the Log_file employee, it is output by the console employee, and its output level is all, lowest level, all output)

Three. log4js FAQ and Tips configuration file format settings

The configuration file is actually a JS object, Json,js, or you can assign it through various set methods.

At first, it is necessary to associate the configuration file with the configuration file Log4js.json with the Log4js module, that is, to call the Configure () function to load the configuration, in fact, it is necessary to have a JavaScript object, in this case, We can completely write the configuration file in JS format, similar to this:
Module.exports = {... This is the content of the above-posted JSON};
The advantage of this model is that if there is dynamic information in the configuration, you can add functions in the configuration, such as using the name of the PID name, in the configuration can be dynamically obtained PID and string concatenation to the filename. Another advantage is that JSON does not support annotations, and you can add comments after you write JS.
This is suitable for more complex application environments.

Tips: New log usage

We added a new feature, the new function of the probability of a problem, we hope that the new features of the log more comprehensive, but do not want to reduce the levels log output level, which will lead to the full program log volume explosion, this time we can use a small trick, log4js provide several levels of log system, We will be one of the higher system negotiation is not used in the normal logic, but left to the new features of the log to use, because its level is high enough, so there will be a full output, and so on after the business stability in the log back to the appropriate version of it! I'm now accustomed to using the error level log as the new log GetLogger ("Test"). Error ("..."),

Four. Additional: detailed configuration examples of LOG4JS in real projects:



Application Scenarios:

This is a task system with a large number of users connecting and getting information. A business is a message driven by a client, a messaging group of tasks, and no correlation between tasks.

Configuration file:

My real project I set up 6 log output employees, one of which is the console type (console), one is the file type (log_info), the remaining 4 are the Datefile type (Log_stat,log_trace,log_error, Log_todo).

The console type is used to capture accidentally written system log content (Console.log),
Log_info: Detailed log, the main log is here, using the file type, 100MB, according to my winning volume I saved 100 copies.
Log_stat: Used to output some statistics, the number of statistics fixed, not dependent on the user volume changes, and less, so set to Datefile, the day output looks clear.
Log_trace: There are a large number of users and message-driven processing business, so add the trace business, each message record one, including the user name, easy to quickly locate a user's all operations, taking into account my current business volume This is a day or can receive, so use datefile format
Log_error: Exception information, the number is not particularly large, using the Datefile format
Log_todo: Record some need to manually handle business, log volume is not much, use datefile format

Details are as follows:
{    "Appenders":        [            {                "Category": "Console",                ' Type ': ' Console '            },            {                "category": "Log_info",                ' type ': ' File ',                "FileName": "./logs/log_info/info.log",                "Maxlogsize": 104857500,                "Backups": 100            },            {                "category": "Log_stat",                "Type": "Datefile",                "FileName": "./logs/log_stat/stat"            },            {                "category": "Log_trace",                "Type": "Datefile",                "FileName": "./logs/log_trace/trace"            },            {                "category": "Log_error",                "Type": "Datefile",                "FileName": "./logs/log_error/error"            },            {                "category": "Log_todo",                "Type": "Datefile",                "FileName": "./logs/log_todo/todo"            }        ],    "Replaceconsole":true,    "Levels":    {        "Log_info": "All",        "Log_stat": "All",        "Log_trace": "All",        "Log_error": "All",        "Log_todo": "All"    }}
A brief overview of other details in the actual use

Configuration file I configured three sets, respectively is

To develop the debugging environment, all type is the console
Intranet test environment, as above
On-line environment configuration, path and log levels are changed.


Reference:

Https://github.com/nomiddlename/log4js-node
Http://www.doc100.net/bugs/t/1046930/index.html

Nodejs Write log _log4js use detailed

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.