Home >Web Front-end >JS Tutorial >Teach you step by step how to write logs in Node.js service
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!
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.
First make sure you have installed it globallykoa2
:
npm i koa2 -g
Then execute:
The basic services ofkoa2 -e node-log # 新建一个项目 cd node-log npm i # 安装依赖 npm run start # 启动
are set up. Visit http://localhost:3000/
, you can see the following page:
The above is a quick setupkoa
Service method. This project has a built-in logging library - koa-logger
. Let's first take a look at what it does.
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());
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 -
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) }))
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
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. 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.
Installation:
npm i --save koa-log4
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('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');
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: <pre class="brush:js;toolbar:false;">const { accessLogger, logger } = require(&#39;./utils/logger&#39;);
app.use(accessLogger())</pre>
to
and routes/index.js
to add:
+ const { logger } = require('../utils/logger') router.get('/', async (ctx, next) => { + logger.info('我是首页'); await ctx.render('index', { title: 'Hello Koa 2!' }) })
Refresh , you can see that two files are output in the log
folder:
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"
[2021-10-12T10:43:33.902] [INFO] application - 我是首页
Next we come Take a look at the configuration of log4js
.
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") }As shown in the figure below:
只会输出级别相等或者级别高的日志。比如你配置了 WARN
,就不会输出 INFO
的日志。
可以在下面配置的 categories
中配置不同的类型日志的日志级别。
日志类别。必须配置默认日志类别,用于没有命中的情况下的兜底行为。该配置为一个对象,key
值为分类名称。比如上述 demo
中:
{ default: { appenders: [ 'out' ], level: 'info' }, access: { appenders: [ 'access' ], level: 'info' }, application: { appenders: [ 'application' ], level: 'all'} }
其中每个类别都有两个配置 appenders
是一个字符串数组,是输出配置(后文中会详解),可以指定多个,至少要有一个。level
是上文日志级别。
解决了日志分级和分类,接下来是日志落盘,也就是输出日志的问题。对应的配置是 appenders
,该配置的 key
值为自定义的名称(可以给 categories
中的 appenders
使用),属性值为一个对象,配置输出类型。如下所示:
// 日志的输出 appenders: { access: { type: 'dateFile', pattern: '-yyyy-MM-dd.log', //生成文件的规则 alwaysIncludePattern: true, // 文件名始终以日期区分 encoding: 'utf-8', filename: path.join(LOG_PATH, 'access.log') //生成文件名 }, out: { type: 'console' } }
其中,out
指的是通过 console
输出,这个可以作为我们的一个兜底。access
中 type
为 dataFile
,指的是输出文件,然后配置文件的命名和输出路径。除了这个类型,详情可以看官网,比如 SMTP
通过邮件发送(这个需要 nodemailer
)
日志分级、日志分类以及日志落盘,配置上的关系如下:
日志对于我们服务端排查定位问题非常重要,本文通过 koa-logger
和 koa-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!