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实用示例 缩址还原
Dec 28 NodeJs
NodeJS中Buffer模块详解
Jan 07 NodeJs
NodeJS和BootStrap分页效果的实现代码
Nov 07 NodeJs
浅谈Nodejs中的作用域问题
Dec 26 NodeJs
nodejs进阶(6)—连接MySQL数据库示例
Jan 07 NodeJs
nodejs搭建本地服务器并访问文件的方法
Mar 03 NodeJs
实例分析nodejs模块xml2js解析xml过程中遇到的坑
Mar 18 NodeJs
nodejs个人博客开发第六步 数据分页
Apr 12 NodeJs
NodeJS 将文件夹按照存放路径变成一个对应的JSON的方法
Oct 17 NodeJs
NodeJS读取分析Nginx错误日志的方法
May 14 NodeJs
nodejs 递归拷贝、读取目录下所有文件和目录
Jul 18 NodeJs
基于NodeJS开发钉钉回调接口实现AES-CBC加解密
Aug 20 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中的串行化变量和序列化对象
2006/09/05 PHP
提升PHP速度全攻略
2006/10/09 PHP
PHP函数microtime()用法与说明
2013/12/04 PHP
PHP基于imap获取邮件实例
2014/11/11 PHP
php生成圆角图片的方法
2015/04/07 PHP
php弹出提示框的是实例写法
2019/09/26 PHP
php中Swoole的热更新实现代码实例
2021/03/04 PHP
JS 无法通过W3C验证的处理方法
2010/03/09 Javascript
PHP 与 js的通信(via ajax,json)
2010/11/16 Javascript
3款实用的在线JS代码工具(国外)
2012/03/15 Javascript
javascript游戏开发之《三国志曹操传》零部件开发(一)让静态人物动起来
2013/01/23 Javascript
jQuery ajax请求返回list数据动态生成input标签,并把list数据赋值到input标签
2016/03/29 Javascript
jQuery添加和删除输入文本框标签代码
2016/05/20 Javascript
jQuery 选择符详细介绍及整理
2016/12/02 Javascript
svg动画之动态描边效果
2017/02/22 Javascript
JS使用正则表达式验证身份证号码
2017/06/23 Javascript
js将当前时间格式化为 年-月-日 时:分:秒的实现代码
2018/01/20 Javascript
小程序ios音频播放没声音问题的解决
2018/07/11 Javascript
apicloud拉起小程序并传递参数的方法示例
2018/11/21 Javascript
学习RxJS之JavaScript框架Cycle.js
2019/06/17 Javascript
js获取url页面id,也就是最后的数字文件名
2020/09/25 Javascript
在Vue里如何把网页的数据导出到Excel的方法
2020/09/30 Javascript
浅要分析Python程序与C程序的结合使用
2015/04/07 Python
介绍Python的@property装饰器的用法
2015/04/28 Python
Python中使用不同编码读写txt文件详解
2015/05/28 Python
巧用python和libnmapd,提取Nmap扫描结果
2016/08/23 Python
Python数据类型中的“冒号“[::]——分片与步长操作示例
2018/01/24 Python
python与c语言的语法有哪些不一样的
2020/09/13 Python
法国奢华女性时尚配饰网上商店:Monnier Frères
2016/08/27 全球购物
ABOUT YOU罗马尼亚:超过600个时尚品牌
2019/09/19 全球购物
简单说下OSPF的操作过程
2014/08/13 面试题
金融事务专业求职信
2014/04/25 职场文书
中秋晚会策划方案
2014/06/12 职场文书
2015年劳动部工作总结
2015/05/23 职场文书
C站最全Python标准库总结,你想要的都在这里
2021/07/03 Python
Golang 并发下的问题定位及解决方案
2022/03/16 Golang