Skip to content

Commit e493e36

Browse files
committed
refactor(cli): organize logging configuration
As a result the responsibility of managing the initial configuration for logging has been moved outside the DefaultServient.
1 parent ee16e04 commit e493e36

3 files changed

Lines changed: 57 additions & 78 deletions

File tree

packages/cli/src/cli-default-servient.ts

Lines changed: 9 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { FileClientFactory } from "@node-wot/binding-file";
2828
import { ThingModelHelpers } from "@thingweb/thing-model";
2929
import { createContext, Script } from "vm";
3030
import { CompilerFunction } from "./compiler-function";
31+
import { LogLevel, setLogLevel } from "./utils/set-log-level";
3132

3233
const { debug, error, info } = createLoggers("cli", "cli-default-servient");
3334

@@ -77,9 +78,6 @@ export default class DefaultServient extends Servient {
7778
coap: {
7879
port: 5683,
7980
},
80-
log: {
81-
level: "info",
82-
},
8381
};
8482

8583
private uncaughtListeners: Array<NodeJS.UncaughtExceptionListener> = [];
@@ -103,9 +101,6 @@ export default class DefaultServient extends Servient {
103101
this.config.servient.clientOnly = true;
104102
}
105103

106-
// set log level before any output
107-
this.setLogLevel(this.config.log.level);
108-
109104
// load credentials from config
110105
this.addCredentials(this.config.credentials);
111106

