Log down the process ID (pid) and thread ID (threadId)
Published on: 23th Nov 2024
Overview
Life can be complicated if you are developing a system that supports many user features. When everything works properly, you will have a feeling like you are invisible. But, when unexpected things always happen and the program crashes, you will need to find out the cause of the failure. We will have to identify which line caused the crash and gather as much as possible on the runtime value. Node.js stack dump provides some hints on what has happened, at which line it crashed and most of the time this is sufficient to fix the issue.
If you are running your system with multiple instances and each instance has multiple threads, the troubleshooting will become complex. This is because Node.js provides the stack dump of the crashing line without the process ID and the thread ID. This makes it difficult to guess or imagine the runtime value and what has happened.
A simple program to explain the process ID and thread ID
const w = require('worker_threads');
if (w.isMainThread) {
// running on the main thread
console.log(`main:pid=${process.pid},thread id=${w.threadId}`);
for (let i = 0; i < 3; i++) {
const w2 = new w.Worker(__filename);
w2.my_id = i + 1;
w2.on('exit', () => {
console.log('thread exit', w2.my_id);
});
}
setTimeout(() => {
const w2 = new w.Worker(__filename);
w2.my_id = 4;
w2.on('exit', () => {
console.log('thread exit', w2.my_id);
});
}, 1000);
setTimeout(() => {
const w2 = new w.Worker(__filename);
w2.my_id = 5;
w2.on('exit', () => {
console.log('thread exit', w2.my_id);
});
}, 2000);
}
else {
// running on a worker thread
console.log(`worker:pid=${process.pid},thread id=${w.threadId}`);
}
Here's the output:
main:pid=9788,thread id=0
worker:pid=9788,thread id=1
thread exit 1
worker:pid=9788,thread id=2
thread exit 2
worker:pid=9788,thread id=3
thread exit 3
worker:pid=9788,thread id=4
thread exit 4
worker:pid=9788,thread id=5
thread exit 5
Explanations
- The process ID (
process.pid
)- It is a value assigned by the operating system.
- In the syslog on Linux, it has the information about a process start time and crashing time. It will give you some hints at what time it crashed.
- The worker thread ID (
threadId
)- It is a running value assigned by Node.js and the main thread ID is always zero (0).
- Logging this value is helpful especially when you are passing some data across threads. With this information, you will be able to tell if the data has been passed to the correct thread. For example, the worker thread should pass the data to the main thread and there is a chance that you were passing the data on the same thread and the program is not working as expected.
Conclusion
Logging is necessary and it will be helpful in troubleshooting.
Jump to #NODEJS blog
Author
Lau Hon Wan, software developer.