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');

Github

[Node.js] Add Logging to a Node.js Application using Winston的更多相关文章

  1. node.js学习(二)--Node.js控制台(REPL)&&Node.js的基础和语法

    1.1.2 Node.js控制台(REPL) Node.js也有自己的虚拟的运行环境:REPL. 我们可以使用它来执行任何的Node.js或者javascript代码.还可以引入模块和使用文件系统. ...

  2. Edge.js:让.NET和Node.js代码比翼齐飞

    通过Edge.js项目,你可以在一个进程中同时运行Node.js和.NET代码.在本文中,我将会论述这个项目背后的动机,并描述Edge.js提供的基本机制.随后将探讨一些Edge.js应用场景,它在这 ...

  3. io.js - 兼容 NPM 平台的 Node.js 新分支

    io.js(JavaScript I/O)是兼容 NPM 平台的 Node.js 新分支,由 Node.js 的核心开发者在 Node.js 的基础上,引入更多的 ES6 特性,它的目的是提供更快的和 ...

  4. [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 ...

  5. [Node.js] 01 - How to learn node.js

    基本概念 链接:https://www.zhihu.com/question/47244505/answer/105026648 链接:How to decide when to use Node.j ...

  6. Node.js实战(四)之调试Node.js

    当项目逐渐扩大以后,功能越来越多,这时有的时候需要增加或者修改,同时优化某些功能,就有可能出问题了.针对于线上Linux环境我们应该如何调试项目呢? 别怕,Node.js已经为我们考虑到了. 通过 n ...

  7. Windows10安装node.js,vue.js以及创建第一个vue.js项目

    [工具官网] Node.js : http://nodejs.cn/ 淘宝NPM: https://npm.taobao.org/ 一.安装环境 1.本机系统:Windows 10 Pro(64位)2 ...

  8. 前端(Node.js)(3)-- Node.js实战项目开发:“技术问答”

    1.Web 与 Node.js 相关技术介绍 1.1.Web应用的基本组件 web应用的三大部分 brower(GUI)<==>webserver(business logic.data ...

  9. node.js day01学习笔记:认识node.js

    Node.js(JavaScript,everywhere) 1.Node.js 介绍 1.1. 为什么要学习Node.js 企业需求 + 具有服务端开发经验更好 + front-end + back ...

随机推荐

  1. IT架构师介绍-软件架构设计学习第一天(非原创)

    文章大纲 一.架构师定义二.架构师分类与具备能力三.研发人员发展的技术路线四.架构师知识体系五.参考文章   一.架构师定义   什么是架构师,这个聊架构话题时永恒的问题.每个公司对架构师的定位也有所 ...

  2. UVM基础之----uvm_object

    uvm_void The uvm_void class is the base class for all UVM classes. uvm_object: The uvm_object class ...

  3. JSP中如何利用JS实现登录页面的跳转(JSP中如何利用JS实现跳转页面)

    <%!          <%                               url =              word =          }             ...

  4. 【译】x86程序员手册16-5.3联合使用段与分页转换

    5.3 Combining Segment and Page Translation  联合使用段与分页转换 Figure 5-12 combines Figure 5-2 and Figure 5- ...

  5. 微信小程序php后台实现

    这里简单介绍用php后台实现获取openid并保存到数据库: 微信的登陆流程是这样的 首先前端发送请求到服务器: wx.login({ success: function (res) { var co ...

  6. Tomcat服务器安装与第一个jsp网页程序

    1.安装tomcat服务器之前需要,先安装相应版本的jdk,个人理解Tomcat的大部分功能是使用了java的 jdk jar包的. jdk包下载方式网上可以查到 下载完后可以解压到一个指定目录,并在 ...

  7. Objective-C在ARC下结合GCD的单例模式和宏模版

    单例模式在iOS开发过程中经常用到,苹果提供过objective c单例的比较官方的写法: static MyGizmoClass *sharedGizmoManager = nil; + (MyGi ...

  8. python笔记之发送邮件

    发送邮件前提:开启邮箱授权码 一.开启授权码(以163邮箱为例) 1.登录163邮箱,点击设置--POP3/SMTP/IMAP,出现设置界面   2. 开启SMTP服务且可以查询SMTP的host地址 ...

  9. gitlab 第1次提交代码到1个新仓库

    1.如果是本地刚刚搭建好git环境,第一次和gitlab服务器产生连接 参照这个文 https://www.cnblogs.com/kaerxifa/p/10929098.html 2.已经和gitl ...

  10. vi 命令学习(三)

    [末行命令] 末行命令主要是针对文件进行操作的:保存.退出.保存&退出.搜索&替换.另存.新建.浏览文件 命令                                     ...