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 相关文章推荐
14款NodeJS Web框架推荐
Jul 11 NodeJs
Google官方支持的NodeJS访问API,提供后台登录授权
Jul 29 NodeJs
nodejs中简单实现Javascript Promise机制的实例
Dec 06 NodeJs
NodeJS制作爬虫全过程
Dec 22 NodeJs
NodeJS配置HTTPS服务实例分享
Feb 19 NodeJs
初识NodeJS服务端开发入门(Express+MySQL)
Apr 07 NodeJs
详解nodejs模板引擎制作
Jun 14 NodeJs
nodejs 图片预览和上传的示例代码
Sep 30 NodeJs
nodejs实现超简单生成二维码的方法
Mar 17 NodeJs
NodeJS搭建HTTP服务器的实现步骤
Oct 12 NodeJs
nodejs图片处理工具gm用法小结
Dec 12 NodeJs
nodejs log4js 使用详解
May 31 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实现可以设置中奖概率的抽奖程序代码分享
2014/01/19 PHP
CodeIgniter使用smtp服务发送html邮件的方法
2015/06/10 PHP
让你的网站可编辑的实现js代码
2009/10/19 Javascript
根据表格中的某一列进行排序的javascript代码
2013/11/29 Javascript
js中AppendChild与insertBefore的用法详细解析
2013/12/16 Javascript
jQuery学习笔记之 Ajax操作篇(二) - 数据传递
2014/06/23 Javascript
Node.js中安全调用系统命令的方法(避免注入安全漏洞)
2014/12/05 Javascript
AngularJS入门教程(一):静态模板
2014/12/06 Javascript
javascript中BOM基础知识总结
2017/02/14 Javascript
bootstrap select插件封装成Vue2.0组件
2017/04/17 Javascript
详解React Native开源时间日期选择器组件(react-native-datetime)
2017/09/13 Javascript
微信小程序倒计时功能实现代码
2017/11/09 Javascript
Vue.js表单标签中的单选按钮、复选按钮和下拉列表的取值问题
2017/11/22 Javascript
bootstrap中selectpicker下拉框使用方法实例
2018/03/22 Javascript
js中apply和Math.max()函数的问题及区别介绍
2018/03/27 Javascript
JavaScript继承与多继承实例分析
2018/05/26 Javascript
vue加载完成后的回调函数方法
2018/09/07 Javascript
解决vue无法设置滚动位置的问题
2018/10/07 Javascript
详解vue更改头像功能实现
2019/04/28 Javascript
vue+koa2实现session、token登陆状态验证的示例
2019/08/30 Javascript
jQuery操作选中select下拉框的值代码实例
2020/02/07 jQuery
Python脚本获取操作系统版本信息
2016/12/17 Python
Python扩展内置类型详解
2018/03/26 Python
使用pandas read_table读取csv文件的方法
2018/07/04 Python
基于Python 中函数的 收集参数 机制
2019/12/21 Python
英国最大的自有市场,比亚马逊便宜:Flubit
2019/03/19 全球购物
可持续未来的时尚基础:Alternative Apparel
2019/05/06 全球购物
德国咖啡批发商:Coffeefair
2019/08/26 全球购物
Why we need EJB
2016/10/20 面试题
会计工作岗位职责
2015/02/03 职场文书
2015年植树节活动总结
2015/02/06 职场文书
跟班学习心得体会(共6篇)
2016/01/23 职场文书
Oracle更换为MySQL遇到的问题及解决
2021/05/21 Oracle
MySQL基础快速入门知识总结(附思维导图)
2021/09/25 MySQL
vue中使用mockjs配置和使用方式
2022/04/06 Vue.js
MySQL8.0 Undo Tablespace管理详解
2022/06/16 MySQL