Welcome to ciysys blog

Logging part 1 - 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

Conclusion

Logging which process is running the function is important and it will be helpful in troubleshooting.

Related posts

  1. Logging part 1 - down the process ID (pid) and thread ID (threadId).
  2. Logging part 2 - runtime performance.

Jump to #NODEJS blog

Author

Lau Hon Wan, software developer.