Table of Contents
Quickly create a koa project
koa-logger
koa-log4js
Use
level
categories
appenders
总结配置
总结
Home Web Front-end JS Tutorial Teach you step by step how to write logs in Node.js service

Teach you step by step how to write logs in Node.js service

Dec 28, 2021 am 10:49 AM
node.js Serve

How to write logs in Node service? The following article will give you a practical understanding of how to write logs in the Node.js service. I hope it will be helpful to you!

Teach you step by step how to write logs in Node.js service

When using Node to write the server, the most troublesome thing is to troubleshoot positioning problems, because unlike the Chrome browser, We have direct error prompts in dev tool, or we can directly break point debugging.

We often encounter the problem of why the live environment is not working even though the test environment is OK. If there is no log, there is no clue about this problem.

So in this article, let’s talk about how to write logs in the Node service.

Quickly create a koa project

First make sure you have installed it globallykoa2:

npm i koa2 -g
Copy after login

Then execute:

The basic services of
koa2 -e node-log # 新建一个项目
cd node-log
npm i # 安装依赖
npm run start # 启动
Copy after login

are set up. Visit http://localhost:3000/, you can see the following page:

Teach you step by step how to write logs in Node.js service

The above is a quick setupkoaService method. This project has a built-in logging library - koa-logger. Let's first take a look at what it does.

koa-logger

This library is relatively simple and records the basic information of the request, such as the request method, URL, time, etc. When used as middleware, note: It is recommended to place it before all middleware. This is related to the onion model of koa. If it is not the first one, the calculated time will be inaccurate.

var logger = require('koa-logger');
app.use(logger());
Copy after login

When we access the response resources, the corresponding log will be output on the console as follows:

  <-- GET /
GET / - 14
  --> GET / 200 19ms 234b
  <-- GET /stylesheets/style.css
GET /stylesheets/style.css - 1
  --> GET /stylesheets/style.css 200 3ms 111b
  <-- GET /favicon.ico
GET /favicon.ico - 1
  --> GET /favicon.ico 404 1ms -
Copy after login

By default, the log is directly through console Output to the console, if we need to perform custom operations on the log, such as writing to a log file, etc. It can be done by something like, for example, I record the time:

app.use(logger((str) => {
  console.log(new Date() + str)
  // redirect koa logger to other output pipe
  // default is process.stdout(by console.log function)
}))
Copy after login

Result:

Mon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time)  <-- GET /
GET / - 10ms
Mon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time)  --> GET / 200 20ms 226b
Mon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time)  <-- GET /stylesheets/style.css
Mon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time)  --> GET /stylesheets/style.css 200 4ms 111b
Copy after login

koa-log4js

koa-logger It is relatively lightweight and exposes a relatively flexible interface. But for use in actual business, I personally recommend using koa-log4js. The main reasons are as follows:

  • koa-logger It seems that it only supports the use of middleware, but does not support the function of reporting specific logs.
  • There are relatively few built-in functions. For example, the classification and placement of logs, etc.

koa-log4js Wraps log4js to support Koa log middleware. Its configuration is consistent with log4js. So if you use log4js, the usage should be consistent.

Use

Installation:

npm i --save koa-log4
Copy after login

Let’s look at the usage first, create a new folder log in the root directory. And create a new folder utils, and create a new file logger.js in it. The code is as follows:

