


An introduction to methods to avoid Node.js module logs from polluting program logs
Video tutorial recommendation: nodejs tutorial
Have you ever had such an experience? When you add logging to a custom Node module and think you'll benefit from the extra information, you discover that when you add the module as a dependency and run npm install
and npm start
, will your program log look like the following?
#How do you find the information you actually need? Like who logged in and when, rather than information from application dependencies:
Likewise, when you suspect that your When a change the team made to a Node module dependency caused performance degradation, the only logs that needed to be addressed were:
Looking at the big picture, this is Here’s what log pollution looks like:
What do we want
The ideal logging solution is one where module logs do not enter the logging of a program or service, but Ability to open it for troubleshooting when needed.
To do this, I will show you how to use the debug module to turn logging on or off in the Node module.
If you don't need them and the service using this module runs fine, set it to OFF.
ON Used when you encounter a problem and need as much log information as possible.
debug
Module Overview
In terms of functionality, please do not think of debug modules as you would normally think of them in a debugger (like how you set breakpoints in the IDE) in the same way), but should be more like a modified console
module. This is a tool that allows you to turn logs on and off as needed. If you go to its GitHub page (https://github.com/visionmedi...), you will also see its various other features, such as namespaces, etc. Ignore that for now, just know that it is a tool that can optimize your production environment.
Implementing debug in your own Node module
Let’s look at an example of using debug
in your code. Assume the following is a module:
const debug = require('debug'); const log = debug('http:server'); const http = require('http'); const name = 'Demo App for debug module'; log('booting %o', name); http.createServer((req, res) => { log(req.method + ' ' + req.url); res.end('debug example\n'); }).listen(3200, () => { log('listening'); });
Implementing debug
is easy. All we have to do is import or require the module, and then create a logger - const log = debug('http:server');
. You just need to pass the tag or namespace 'http:server' of a specific logger to the DEBUG
environment variable to enable debugging.
When you start the application (that is, the program that imported the module), you will start it like this:
DEBUG=http:server node app-entrypoint.js
If we want What should I do if I use a separate logger to switch certain logs? For example, what if we only want to switch to error? It's as simple as creating another logger, like this:
const debug = require('debug'); const log = debug('http:server'); const errorLogger = debug('http:error'); // create new logger here, passing it a new namespace const http = require('http'); const name = 'Demo App for debug module'; log('booting %o', name); http.createServer((req, res) => { log(req.method + ' ' + req.url); res.end('hello\n'); // fake an error to demonstrate using debug for http:error namespace setTimeout(() => { errorLogger('fake error'); // then call the logger }, 1000); }).listen(3200, () => { log('listening'); });
如下所示将会仅打开错误:
DEBUG=http:error node app-entrypoint.js
而且,当你要记录所有命名空间的日志时(在这种情况下,是 http:server
和 http:error
),只需传递通配符 *
即可。
DEBUG=http:* node app-entrypoint.js
让我们看看这些日志现在是什么样的:
然后,当我们加载页面时:
注意,debug
会写入 stderr
而不是 stdout
,所以如果你有一个根据不同的来源提取日志的日志路由,这些调试日志将最终会存储在 stderr 流中。
最后,你还可以选择:
- 你可以记录所有用
debug
编写的模块的日志。 - 或者,你仍然可以用
console.log()
/console.error()
记录某些内容,而另一些记录debug
如果你有必须要记录的事项,并且与使用该模块的应用程序有关,请用 console
将其记录下来。但是如果你不这样做,就会用 debug
记录所有的内容。
为第三方模块打开 debug
到目前为止,如果你(或你的团队)编写了该模块,那么我们所介绍的内容就很棒。
但是如果你用的是第三方模块,那需要打开调试时该怎么办?
也许你已经对程序的各个部分进行了故障排除,不够现在假设你正在使用的开源模块可能会让你遇到问题。
好消息是,debug
是一个使用非常广泛的模块,npm 中的许多模块可能都在用它。第三方模块的创建者知道(至少,应该知道)该模块的用户真的不希望默认情况下进行记录,因为所有其他的日志都可能会变得杂乱无章。
由于 Express 内部使用了 debug 模块,所以如果你用了 Express 并需要对其进行故障排除,则可以通过运行以下命令打开日志:
DEBUG=express:* node your-app-entrypoint.js
查看开源 node 模块是否使用了 debug
以及是如何使用的
如果在文档中没有看到关于是否使用了 debug
的内容该怎么办? 即便如此,也有可能使用了该模块,但是你必须进行一些挖掘。
我们已经知道 Express 文档中描述了该如何使用它,但是我们假设它并没有记录在案:
首先,你可以在项目的 GitHub(或其他开放源代码网站)上搜索 package.json
,然后查找其中列出的作为依赖项的模块:
确认后,你还需要确认 1)实际正在使用中,以及 2)切换需要使用哪些标志。 GitHub 现在具有一项不错的功能,你可以在其中使用搜索栏搜索项目本身。如果我们在 Express 项目中搜索“debug”,则会发现以下内容:
We can see that the switch is marked "express", so express:*
will give us all's logs, express:view
will give us the view's logs, etc.
Summary
Hope you saw how easy it is to implement debug
in the node module and turn it on for third-party modules, and how it can help you clean up your logs while also Again giving you a convenient way to turn it back on for troubleshooting.
For more programming-related knowledge, please visit: Programming Courses! !
The above is the detailed content of An introduction to methods to avoid Node.js module logs from polluting program logs. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.