[Node.js] Add Logging to a Node.js Application using Winston
2023-09-14 08:59:17 时间
Winston is a popular logging library for NodeJS which allows you to customise the output, as well as different logging targets.
This lesson covers configuring Winston to run with different levels depending on a Node environment variable as well as enhancing the log output to include the filename and line number the log message originates from.
winston: "2.4.2", >v3.0 has breaking changes.
Below code can just take away and use. It set 'debug' log level in developerment and 'info' level for production.
logger.js:
const winston = require("winston"); const moment = require("moment"); const path = require("path"); const PROJECT_ROOT = path.join(__dirname, ".."); const consoleLogger = new winston.transports.Console({ timestamp: function() { const today = moment(); return today.format("DD-MM-YYYY h:mm:ssa"); }, colorize: true, level: "debug" }); const logger = new winston.Logger({ transports: [consoleLogger] }); if (process.env.NODE_ENV === "production") { logger.transports.console.level = "info"; } if (process.env.NODE_ENV === "development") { logger.transports.console.level = "debug"; } module.exports.info = function() { logger.info.apply(logger, formatLogArguments(arguments)); }; module.exports.log = function() { logger.log.apply(logger, formatLogArguments(arguments)); }; module.exports.warn = function() { logger.warn.apply(logger, formatLogArguments(arguments)); }; module.exports.debug = function() { logger.debug.apply(logger, formatLogArguments(arguments)); }; module.exports.verbose = function() { logger.verbose.apply(logger, formatLogArguments(arguments)); }; module.exports.error = function() { logger.error.apply(logger, formatLogArguments(arguments)); }; function formatLogArguments(args) { args = Array.prototype.slice.call(args); const stackInfo = getStackInfo(1); if (stackInfo) { const calleeStr = `(${stackInfo.relativePath}:${stackInfo.line})`; if (typeof args[0] === "string") { args[0] = args[0] + " " + calleeStr; } else { args.unshift(calleeStr); } } return args; } function getStackInfo(stackIndex) { const stacklist = new Error().stack.split("\n").slice(3); // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi // do not remove the regex expresses to outside of this method (due to a BUG in node.js) const stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi; const stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi; const s = stacklist[stackIndex] || stacklist[0]; const sp = stackReg.exec(s) || stackReg2.exec(s); if (sp && sp.length === 5) { return { method: sp[1], relativePath: path.relative(PROJECT_ROOT, sp[2]), line: sp[3], pos: sp[4], file: path.basename(sp[2]), stack: stacklist.join("\n") }; } } logger.exitOnError = false;
How to use:
const dotenv = require('dotenv').config({ path: 'variables.env' }); const colors = require('colors'); const setup = require('./setup'); const logger = require('./logger'); // run setup try{ setup.init() }catch(err){ logger.error(`Critical Error - Server Stoppping ${err}`); process.exit(); } logger.log('Server Started');
相关文章
- JS框架_(JQuery.js)文章全屏动画切换
- Node.js之Express四
- Node.js压缩与解压数据
- Node.js HTTP Server对象及GET、POST请求
- [Node.js] Add node.js command line to global
- [Docker] Hooking a Volume to Node.js Source Code
- [Node.js] Show More Lines in a Node.js Error Stack Trace
- [WASM] Run WebAssembly in Node.js using the node-loader
- [Node.js] Create a model to persist data in a Node.js LoopBack API
- [Node.js] Pass command line arguments to node.js
- [Node.js] node-persist: localStorage on the server
- [Whole Web] [Node.js] Using npm run to launch local scripts
- [Server Running] [Node.js, PM2] Using PM2 To Keep Your Node Apps Alive
- [Node.js] Level 1 new. Intro the Node.js
- Cocos2d-JS自定义粒子系统
- [Tools] Install and Manage Node.js Versions with nvm
- [Node.js] Setup Local Configuration with Node.js Applications
- [Whole Web, Nods.js, PM2] Passing environment variables to node.js using pm2
- [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
- [Whole Web] [Node.js] Using npm run to launch local scripts
- Ubuntu 20.04 安装 Node.js
- Atitit node.js问题解决总结t99 目录 1.1. 找不到node程序1 1.2. GBK编码问题1 2. 按行读取gbk编码问题2 2.1. 先写入txt utf8 encode
- Atitit. 获取cpu占有率的 java c# .net php node.js的实现
- yenv - 一个使用 JAML 文件管理环境的 Node.js 工具
- node.js JS对象和JSON字符串之间的转换
- Node.js:Array.prototype.sort数组排序的使用
- Node.js学习笔记(一)——Node.js概要、NPM与package.json
- How to set up a Headless Chrome Node.js server in Docker