const path = require(&#39;path&#39;);
const log4js = require(&#39;koa-log4&#39;);
const RUNTIME_PATH = path.resolve(__dirname, &#39;../&#39;);
const LOG_PATH = path.join(RUNTIME_PATH, &#39;log&#39;);

log4js.configure({
  // 日志的输出
  appenders: {
    access: {
      type: &#39;dateFile&#39;,
      pattern: &#39;-yyyy-MM-dd.log&#39;, //生成文件的规则
      alwaysIncludePattern: true, // 文件名始终以日期区分
      encoding: &#39;utf-8&#39;,
      filename: path.join(LOG_PATH, &#39;access.log&#39;) //生成文件名
    },
    application: {
      type: &#39;dateFile&#39;,
      pattern: &#39;-yyyy-MM-dd.log&#39;,
      alwaysIncludePattern: true,
      encoding: &#39;utf-8&#39;,
      filename: path.join(LOG_PATH, &#39;application.log&#39;)
    },
    out: {
      type: &#39;console&#39;
    }
  },
  categories: {
    default: { appenders: [ &#39;out&#39; ], level: &#39;info&#39; },
    access: { appenders: [ &#39;access&#39; ], level: &#39;info&#39; },
    application: { appenders: [ &#39;application&#39; ], level: &#39;all&#39;}
  }
});

// getLogger 传参指定的是类型
exports.accessLogger = () => log4js.koaLogger(log4js.getLogger(&#39;access&#39;)); // 记录所有访问级别的日志
exports.logger = log4js.getLogger(&#39;application&#39;);
Copy after login

Briefly explain, configure is the configuration of log4js-node (will be explained in detail later), passed through the getLogger function Parameter is the log type, for example access is the access level log.

Then add: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const { accessLogger, logger } = require(&amp;#39;./utils/logger&amp;#39;); app.use(accessLogger())</pre><div class="contentsignin">Copy after login</div></div> to

app.js

and routes/index.js to add:

+ const { logger } = require(&#39;../utils/logger&#39;)

router.get(&#39;/&#39;, async (ctx, next) => {
+  logger.info(&#39;我是首页&#39;);
  await ctx.render(&#39;index&#39;, {
    title: &#39;Hello Koa 2!&#39;
  })
})
Copy after login

Refresh , you can see that two files are output in the log folder:

Teach you step by step how to write logs in Node.js service

recorded respectively:

[2021-10-12T10:43:33.914] [INFO] access - ::1 - - "GET / HTTP/1.1" 200 226 "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
[2021-10-12T10:43:34.065] [INFO] access - ::1 - - "GET /stylesheets/style.css HTTP/1.1" 200 111 "http://localhost:3000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
Copy after login
[2021-10-12T10:43:33.902] [INFO] application - 我是首页
Copy after login

Next we come Take a look at the configuration of log4js.

level

The main function of log classification is to better display logs (different colors) and selectively place logs, such as to avoid some# in production. Sensitive logs of ##debug were leaked. log4js There are nine levels by default (you can modify it through levels), as follows:

{
  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 after login

As shown in the figure below:

Teach you step by step how to write logs in Node.js service

只会输出级别相等或者级别高的日志。比如你配置了 WARN,就不会输出 INFO 的日志。 可以在下面配置的 categories 中配置不同的类型日志的日志级别。

categories

日志类别。必须配置默认日志类别,用于没有命中的情况下的兜底行为。该配置为一个对象,key 值为分类名称。比如上述 demo 中:

{
  default: { appenders: [ &#39;out&#39; ], level: &#39;info&#39; },
  access: { appenders: [ &#39;access&#39; ], level: &#39;info&#39; },
  application: { appenders: [ &#39;application&#39; ], level: &#39;all&#39;}
}
Copy after login

其中每个类别都有两个配置 appenders 是一个字符串数组,是输出配置(后文中会详解),可以指定多个,至少要有一个。level 是上文日志级别。

appenders

解决了日志分级和分类,接下来是日志落盘,也就是输出日志的问题。对应的配置是 appenders,该配置的 key 值为自定义的名称(可以给 categories 中的 appenders 使用),属性值为一个对象,配置输出类型。如下所示:

// 日志的输出
appenders: {
  access: {
    type: &#39;dateFile&#39;,
    pattern: &#39;-yyyy-MM-dd.log&#39;, //生成文件的规则
    alwaysIncludePattern: true, // 文件名始终以日期区分
    encoding: &#39;utf-8&#39;,
    filename: path.join(LOG_PATH, &#39;access.log&#39;) //生成文件名
  },
  out: {
    type: &#39;console&#39;
  }
}
Copy after login

其中,out 指的是通过 console 输出,这个可以作为我们的一个兜底。accesstypedataFile,指的是输出文件,然后配置文件的命名和输出路径。除了这个类型,详情可以看官网,比如 SMTP 通过邮件发送(这个需要 nodemailer

总结配置

日志分级、日志分类以及日志落盘,配置上的关系如下:

Teach you step by step how to write logs in Node.js service

总结

日志对于我们服务端排查定位问题非常重要,本文通过 koa-loggerkoa-log4js 讲解了如何上报日志。

koa-logger 比较轻量,记录请求的基本信息,也提供了一定的自定义能力。

koa-log4js 在日志分级、日志分类以及日志落盘上提供了一定的能力,个人认为基本这个更加适用于生产环境。

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of Teach you step by step how to write logs in Node.js service. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

How to fix 'Service is not responding' error in Windows. How to fix 'Service is not responding' error in Windows. Apr 27, 2023 am 08:16 AM

The NETSTART command is a built-in command in Windows that can be used to start and stop services and other programs. Sometimes, you may encounter NetHelpmsg2186 error while running this command. Most users who encounter this error try to restart the Windows Update service by running the NETSTARTWUAUSERV command. If the Windows Update service is disabled or not running, your system may be at risk as you will not be able to get the latest updates. Let’s explore in detail why this error occurs and how to bypass it. Okay? What is error 2186? Windows Update service installs the latest critical updates and security features

Solution to Windows 10 Security Center service being disabled Solution to Windows 10 Security Center service being disabled Jul 16, 2023 pm 01:17 PM

The Security Center service is a built-in computer protection function in the win10 system, which can protect computer security in real time. However, some users encounter a situation where the Security Center service is disabled when booting the computer. What should they do? It's very simple. You can open the service panel, find the SecurityCenter item, then right-click to open its properties window, set the startup type to automatic, and then click Start to start the service again. What to do if the Win10 Security Center service is disabled: 1. Press "Win+R" to open the "Operation" window. 2. Then enter the "services.msc" command and press Enter. 3. Then find the "SecurityCenter" item in the right window and double-click it to open its properties window.

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

How to open Remote Desktop Connection Service using command How to open Remote Desktop Connection Service using command Dec 31, 2023 am 10:38 AM

Remote desktop connection has brought convenience to many users' daily lives. Some people want to use commands to connect remotely, which is more convenient to operate. So how to connect? Remote Desktop Connection Service can help you solve this problem by using a command to open it. How to set up the remote desktop connection command: Method 1. Connect remotely by running the command 1. Press "Win+R" to open "Run" and enter mstsc2, then click "Show Options" 3. Enter the IP address and click "Connect". 4. It will show that it is connecting. Method 2: Connect remotely through the command prompt 1. Press "Win+R" to open "Run" and enter cmd2. In the "Command Prompt" enter mstsc/v:192.168.1.250/console

How to enable audio service in win7 How to enable audio service in win7 Jul 10, 2023 pm 05:13 PM

Computers have many system services to support the application of various programs. If the computer has no sound and most audio services are not turned on after troubleshooting hardware problems, how do you enable audio services in win7? Many friends are confused, so for the question of how to enable the audio service in win7, the editor below will introduce how to enable the audio service in win7. How to enable audio service in win7. 1. Find the computer on the computer desktop under Windows 7 system, right-click and select the management option. 2. Find and open the service item under Services and Applications in the computer management interface that opens. Find WindowsAudio on the service interface on the right and double-click to open the modification. 4. Switch to the regular project and click Start to enable the function.

What is the correct way to restart a service in Linux? What is the correct way to restart a service in Linux? Mar 15, 2024 am 09:09 AM

What is the correct way to restart a service in Linux? When using a Linux system, we often encounter situations where we need to restart a certain service, but sometimes we may encounter some problems when restarting the service, such as the service not actually stopping or starting. Therefore, it is very important to master the correct way to restart services. In Linux, you can usually use the systemctl command to manage system services. The systemctl command is part of the systemd system manager

See all articles