21

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

5
  • 1
    What do you mean "the log level"? As determined by what? Commented Sep 22, 2012 at 0:23
  • 1
    Node provides no intrinsic logging, other than printing an error message on unhandled exceptions, so there is no loglevel to set. Commented Sep 22, 2012 at 4:29
  • 9
    To add to what Rob said, the console.log/console.warn/console.err methods are just writers to stdout/stderr, there's nothing that uses those method names to determine if something is outputted or not. Commented Sep 22, 2012 at 13:20
  • 4
    thanks guys, i'm using this library now in case anyone is interested: github.com/visionmedia/log.js Commented Oct 1, 2012 at 5:24
  • @kocodude but how do you filter the logs you see from log.js based on an env variable - as per your question ? ( I have the same question ) stackoverflow.com/questions/71082365/… Commented Feb 11, 2022 at 15:20

2 Answers 2

9

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"

Sign up to request clarification or add additional context in comments.

Comments

2

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.

https://github.com/joyent/node/blob/master/lib/net.js#L66

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.