NodeJS backend development 08 log using log4js
What is a log?
Like keeping a diary, the log is printed out by the program, recording when and where events occurred within the program.
This article is only for use learning. If you want to have a deeper understanding of log management and analysis, you can see = > This complete guide to log principle and development analysis is enough! Adapt to various scales
We also used console Log to print some debugging information. What's the difference? Please read on with this question.
Install first
Let's install a log module first.
Open the terminal and execute the following command:
npm install log4js
Basic use
const log4js = require('log4js') var logger = log4js.getLogger('Develop daily') logger.level = 'info' logger.info('Get up in the morning') logger.info('Embrace the sun') logger.info('After breakfast') logger.info('hopeful') logger.info('Started the day of the code')
Save the above code as demo fun JS, and then run:
node demo-fun.js
You can get the same effect as the log image above. You can try it after reading it.
The effect is as follows:
Project configuration usage log
log4js can configure logging rules based on code, but we recommend using json. This is a good habit. Although it is necessary to restart the application to modify the code and configuration, it can be realized through the program to make the code load the log without restarting. This point will not be shown in depth in this paper, but will be added later.
Code configuration log
Readers can save as demo2 JS, self running.
//demo2.js const log4js = require("log4js"); //Here, configure log4js and use fileAppender to output "error" level logs. //Then fileAppender is a log accumulator of file type, which outputs logs to file demo2 log log4js.configure({ appenders: { fileAppender: { type: "file", filename: "demo2.log" } }, categories: { default: { appenders: ["fileAppender"], level: "error" } } }); const logger = log4js.getLogger("demo"); //Next, call the logger object to print some logs. logger.info("Ordinary log output is here!!!"); logger.error(",The program found an error and sent an alarm message!"); logger.fatal(",This is usually the server/The engine can't stand it. Print the serious error log.");
Configure log4js using JSON
Save the following content as log4js json
-
Two Appenders are defined: file appender and stdout, which write logs to files and standard output streams respectively.
-
Then set the list of appenders loaded by default.
{
"appenders": {
"fileAppender": { "type": "file", "filename": "leiXueWei.log" },
"stdout": { "type": "stdout", "layout": {
"type": "pattern",
"pattern": "%d [%p] [%c] - %m%n"
}}
},
"categories": {
"default": {
"appenders": ["fileAppender","stdout"],
"level": "info"
}
}
}
Simpleweb JS code
const log4js = require("log4js"); const logCfg = require("./log4js.json") console.log('logCfg:',logCfg) log4js.configure(logCfg) const logger = log4js.getLogger('Logger') const pid = require('process').pid logger.info("process id:",pid) const server = require('http').createServer((req,res)=>{ console.log(new Date() + ' - visiting app:', req.url) logger.log('visiting app:', req.url) res.write("Levin - Log4js DEMO - ProcessId: "+pid) res.end() }) server.listen(8000,()=>{console.log('listening at 8000, pid:',pid)})
Print log renderings using log4js
In the current project path, you can find the following log file leixuewei Log, we found the console Log information is not recorded.
logger and console of log4js Log difference
console.log
It is usually used to output information such as program intermediate status / events. It can also match the date and other data like printing logs, but it is more portable and can not be written to files, and the printing method is relatively simple.
Log4js provides us with a logger so that we can log4js Getlogger (the name of different loggers) to distinguish the intermediate status / event and other information of the printing program.
The key is to be able to write to the file, which is convenient for us to trace the program state in the future.
log data is very useful, so the program must print accurate information
For example, after a month of operation, the program finds that the rendering page is particularly slow. With the file log, we can easily conduct statistical analysis and find some lazy bug s in the program, which can only be found over time.
In particular, for some multi person collaborative projects, a developer may not know the logic of other development codes. After multiple packaging, there may be some strange loops or codes executed only under specific conditions (such as the code for displaying activities according to holidays).
Many problems are difficult to be found when the program is not running, so the potential problems can be recorded and tracked through the log. Of course, the premise is that the developer has to output the log to the program.
Another is that you can't blindly output too many logs and visit the home page. If you print 1G log data, it will not only occupy the hard disk, but also easily lead to the failure of the home page to load. It's a little exaggerated, but one product at a time.
log4js configuration available for production environment
OK, it's just the Dragon Boat Festival. A log4js suitable for living environment is attached Prod.json configuration. It defines daily log rollback and maintains log data for 30 days, which is basically in line with production use.
{ "appenders": { "fileAppender": { "type": "dateFile", "daysToKeep": 30, "pattern": ".yyyyMMdd", "filename": "leixuewei.log", "layout": { "type": "pattern", "pattern": "%d [%p] [%c] - %m%n" } } }, "categories": { "default": { "appenders": ["fileAppender"], "level": "info" } } }
The following is the log scrolling effect with pattern ". yyyyMMddhhmm". Readers can download the code and try to modify it by themselves.
summary
Blogger, give me a little advice
-
Be sure to log. Unless this application is maintained only by you, failure is cheating.
-
Maybe we have written 100 lines of code and can print 2 to 3 lines. If it is a particularly complex business, we can manage more.
-
Use different levels of logs to print at the same time.
This is not a rigid standard. The key is to learn to use the log system efficiently through repeated use.
Continuous learning, continuous development, I am
Reference link
The project code shown in this article
This complete guide to log principle and development analysis is enough! Adapt to all sizes!
log4js more examples
log4js document