'Node.js Command Line Console Log Level
How do you set the log level for node when starting it from the command line? I admit, i'm a node.js newbie, but looking for something like node myapp.js --loglevel warn
Solution 1:[1]
Not possibly quite what you are after but you can enable debugging within node by setting a NODE_DEBUG environment variable first.
E.g. export NODE_DEBUG="net" && node myapp.js
will give debugging for network related node operations.
Solution 2:[2]
You can overwrite the console.log
,console.debug
,console.error
,console.warn
functions to allow logLevels.
Check out my snippet written in typescript:
export type LogLevel = "debug" | "log" | "warn" | "error" | "none";
let logLevels = ["debug", "log", "warn", "error", "none"];
let shouldLog = (level: LogLevel) => {
// @ts-ignore
return logLevels.indexOf(level) >= logLevels.indexOf(global.logLevel);
};
// @ts-ignore
global.logLevel = "debug";
let _console=console
global.console = {
...global.console,
log: (message?: any, ...optionalParams: any[]) => {
shouldLog("log")&&_console.log(message, ...optionalParams);
},
warn: (message?: any, ...optionalParams: any[]) => {
shouldLog("warn") && _console.warn(message, ...optionalParams);
},
error: (message?: any, ...optionalParams: any[]) => {
shouldLog("error") && _console.error(message, ...optionalParams);
},
debug: (message?: any, ...optionalParams: any[]) => {
shouldLog("debug") && _console.debug(message, ...optionalParams);
},
};
Then you can use the console
functions as usual and set the logLevel with globals.logLevel="warn"
,...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AndyA |
Solution 2 | haschtl |