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. php从数据库读取中文显示问号??的解决办法

    出错原因:1.数据库编码格式不对 2.PHP编码格式不对 3.浏览器编码格式不对 上面三者编码格式不统一,就会出现问题 数据库读取的时候在mysqli_connect()之后要设置连接字符编码mysq ...

  2. ACM_小Z的A+B

    小Z的A+B Time Limit: 2000/1000ms (Java/Others) Problem Description: 小Z最喜欢A+B了,没事就研究研究,比如什么大整数A+B(就是100 ...

  3. Mysql中的索引()key 、primary key 、unique key 与index区别)

    CREATE TABLE pre_forum_post ( pid int(10) unsigned NOT NULL COMMENT '帖子id', fid mediumint(8) unsigne ...

  4. HDU_1848_博弈,sg函数

    Fibonacci again and again Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Jav ...

  5. day08-字符编码

    目录 计算机基础 启动应用程序 写文本的流程 Python解释器执行文件的原理 Python解释器与文本编辑器的区别 字符编码 字符编码发生在哪三个阶段 字符编码发展史与分类 总结 Python2与P ...

  6. scp: /xxxx: not a regular file

    问题描述 scp root@10.2.1.92:/home /home/wangju/databakroot@10.2.1.92's password: xxxxscp: /home: not a r ...

  7. CAD从线型文件加载线型记录(com接口)

    主要用到函数说明: _DMxDrawX::LoadLinetypeFromFile 从线型文件加载线型记录,详细说明如下: 参数 说明 BSTR pszLinetypeFile 线型文件名,支持htt ...

  8. Git学习总结四(删除)

    一般情况下,你通常直接在文件管理器中把没用的文件删了,或者用rm命令删了: $ rm test.txt 这个时候,Git知道你删除了文件,因此,工作区和版本库就不一致了,git status命令会立刻 ...

  9. How To:配置Linux iSCSI客户端

    1.安装客户端 [root@node01 Packages]# rpm -Uvh iscsi-initiator-utils-6.2.0.873-2.el6.x86_64.rpm warning: i ...

  10. 模板中tempname与class区别

    前言 在分析traits编程之前, 我们需要对模板参数类型tempname和class有一定的了解, 要明白他们在哪些方面不同, 哪些方面相同, 这样才能对体会到traits编程的核心. 如果你已经明 ...