惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 聂微东
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
C
Check Point Blog
M
MIT News - Artificial intelligence
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
DataBreaches.Net
大猫的无限游戏
大猫的无限游戏
D
Docker
Last Week in AI
Last Week in AI
IT之家
IT之家
F
Fortinet All Blogs
A
About on SuperTechFans
P
Proofpoint News Feed
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog RSS Feed
博客园_首页
月光博客
月光博客
博客园 - 司徒正美
Y
Y Combinator Blog

mafeifan 的编程技术分享

mafengwo-mp3-downloader | mafeifan 的编程技术分享 示例页面 | mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 查看 default namespace 下的 default service account名称 mafeifan 的编程技术分享 检查日志 | mafeifan 的编程技术分享 bridge fdb show dev flannel.1 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享 mafeifan 的编程技术分享
mafeifan 的编程技术分享
2026-01-16 · via mafeifan 的编程技术分享

记录请求参数和请求内容 ​

默认morgan没有提供记录请求参数和请求内容的方法, 但是他提供了扩展方法,如下:

morgan.token('requestParameters', function(req, res){
  return JSON.stringify(req.query) || '-';
});

morgan.token('requestBody', function(req, res){
  return JSON.stringify(req.body) || '-';
});

// create custom format,includes the custom token
morgan.format('live-api', ':method :url :status :requestParameters :requestBody');

app.use(morgan('live-api'));

输出日志到数据库或将日志作为参数发送到其他请求 ​

默认日志信息是输出到命令行窗口中,能否输出到文件或数据库中呢?答案是肯定的 定义morgan的options中有个stream配置项,我们可以利用他做文章。

const request = require('request')
const split = require('split')

// 将日志信息作为请求参数传给其他地址,比如 Elasticsearch 日志分析系统
let httpLogStream = split().on('data', function (line) {
  request({
    url: 'localhost://192.168.1.1:8080',
    method: 'POST',
    body: line
  })
  .on('response', function(response) {
    console.log(response.statusCode) // 200
  })
});

app.use(morgan('common', {
  stream: httpLogStream
}));


// 将日志写入数据库
// 带write方法的对象
let dbStream = {
  write: function(line){
    saveToDatabase(line);  // 伪代码,保存到数据库
  }
};

// 将 dbStream 作为 stream 配置项的值
app.use(morgan('short', {stream: dbStream}));