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
2 Answers
You can overwrite the console.log,console.debug,console.error,console.warn functions to allow logLevels.
Check out my snippet written in typescript:
export const logLevels = ["debug", "log", "warn", "error", "none"] as const;
type LogLevel = (typeof logLevels)[number];
declare global {
var logLevel: LogLevel;
}
const shouldLog = (level: LogLevel) => {
return logLevels.indexOf(level) >= logLevels.indexOf(global.logLevel);
};
global.logLevel = "debug";
const _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"
Comments
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.
log.jsbased on an env variable - as per your question ? ( I have the same question ) stackoverflow.com/questions/71082365/…