Node.js 命令行控制台日志级别

标签 node.js command-line-arguments

从命令行启动 Node 时,如何设置 Node 的日志级别?我承认,我是一个 node.js 新手,但正在寻找像 node myapp.js --loglevel warn

这样的东西

最佳答案

你可以覆盖console.log,console.debug,console.error,console.warn允许 logLevels 的函数。

看看我用 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);
  },
};

然后您可以像往常一样使用console 函数并使用globals.logLevel="warn" 设置logLevel,...

关于Node.js 命令行控制台日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539599/

相关文章:

java - 如果存在命令行值,则覆盖属性文件

c# - C# 命令行中的自定义主入口点参数

windows - 在 Windows 上的 mongorc 中设置 mongodb 编辑器路径

node.js - 将 angular 2 App(angular cli)部署到 heroku

node.js - 如何增加 gulp 任务的堆栈跟踪?

node.js - 在 Node JS - Express 应用程序中将注册用户保存到 MongoDB 时出现问题

python - argparse 接受 int 和字符串?

c++ - 为什么 C++ 中的 main() 没有重载以使用 std::string?

json - 将 JSON 传递给 HTTP POST 请求

php - 使用 http 请求在 php 旁边使用 node.js 是否安全?