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. Android Studio 常用快捷键(超实用!!!)

    快捷键又称为“热键”,多个按键的组合可以实现某些快速操作,例如Window中最常用的Ctrl+C和Ctrl+V,熟练使用快捷键可以大大提高开发效率并可以减少某些错误的发生.Android Studio ...

  2. assistant: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by

    [oracle@oracledb button]$ assistantassistant: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' no ...

  3. Java 删除List元素的正确方式

    方式一:使用Iterator的remove()方法 public class Test { public static void main(String[] args) { List<Strin ...

  4. ZOJ3714JavaBeans

    #!/usr/bin/env python # encoding: utf-8 t = int(raw_input()) for i in range(t): n,k = [int(x) for x ...

  5. web api初学

    据说web api的作用和wcf的一样,只是比wcf更简单而已,具体如何我也不清楚,毕竟不是做学术研究的,我只是通过简单的例子来学习web api.能做的只需要知其然,不必管其所以然.当然有兴趣的可以 ...

  6. Linux命令(004) -- watch

    对Linux系统的操作过程中,经常会遇到重复执行同一命令,以观察其结果变化的情况.惯用的方法是:上下键加回车,或是Ctr+p然后回车.今天我们来了解一下watch命令,它可以帮助我们周期性的执行一个命 ...

  7. 跨服务器进行SQL Server数据库的数据处理

    exec sp_addlinkedserver 'ITDB', ' ', 'SQLOLEDB', '服务器IP' exec sp_addlinkedsrvlogin 'ITDB', 'false ', ...

  8. Python爬取贴吧中的图片

    #看到贴吧大佬在发图,准备盗一下 #只是爬取一个帖子中的图片 1.先新建一个scrapy项目 scrapy startproject TuBaEx 2.新建一个爬虫 scrapy genspider ...

  9. S-HR之时间空间配置

    <field name="entrys.bizDate"   dataType = "DATE"  label="生效日期" year ...

  10. Capture the Flag ZOJ - 3879(模拟题)

    In computer security, Capture the Flag (CTF) is a computer security competition. CTF contests are us ...