[Node.js] Add Logging to a Node.js Application using Winston
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');
[Node.js] Add Logging to a Node.js Application using Winston的更多相关文章
- node.js学习(二)--Node.js控制台(REPL)&&Node.js的基础和语法
1.1.2 Node.js控制台(REPL) Node.js也有自己的虚拟的运行环境:REPL. 我们可以使用它来执行任何的Node.js或者javascript代码.还可以引入模块和使用文件系统. ...
- Edge.js:让.NET和Node.js代码比翼齐飞
通过Edge.js项目,你可以在一个进程中同时运行Node.js和.NET代码.在本文中,我将会论述这个项目背后的动机,并描述Edge.js提供的基本机制.随后将探讨一些Edge.js应用场景,它在这 ...
- io.js - 兼容 NPM 平台的 Node.js 新分支
io.js(JavaScript I/O)是兼容 NPM 平台的 Node.js 新分支,由 Node.js 的核心开发者在 Node.js 的基础上,引入更多的 ES6 特性,它的目的是提供更快的和 ...
- [Whole Web, Node.js, PM2] Configuring PM2 for Node applications
In this lesson, you will learn how to configure node apps using pm2 and a json config file. Let's sa ...
- [Node.js] 01 - How to learn node.js
基本概念 链接:https://www.zhihu.com/question/47244505/answer/105026648 链接:How to decide when to use Node.j ...
- Node.js实战(四)之调试Node.js
当项目逐渐扩大以后,功能越来越多,这时有的时候需要增加或者修改,同时优化某些功能,就有可能出问题了.针对于线上Linux环境我们应该如何调试项目呢? 别怕,Node.js已经为我们考虑到了. 通过 n ...
- Windows10安装node.js,vue.js以及创建第一个vue.js项目
[工具官网] Node.js : http://nodejs.cn/ 淘宝NPM: https://npm.taobao.org/ 一.安装环境 1.本机系统:Windows 10 Pro(64位)2 ...
- 前端(Node.js)(3)-- Node.js实战项目开发:“技术问答”
1.Web 与 Node.js 相关技术介绍 1.1.Web应用的基本组件 web应用的三大部分 brower(GUI)<==>webserver(business logic.data ...
- node.js day01学习笔记:认识node.js
Node.js(JavaScript,everywhere) 1.Node.js 介绍 1.1. 为什么要学习Node.js 企业需求 + 具有服务端开发经验更好 + front-end + back ...
随机推荐
- 最大正方形 同luogu1387
这道题下面这么写就够了(n<=100)暴力,枚举 #include<bits/stdc++.h> #define ULL unsigned long long #define MAX ...
- 为什么使用HttpServlet?http协议特点、servlet
因为只有HttpServlet是基于http协议,实现Servlet接口,而http协议是短连接协议,能够实现客户端访问服务端后,数据交互后 连接自动断开.同时http协议基于tcp.ip协议,封装了 ...
- 350 Intersection of Two Arrays II 两个数组的交集 II
给定两个数组,写一个方法来计算它们的交集.例如:给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].注意: 输出结果中每个元素出现的次数, ...
- Unity学习-地形的设置(五)
添加地形游戏对象 [Hierarchy-Create-Terrain] 为了看的看清楚,在添加一个平行光 [Hierarchy-Create-Direction light] 导入地形包 [Asset ...
- python--11、协程
协程,又称微线程,纤程.英文名Coroutine. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B在执行过程中又调用了C,C执行完毕返回,B执行完毕返回,最后是A执行完毕. 所以子程 ...
- Android进入一个新页面,EditText失去焦点并禁止弹出键盘
android在进入一个新页面后,edittext会自动获取焦点并弹出软键盘,这样并不符合用户操作习惯. 在其父控件下,添加如下的属性,就可以完美解决,使其进入页面后不主动获取焦点,并且不弹出软键盘: ...
- servlet-响应信息的content-Type作用
package servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; im ...
- Centos永久路由添加教程
Centos 永久路由添加,一张图看懂全部 blog地址:http://www.cnblogs.com/caoguo
- java_第一个servlet小程序
xml中注册: <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>s ...
- mysql异地备份方案经验总结
Mysql 数据库异地备份脚本 实验环境:关闭防火墙不然不能授权登录 Mysql-server:192.168.30.25 Mysql-client: 192.168.30.24 实验要求:对mys ...