nodejs 日志模塊winston的使用方法
winston 日志模塊
在使用 nodejs winston 模塊中,加上相關(guān)的兩個模塊,事倍功半。
- express-winston
- winston-daily-rotate-file
express-winston
是 express-winston 的 winston 的增加版, 是作為 express 的中間件來打印日志,不僅有請求頭信息,并且有響應(yīng)時間。
作為中間件, 為什么會有響應(yīng)時間呢? 因為 express-winston 改寫了 express 的 res.end 辦法, 是請求結(jié)束后再打的日志。
代碼片段
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 有滾動日志的能力。
結(jié)合使用
我們來一個需求: 如何讓 express-winston 打印日志的時候,也打印出接口 /api 的請求參數(shù)和響應(yīng)數(shù)據(jù)?
- 該日志中間件應(yīng)該在調(diào)用鏈 api 后面, api/* 業(yè)務(wù)處理之前。 like: app.use('/api', apiRequestLogger, apiHandler)
- 要獲取到響應(yīng)數(shù)據(jù), 就要在業(yè)務(wù)處理完后 send 出來后才能捕獲到,express 所有的請求響應(yīng)最后都是走 res.send 我們可以從這里入手捕獲響應(yīng)數(shù)據(jù)
代碼如下
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)
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Nodejs Express 通過log4js寫日志到Logstash(ELK)
- 使用koa-log4管理nodeJs日志筆記的使用方法
- NodeJS讀取分析Nginx錯誤日志的方法
- Node.js中使用Log.io在瀏覽器中實時監(jiān)控日志(等同tail -f命令)
- Node.js 日志處理模塊log4js
- Node.js利用console輸出日志文件的方法示例
- Node.js利用debug模塊打印出調(diào)試日志的方法
- Node.js和MongoDB實現(xiàn)簡單日志分析系統(tǒng)
- Node.js log4js日志管理詳解
- node錯誤處理與日志記錄的實現(xiàn)
- nodejs實現(xiàn)日志讀取、日志查找及日志刷新的方法分析
相關(guān)文章
NestJS核心概念之Middleware中間件創(chuàng)建使用示例
這篇文章主要為大家介紹了NestJS核心概念之Middleware中間件創(chuàng)建使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
node.js中實現(xiàn)kindEditor圖片上傳功能的方法教程
最近在做一個類似于論壇的系統(tǒng),帖子需要進(jìn)行圖文并茂的顯示,所以用到了富文本編輯器:kindeditor,下面這篇文章主要給大家介紹了在node.js中實現(xiàn)kindEditor圖片上傳功能的方法教程,需要的朋友可以參考借鑒,下面來一起看看吧。2017-04-04
從零開始學(xué)習(xí)Node.js系列教程六:EventEmitter發(fā)送和接收事件的方法示例
這篇文章主要介紹了Node.js EventEmitter發(fā)送和接收事件的方法,結(jié)合實例形式分析了EventEmitter發(fā)送和接收事件的原理、實現(xiàn)方法與相關(guān)操作技巧,需要的朋友可以參考下2017-04-04
使用Node.js在深度學(xué)習(xí)中做圖片預(yù)處理的方法
這篇文章主要介紹了使用Node.js在深度學(xué)習(xí)中做圖片預(yù)處理的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

