This is the second day of my participation in the August Text Challenge.More challenges in August

NodeJS backend development 08 using log4JS to log

What is a log?

Like a diary, a journal is printed by a program to record what happened and when within the program.

This article is mainly for use learning, want to have a deeper understanding of log management and analysis can see => log principle and development analysis this complete guide is enough! Adapt to all sizes

We’ve also used console.log to print debugging information. What’s the difference? Please read on with this question in mind.

First installation

Here we first install a log module.

Open the terminal and execute the following command:

npm install log4js
Copy the code

The basic use

const log4js = require('log4js')


var logger = log4js.getLogger('Thunder Committee Development Daily')
logger.level = 'info'


logger.info('Get up in the morning')
logger.info('Embrace the Sun')
logger.info('Finish breakfast')
logger.info('Full of hope')
logger.info('Start a day of code')
Copy the code

Save the above code as demo-fun.js and run: node demo-fun.js to get the same effect as the above log image.

The effect is as follows:

Project configuration uses logs

Log4js can configure logging rules based on code, but we recommend using JSON. This is a good habit, and although changing code and configuration requires rebooting the application, you can programmatically load logs without rebooting the code. This is not covered in this article, but will be covered later.

Code configuration log

Readers can save it as demo2.js and run it themselves.

//demo2.js
const log4js = require("log4js");
Log4js is configured to use fileAppender to output "error" level logs.
// The fileAppender is a log accumulator of file type that outputs logs to the file demo2.log
log4js.configure({
  appenders: { fileAppender: { type: "file".filename: "demo2.log"}},categories: { default: { appenders: ["fileAppender"].level: "error"}}});const logger = log4js.getLogger("demo");
// Now we call the logger object to print some logs.
logger.info("Normal log output here!!");
logger.error("Thunder committee, program found error, alarm message!");
logger.fatal("Ray committee, here is usually the server/engine overwhelmed, print the critical error log.");
Copy the code

Configure log4JS using JSON

Save the following as log4js.json

  • Two appenders are defined: fileAppender and stdout, which log to a file and standard output stream respectively.
  • Then set the appenders list loaded by default (the 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"}}}Copy the code

The simpleWeb.js code for ray

const log4js = require("log4js");
const logCfg = require("./log4js.json")
console.log('logCfg:',logCfg)
log4js.configure(logCfg)

const logger = log4js.getLogger('Thunder Committee 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)})
Copy the code

Use log4JS to print the log effect view



In the current project path, you can find the following log file leixuewei.log, we check and find that console.log information is not recorded.

Log4js logger and console.log

Console. log is usually used to output status/events and other information in the program. It can also be used to print dates and other data like a log, but it is lighter, cannot be written to a file, and can be printed in a single way.

Log4js provides logger for us to use, so we can use log4js.getLogger(different logger names) to print state/event information in the program. The key is to be able to write to a file so that we can trace the state of the program later.

Log data is useful, and the program must print accurate information

For example, after a month of application operation, there was a period of time when the application rendered pages very slowly. With the file log, we can easily do statistical analysis and find lazy bugs in the program that are discovered over time.

This is especially true for multi-team projects where one developer may not know the logic of the other developer code, and after multiple wraps, there may be some weird loops, or code that is only executed under certain conditions (for example, code that shows events based on holidays).

Many problems are difficult to detect when the program is not being run, so through logging, you can record and track down potential problems, provided, of course, the developer has to export logs to the program.

Another is not to blindly output too much log, visit the home page, you print 1 gb of log data, not only occupy the hard disk but also easy to cause the home page load. I exaggerate a little bit, but taste it.

Log4js configuration available in the production environment

A log4js.prod.json configuration suitable for living environment is attached. It defines daily log rollback and maintains log data for 30 days, which is basically consistent 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"}}}Copy the code

Pattern ‘. YyyyMMddhhmm ‘is the log scrolling effect.

conclusion

Here’s a tip from the blogger

  • Be sure to log, unless the app is only maintained by you otherwise a failure is cheating.
  • Maybe if we write 100 lines of code we can print two or three lines, if it’s something really complicated we can print more.
  • Print with different levels of logs at the same time.

This is not a hard and fast standard; the key is to learn to use logging efficiently through repeated use.

Continuous learning and continuous development, I am The Lei Committee of students

Refer to the link

This article shows the project code log principle and development analysis of this complete guide is enough! Adapt to all sizes! Log4js More examples log4JS documentation