Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a log in Node.js service

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Xiaobian to share with you how to write logs in Node.js service, I believe most people still do not know how, so share this article for everyone's reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

When writing a server in Node, it is a headache to troubleshoot positioning problems, because unlike Chrome, we have direct error prompts in the dev tool, or we can directly interrupt the point debugging.

Often we will encounter the problem of why the live environment does not work when it is clearly OK for me in the test environment. If there is no journal, there is no clue to this problem.

Quickly create a new koa project

Make sure you install koa2 globally:

npm i koa2 -g

Then execute:

koa2 -e node-log #create a new project cd node-lognpm i #install dependency npm run start #start

The basic services are set up. Visit http://localhost:3000/and you will see the following page:

以上是一个快速搭建 koa 服务的方法。这个项目中内置了一个写日志的库--koa-logger。我们先来看看它做了什么东西吧。

koa-logger

这个库比较简单,记录请求的基本信息,比如请求的方法、URl、用时等。作为中间件中使用,注意:推荐放在所有的中间件之前,这个跟 koa 的洋葱模型有关。假如不是第一个,计算时间会不准确。

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

在我们访问响应的资源的时候,会在控制台输出相应的日志如下:

GET / 200 19ms 234b GET /stylesheets/style.css 200 3ms 111b GET /favicon.ico 404 1ms -

默认情况下,日志是通过 console 的方式直接输出到控制台中,假如我们需要对日志做自定义的操作,比如写入到日志文件中等。可以通过类似完成,比如我记录时间:

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

结果:

Mon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time) GET / 200 20ms 226bMon Oct 11 2021 19:28:41 GMT+0800 (China Standard Time) GET /stylesheets/style.css 200 4ms 111bkoa-log4js

koa-logger 比较轻量,也暴露了相对灵活的接口。但在实际业务中使用,我个人推荐使用 koa-log4js。主要理由如下:

koa-logger 看起来只支持中间件的使用方式,而不支持上报特定日志的功能。

内置的功能比较少。比如日志的分类和落盘等。

koa-log4js 对 log4js 做了一层包装,从而支持 Koa 日志的中间件。它的配置和 log4js 是保持一致的。所以假如你用 log4js 的话,使用上应该是一致的。

使用

安装:

npm i --save koa-log4

先来看使用,根目录新建一个文件夹 log。并且新建一个文件夹 utils,在其中新建文件 logger.js。代码如下:

const path = require('path');const log4js = require('koa-log4');const RUNTIME_PATH = path.resolve(__dirname, '../');const LOG_PATH = path.join(RUNTIME_PATH, 'log');log4js.configure({ // 日志的输出 appenders: { access: { type: 'dateFile', pattern: '-yyyy-MM-dd.log', //生成文件的规则 alwaysIncludePattern: true, // 文件名始终以日期区分 encoding: 'utf-8', filename: path.join(LOG_PATH, 'access.log') //生成文件名 }, application: { type: 'dateFile', pattern: '-yyyy-MM-dd.log', alwaysIncludePattern: true, encoding: 'utf-8', filename: path.join(LOG_PATH, 'application.log') }, out: { type: 'console' } }, categories: { default: { appenders: [ 'out' ], level: 'info' }, access: { appenders: [ 'access' ], level: 'info' }, application: { appenders: [ 'application' ], level: 'all'} }});// getLogger 传参指定的是类型exports.accessLogger = () => log4js.koaLogger(log4js.getLogger('access')); // 记录所有访问级别的日志exports.logger = log4js.getLogger('application');

简单解释一下,configure 是 log4js-node 的配置(后文会详解),通过 getLogger 函数传参为日志类型,比如 access 是访问级别日志。

然后在 app.js 中加入:

const { accessLogger, logger } = require('./utils/logger');app.use(accessLogger())

以及 routes/index.js 中加入:

+ const { logger } = require('../utils/logger')router.get('/', async (ctx, next) => {+ logger.info('我是首页'); await ctx.render('index', { title: 'Hello Koa 2!' })})

刷新,可以看到在 log 文件夹中输出两个文件:

Recorded separately:

[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"[2021-10- 12T10:43:33.902] [INFO] application -I am Home

Let's look at the log4js configuration.

level

Log classification, the main role is to better display logs (different colors), there are selective drop logs, such as in production to avoid some debug sensitive logs are leaked. Log4js has nine levels by default (you can modify them via 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")}

As shown below:

Only logs of equal or higher level will be output. For example, if you configure WARN, you will not output INFO logs. Log levels for different types of logs can be configured in the categories configured below.

categories

Log category. Default log categories must be configured for underlining behavior in case of no hits. The configuration is an object, and the key value is the classification name. For example, in the demo above:

{ default: { appenders: [ 'out' ], level: 'info' }, access: { appenders: [ 'access' ], level: 'info' }, application: { appenders: [ 'application' ], level: 'all'}}

Each category has two configurations appenders is a string array, is the output configuration (explained later), you can specify more than one, at least one. level is the log level above.

appenders

Resolved log classification and classification, followed by log drop, that is, the output log problem. The corresponding configuration is appenders. The key value of this configuration is a user-defined name (which can be used for appenders in categories). The attribute value is an object. The output type is configured. As follows:

//output appenders of log: { access: { type: 'dateFile', pattern: '-y-MM-dd.log',//Rules for generating files alwaysIncludePattern: true, //filenames are always date-specific encoding: 'utf-8', filename: path. join(LOG_PATH, 'access.log')//generate filename}, out: { type: 'console' }}

Among them, out refers to the output through the console, which can be used as one of our bottoms. The type in access is dataFile, which refers to the output file, and then the name and output path of the configuration file. In addition to this type, details can be seen on the official website, such as SMTP sent by mail (this requires nodemailer)

Summary Configuration

Log classification, log classification, and log drop. The configuration relationships are as follows:

That's all for the article "How to write a blog in Node.js", thanks for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report