Best practices for console.log in contrib nodes?

Hello,

I'd like my custom nodes to log in the seamlessly in terminal window or in the debug window. I was wondering if there are any best practices for this or a util that's available that will handle the timestamping and formatting.

I'm trying to avoid doint this:

this.socket.on('error', function (err) {
   console.log(err.toString());
});

Thanks and happy NYE :mirror_ball: :tada: :partying_face:

you can use node.log("words") to write to the log file, node.warn("words") to the log and sidebar, and node.error("words",msg) to create a error that the catch node can handle (and goes to the log) - and where msg is the incoming message that caused the error.

See here for details of how to handle errors.

The docs have a section on logging: JavaScript file : Node-RED

In those examples, this is your node. To access them inside a callback function like in your example, you'll want to assign this to a variable so you can reference it.

You'll commonly see the following used:

const node = this

So you can then use node.log(...)

2 Likes

The contemporary javascript way would be to use a closure, for example:

this.socket.on('error', (err) => {
   this.log(`socket error: ${err}`);
});

ah yes - need to tweak that error example to include the msg.

Additional note: while console.log takes multiple arguments and prints them space-separated, the various this.log, this.warn, this.error don't: they only have a single string argument (plus the msg argument for error).

There is still a role for console.log, which is to print a data structure. JSON.stringify can work as an alternative in many cases, but it barfs if there is any circularity. There's probably some helper in Node.js, though...

Thank you all. I really appreciate all the great advice :grinning:

But it is discouraged - because if Node-RED is running in an environment with a custom log handler, console.logs won't be captured.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.