@@ -249,7 +244,10 @@ export default class DefaultServient extends Servient {
249244
actions: {
250245
setLogLevel: {
251246
description: "Set log level",
252-
input: { oneOf: [{ type: "string" }, { type: "number" }] },
247+
input: {
248+
type: "string",
249+
enum: ["debug", "info", "warn", "error"],
250+
},
253251
output: { type: "string" },
254252
},
255253
shutdown: {
@@ -268,16 +266,10 @@ export default class DefaultServient extends Servient {
268266
},
269267
});
270268

271-
servientProducedThing.setActionHandler("setLogLevel", async (level) => {
272-
const ll = await Helpers.parseInteractionOutput(level);
273-
if (typeof ll === "number") {
274-
this.setLogLevel(ll as number);
275-
} else if (typeof ll === "string") {
276-
this.setLogLevel(ll as string);
277-
} else {
278-
// try to convert it to strings
279-
this.setLogLevel(ll + "");
280-
}
269+
servientProducedThing.setActionHandler("setLogLevel", async (payload) => {
270+
const level = (await Helpers.parseInteractionOutput(payload)) as LogLevel;
271+
setLogLevel(level);
272+
this.logLevel = level;
281273
return `Log level set to '${this.logLevel}'`;
282274
});
283275
servientProducedThing.setActionHandler("shutdown", async () => {
@@ -310,60 +302,4 @@ export default class DefaultServient extends Servient {
310302
process.removeListener("uncaughtException", listener);
311303
});
312304
}
313-
314-
// Save default loggers (needed when changing log levels)
315-
private readonly loggers: any = {
316-
warn: console.warn,
317-
info: console.info,
318-
debug: console.debug,
319-
};
320-
321-
private setLogLevel(logLevel: string | number): void {
322-
if (logLevel === "error" || logLevel === 0) {
323-
console.warn = () => {
324-
/* nothing */
325-
};
326-
console.info = () => {
327-
/* nothing */
328-
};
329-
console.debug = () => {
330-
/* nothing */
331-
};
332-
333-
this.logLevel = "error";
334-
} else if (logLevel === "warn" || logLevel === "warning" || logLevel === 1) {
335-
console.warn = this.loggers.warn;
336-
console.info = () => {
337-
/* nothing */
338-
};
339-
console.debug = () => {
340-
/* nothing */
341-
};
342-
343-
this.logLevel = "warn";
344-
} else if (logLevel === "info" || logLevel === 2) {
345-
console.warn = this.loggers.warn;
346-
console.info = this.loggers.info;
347-
console.debug = () => {
348-
/* nothing */
349-
};
350-
351-
this.logLevel = "info";
352-
} else if (logLevel === "debug" || logLevel === 3) {
353-
console.warn = this.loggers.warn;
354-
console.info = this.loggers.info;
355-
console.debug = this.loggers.debug;
356-
357-
this.logLevel = "debug";
358-
} else {
359-
// Fallback to default ("info")
360-
console.warn = this.loggers.warn;
361-
console.info = this.loggers.info;
362-
console.debug = () => {
363-
/* nothing */
364-
};
365-
366-
this.logLevel = "info";
367-
}
368-
}
369305
}

packages/cli/src/cli.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import DefaultServient, { ScriptOptions } from "./cli-default-servient";
1818

1919
// tools
2020
import * as path from "path";
21-
import { Command, Argument } from "commander";
21+
import { Command, Argument, Option } from "commander";
2222
import Ajv, { ValidateFunction } from "ajv";
2323
import ConfigSchema from "./wot-servient-schema.conf.json";
2424
import { version } from "@node-wot/core/package.json";
@@ -27,8 +27,8 @@ import { buildConfig } from "./config-builder";
2727
import { loadCompiler, loadEnvVariables } from "./utils";
2828
import { runScripts } from "./script-runner";
2929
import { readdir } from "fs/promises";
30-
import * as logger from "debug";
3130
import { parseConfigFile, parseConfigParams, parseIp } from "./parsers";
31+
import { setLogLevel } from "./utils/set-log-level";
3232

3333
const { error, info, warn, debug } = createLoggers("cli", "cli");
3434

@@ -120,6 +120,12 @@ program
120120
.option("-ib, --inspect-brk [host]:[port]", "activate inspector on host:port (default: 127.0.0.1:9229)", parseIp)
121121
.option("-c, --client-only", "do not start any servers (enables multiple instances without port conflicts)")
122122
.option("-cp, --compiler <module>", "load module as a compiler")
123+
.addOption(
124+
new Option(
125+
"-ll, --logLevel <string>",
126+
"choose the desired log level. WARNING: if DEBUG env variable is specified this option gets overridden."
127+
).choices(["debug", "info", "warn", "error"])
128+
)
123129
.option("-f, --config-file <file>", "load configuration from specified file", (value, previous) =>
124130
parseConfigFile(value, previous, schemaValidator)
125131
)
@@ -138,11 +144,11 @@ program.addArgument(
138144
);
139145

140146
program.action(async function (_, options, cmd) {
147+
// Allow user to personalized the env
141148
if (process.env.DEBUG == null) {
142149
// by default enable error logs and warnings
143-
// user can override it using DEBUG env
144-
logger.enable("node-wot:**:error");
145-
logger.enable("node-wot:**:warn");
150+
// user can override using command line option
151+
setLogLevel(options.logLevel ?? "warn");
146152
}
147153

148154
const args = cmd.args;
@@ -156,6 +162,8 @@ program.action(async function (_, options, cmd) {
156162

157163
try {
158164
const config = await buildConfig(options, defaultFilePath, env);
165+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
166+
setLogLevel((config.log as any).level ?? options.logLevel ?? "warn");
159167
servient = new DefaultServient(options.clientOnly, config);
160168
} catch (err) {
161169
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT" || options.configFile != null) {
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/********************************************************************************
2+
* Copyright (c) 2025 Contributors to the Eclipse Foundation
3+
*
4+
* See the NOTICE file(s) distributed with this work for additional
5+
* information regarding copyright ownership.
6+
*
7+
* This program and the accompanying materials are made available under the
8+
* terms of the Eclipse Public License v. 2.0 which is available at
9+
* http://www.eclipse.org/legal/epl-2.0, or the W3C Software Notice and
10+
* Document License (2015-05-13) which is available at
11+
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document.
12+
*
13+
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
14+
********************************************************************************/
15+
import { createLoggers } from "@node-wot/core";
16+
import * as logger from "debug";
17+
18+
export type LogLevel = keyof ReturnType<typeof createLoggers>;
19+
export function setLogLevel(level: LogLevel): void {
20+
logger.disable();
21+
switch (level) {
22+
case "debug":
23+
logger.enable("node-wot:*");
24+
break;
25+
case "info":
26+
logger.enable("node-wot:**:error,node-wot:**:warn,node-wot:**:info");
27+
break;
28+
case "warn":
29+
logger.enable("node-wot:**:error,node-wot:**:warn");
30+
break;
31+
case "error":
32+
logger.enable("node-wot:**:error");
33+
break;
34+
}
35+
}

0 commit comments

Comments
 (0)