nodejs 日志模块winston的使用方法


Posted in NodeJs onMay 02, 2018

winston 日志模块

在使用 nodejs winston 模块中,加上相关的两个模块,事倍功半。

  1. express-winston
  2. winston-daily-rotate-file

express-winston

是 express-winston 的 winston 的增加版, 是作为 express 的中间件来打印日志,不仅有请求头信息,并且有响应时间。
作为中间件, 为什么会有响应时间呢? 因为 express-winston 改写了 express 的 res.end 办法, 是请求结束后再打的日志。

代码片段

var end = res.end;
res.end = function(chunk, encoding) {
 res.responseTime = (new Date) - req._startTime;
 res.end = end;
 res.end(chunk, encoding);
 ...
 }

express-winston 没有修改或者扩展 winston 的transport, 而 winston-daily-rotate-file 正是增强了 winston 的transport 办法

winston-daily-rotate-file

winston-daily-rotate-file 是 winston 扩展, 增加了 transport 的办法,使 winston 有滚动日志的能力。

结合使用

我们来一个需求: 如何让 express-winston 打印日志的时候,也打印出接口 /api 的请求参数和响应数据?

  1. 该日志中间件应该在调用链 api 后面, api/* 业务处理之前。 like: app.use('/api', apiRequestLogger, apiHandler)
  2. 要获取到响应数据, 就要在业务处理完后 send 出来后才能捕获到,express 所有的请求响应最后都是走 res.send 我们可以从这里入手捕获响应数据

代码如下

import winston from 'winston'
import expressWinston from 'express-winston'
import 'winston-daily-rotate-file'
import path from 'path'

export let DailyRotateFileTransport = (fileName) => {
 return new (winston.transports.DailyRotateFile)({
 filename: path.join(process.env.LOGPATH, `${fileName}-%DATE%.log`),
 datePattern: 'YYYY-MM-DD-HH',
 // maxSize: '20m',
 maxFiles: '7d',
 timestamp: () => new Date().format('yyyy-MM-dd hh:mm:ss.S')
 })
}

export let pageRequestLogger = expressWinston.logger({
 transports: [
 DailyRotateFileTransport('page-request')
 ],
 meta: true, // optional: control whether you want to log the meta data about the request (default to true)
 msg: 'HTTP {{req.method}} {{req.url}}', // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
 expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
 colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
 ignoreRoute: function (req, res) {
 // 只打印页面请求信息
 let notPageRequest = false
 let ignoreArr = ['/api', '.js', '.css', '.png', '.jpg', '.gif']
 ignoreArr.forEach(item => {
  if (req.url.indexOf(item) > -1) notPageRequest = true
 })
 return notPageRequest
 } // optional: allows to skip some log messages based on request and/or response
})

export let apiRequestLogger = (req, res, next) => {
 let send = res.send
 let content = ''
 let query = req.query || {}
 let body = req.body || {}
 res.send = function () {
 content = arguments[0]
 send.apply(res, arguments)
 }
 expressWinston.logger({
 transports: [
  DailyRotateFileTransport('api-request')
 ],
 meta: true, // optional: control whether you want to log the meta data about the request (default to true)
 msg () {
  return `HTTP ${req.method} ${req.url} query ${JSON.stringify(query)} body ${JSON.stringify(body)} resData ${content} `
 },
 colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
 ignoreRoute: function (req, res) {
  if (req.headers.self) return true
  return false
 } // optional: allows to skip some log messages based on request and/or response
 })(req, res, next)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

NodeJs 相关文章推荐
nodejs的10个性能优化技巧
Jul 15 NodeJs
Nodejs为什么选择javascript为载体语言
Jan 13 NodeJs
windows下安装nodejs及框架express
Aug 07 NodeJs
NodeJS实现阿里大鱼短信通知发送
Jan 17 NodeJs
nodejs入门教程六:express模块用法示例
Apr 24 NodeJs
Nodejs读取文件时相对路径的正确写法(使用fs模块)
Apr 27 NodeJs
nodejs中解决异步嵌套循环和循环嵌套异步的问题
Jul 12 NodeJs
nodejs密码加密中生成随机数的实例代码
Jul 17 NodeJs
nodejs简单访问及操作mysql数据库的方法示例
Mar 15 NodeJs
详解nodejs 开发企业微信第三方应用入门教程
Mar 12 NodeJs
NodeJS配置CORS实现过程详解
Dec 02 NodeJs
NodeJs使用webpack打包项目的方法详解
Feb 28 NodeJs
详解redis在nodejs中的应用
May 02 #NodeJs
nodejs读取并去重excel文件
Apr 22 #NodeJs
nodeJS模块简单用法示例
Apr 21 #NodeJs
NodeJS安装图文教程
Apr 19 #NodeJs
关于Mac下安装nodejs、npm和cnpm的教程
Apr 11 #NodeJs
详解nodejs通过响应回写的方式渲染页面资源
Apr 07 #NodeJs
原生nodejs使用websocket代码分享
Apr 07 #NodeJs
You might like
php-cli简介(不会Shell语言一样用Shell)
2013/06/03 PHP
php实现学生管理系统
2020/03/21 PHP
PDO::getAvailableDrivers讲解
2019/01/28 PHP
js精度溢出解决方案
2012/12/02 Javascript
UpdatePanel和Jquery冲突的解决方法
2013/04/01 Javascript
js jq 单击和双击区分示例介绍
2013/11/05 Javascript
JS+CSS实现Li列表隔行换色效果的方法
2015/02/16 Javascript
jQuery实现转动随机数抽奖效果的方法
2015/05/21 Javascript
jQuery实现多级下拉菜单jDropMenu的方法
2015/08/28 Javascript
使用node+vue.js实现SPA应用
2016/01/28 Javascript
自己封装的一个简单的倒计时功能实例
2016/11/23 Javascript
javascript表单正则应用
2017/02/04 Javascript
Ext JS 实现建议词模糊动态搜索功能
2017/05/13 Javascript
vue按需引入element Transfer 穿梭框
2017/09/30 Javascript
web3.js增加eth.getRawTransactionByHash(txhash)方法步骤
2018/03/15 Javascript
layui使用form表单实现post请求页面跳转的方法
2019/09/14 Javascript
Vue实现导航栏的显示开关控制
2019/11/01 Javascript
vue+koa2搭建mock数据环境的详细教程
2020/05/18 Javascript
Vuex实现购物车小功能
2020/08/17 Javascript
[03:21]【TI9纪实】Old Boys
2019/08/23 DOTA
[46:42]DOTA2-DPC中国联赛正赛 Aster vs Magma BO3 第二场 3月5日
2021/03/11 DOTA
python实现数值积分的Simpson方法实例分析
2015/06/05 Python
Python中使用多进程来实现并行处理的方法小结
2017/08/09 Python
详解appium+python 启动一个app步骤
2017/12/20 Python
python3中numpy函数tile的用法详解
2019/12/04 Python
python+adb+monkey实现Rom稳定性测试详解
2020/04/23 Python
TensorFlow实现模型断点训练,checkpoint模型载入方式
2020/05/26 Python
加拿大最大的五金、家居装修和园艺产品商店:RONA
2017/01/27 全球购物
护理专业毕业生自我鉴定
2013/10/08 职场文书
商场消防演习方案
2014/02/12 职场文书
基层党员公开承诺书
2014/05/29 职场文书
邀请函模板
2015/02/02 职场文书
2019大学生社会实践报告汇总
2019/08/16 职场文书
python - asyncio异步编程
2021/04/06 Python
十大经典日本动漫排行榜 海贼王第三,犬夜叉仅第八
2022/03/18 日漫
改造DE1103三步曲
2022/04/07 无线电