Loglevel in ECMA2021 script

I am trying to learn how to use logging in ECMA2021 scripts.

The UID of my ECMA2021 in this example is “TestOwnLogger”.

This is my Script

"use strict";
console.warn("this is a Warn log");
console.info("this is a Info log");
console.trace("this is a Trace log");

within karaf i used this command:

log:set TRACE openhab.automation.script.ui.TestOwnLogger

and log:list output is:

so far so good.

but the output of my script is:

why is the TRACE message missing here?

The logger identifier is incomplete, it should be

log:set TRACE org.openhab.automation.script.ui.TestOwnLogger

@florian-h05 thanks! Now it works.

Just another question. Is there a way to set the loglevel via script or UI instead of karaf?

So after checking the openHAB codebase, I found a way to set a log level from a script:

// ECMAScript-2021 / JS Scripting
osgi.getService('org.apache.karaf.log.core.LogService').setLevel(console.loggerName, 'TRACE')

From UI, you can only set add-on log level (coming with openHAB 4). but not generally for all scripts. You may use the REST API endpoint (available since openHAB 3.3.0), use Developer Tools → API Explorer → logging.

@rlkoshak Do you think changing log levels from scripting is a common task? If yes, we should probably provide an action to do that.

1 Like

I can’t imagine it would be common, but I can see some cases where a user detects some problem (e.g. a Thing went offline) and wants to capture some trace logging when they restart the binding through a script or something like that.

I personally would probably use this in the ~Scratchpad~ occasionally to turn up the logging on a rule I’m debugging.

As I think about all the ways people control the logging in their rules, I think I could see this being appreciated as part of the library. But in my case, it’s not just changing the logging level of the current rule/script but being able to change any arbitrary logger’s level.

Of course you can change any log level with the method above, the first parameter takes the logger indentifier and the seconds one the level.

Yes, I figured that. I only mentioned if in case you decide to add it to the library that we retain the ability to change other loggers. So we have more than just

console.level = 'TRACE';

for example.