NodeJs中Express框架使用morgan中间件记录日志

Express中的app.js文件已经默认引入了该中间件var logger = require('morgan');

使用app.use(logger('dev'));可以将请求信息打印在控制台,便于开发调试,但实际生产环境中,需要将日志记录在log文件里,可以使用如下代码

这样便可以将请求信息打印在根目录下的access.log文件中(注意文件路径别填错,并不会自动创建该文件)

示例:

express/connect

Simple app that will log all request in the Apache combined format to STDOUTq

Log出所有Apache请求(结合STTDOUT格式)

var express = require('express')
var morgan = require('morgan') var app = express() app.use(morgan('combined')) app.get('/', function (req, res) {
res.send('hello, world!')
})

vanilla http server

Simple app that will log all request in the Apache combined format to STDOUT

var finalhandler = require('finalhandler')
var http = require('http')
var morgan = require('morgan') // create "middleware"
var logger = morgan('combined') http.createServer(function (req, res) {
var done = finalhandler(req, res)
logger(req, res, function (err) {
if (err) return done(err) // respond to request
res.setHeader('content-type', 'text/plain')
res.end('hello, world!')
})
})

write logs to a file

single file

Simple app that will log all requests in the Apache combined format to the file access.log.

Log列出所有Apache请求到access.log中

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path') var app = express() // create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}) // setup the logger
app.use(morgan('combined', {stream: accessLogStream})) app.get('/', function (req, res) {
res.send('hello, world!')
})

log file rotation

Simple app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.

每天将所有Apache请求记录到log中

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var rfs = require('rotating-file-stream') var app = express()
var logDirectory = path.join(__dirname, 'log') // ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory) // create a rotating write stream
var accessLogStream = rfs('access.log', {
interval: '1d', // rotate daily
path: logDirectory
}) // setup the logger
app.use(morgan('combined', {stream: accessLogStream})) app.get('/', function (req, res) {
res.send('hello, world!')
})

split / dual logging

The morgan middleware can be used as many times as needed, enabling combinations like:

  • Log entry on request and one on response
  • Log all requests to file, but errors to console
  • ... and more!

Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:

Log所有Apache请求,错误Log到console中

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path') var app = express() // log only 4xx and 5xx responses to console
app.use(morgan('dev', {
skip: function (req, res) { return res.statusCode < 400 }
})) // log all requests to access.log
app.use(morgan('common', {
stream: fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'})
})) app.get('/', function (req, res) {
res.send('hello, world!')
})

use custom token formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

ID Token格式

var express = require('express')
var morgan = require('morgan')
var uuid = require('node-uuid') morgan.token('id', function getId (req) {
return req.id
}) var app = express() app.use(assignId)
app.use(morgan(':id :method :url :response-time')) app.get('/', function (req, res) {
res.send('hello, world!')
}) function assignId (req, res, next) {
req.id = uuid.v4()
next()
}

Node.js 模块之 morgan中间件记录日志的更多相关文章

  1. Node.js模块

    每一个Node.js都是一个Node.js模块,包括JavaScript文件(.js).JSON文本文件(.json)和二进制模块文件(.node). mymodul.js function Hell ...

  2. 如何发布一个自定义Node.js模块到NPM(详细步骤)

    咱们闲话不多说,直接开始! 由于我从没有使用过MAC,所以我不保证本文中介绍的操作与MAC一致. 文章开始我先假定各位已经在window全局安装了Node.js,下面开始进行详细步骤介绍: 本文本着, ...

  3. 编写原生Node.js模块

    导语:当Javascript的性能需要优化,或者需要增强Javascript能力的时候,就需要依赖native模块来实现了. 应用场景 日常工作中,我们经常需要将原生的Node.js模块做为依赖并在项 ...

  4. 编写原生的Node.js模块

    导语:当Javascript的性能遭遇瓶颈,或者需要增强Javascript能力的时候,就需要依赖native模块来实现了. 应用场景 日常工作中,我们经常需要将原生的Node.js模块做为依赖并在项 ...

  5. Node.js模块封装及使用

    Node.js中也有一些功能的封装,类似C#的类库,封装成模块这样方便使用,安装之后用require()就能引入调用. 一.Node.js模块封装 1.创建一个名为censorify的文件夹 2.在c ...

  6. 10、Node.js模块系统

    ##################################################################################介绍Node.js模块系统为了让No ...

  7. 如何发布一个自定义Node.js模块到NPM(详细步骤,附Git使用方法)

    咱们闲话不多说,直接开始! 由于我从没有使用过MAC,所以我不保证本文中介绍的操作与MAC一致. 文章开始我先假定各位已经在window全局安装了Node.js,下面开始进行详细步骤介绍: 本文本着, ...

  8. node.js 模块和其下载资源的镜像设置

    以前安装 electron 时总是失败,然后就在淘宝镜像上下载好相应版本的文件放到用户目录来解决问题. 后来研究发现 npm 不仅可以设置 node.js 模块仓库的代理, 同样可以设置像 elect ...

  9. Developer - 如何自我保证Node.js模块质量

    组里正在做SaaS产品,其中一些模块(Module)是Node.js实现,这里我们主要使用Node.js实现Web Server来提供服务. 在做SaaS项目之前,组里的开发模式是传统的Deverlo ...

随机推荐

  1. WebSphere ILOG JRules 规则引擎运行模式简介

    WebSphere ILOG JRules 规则引擎运行模式简介 引言 作为 JRules 的核心组件,规则引擎决定了在规则集的执行过程中,哪些业务规则会被执行,以及以何种顺序执行.理解并合理选择规则 ...

  2. TP v5中Url Compat模式

    compatible 对于配置pathinfo的支持,在Nginx作服务器.无数种系统要同时运行的环境,实在是一项很累赘的事情,而又不想很low的多个参数(像m.c.a)构造路由参数,我需要那种不必强 ...

  3. Spring WebSocket初探1 (Spring WebSocket入门教程)<转>

    See more: Spring WebSocket reference整个例子属于WiseMenuFrameWork的一部分,可以将整个项目Clone下来,如果朋友们有需求,我可以整理一个独立的de ...

  4. QQ小薇机器人

    https://github.com/b3log/xiaov XiaoV(小薇)是一个用 Java 写的 QQ 聊天机器人 Web 服务,可以用于社群互动: 监听多个 QQ 群消息,发现有“感兴趣”的 ...

  5. CentOS服务器简单判断CC攻击的命令

    使用下面的命令,可以分析下是否在被CC攻击.   第一条命令: tcpdump -s0 -A -n -i any | grep -o -E '(GET|POST|HEAD) .*' 正常的输出结果类似 ...

  6. android开发(30) 使用WebView,点击网页中的链接建立QQ 临时会话 WPA

    在PC端,我们可以通过一个URL链接,点击后启动QQ,这是很好的用户跳转体验.很方便. 使用的链接如下: <a target="_blank" href="http ...

  7. Mongo的备份和恢复(mongodump 和mongorestore )

    http://www.runoob.com/mongodb/mongodb-mongodump-mongorestore.html --备份单个表mongodump -u superuser -p 1 ...

  8. webpack5--css 打包

    1.在 src 文件夹下面新建 css 文件夹,创建 common.css body{ background-color: #f2f2f2; } a{ color: #188eee; text-dec ...

  9. 【转】如果有人让你推荐Python技术书,请让他看这个列表

    入门级 <Head First Python>+ 入门级 + 微信49票 + 豆瓣评分 9.5 推荐语: 66:浅显易懂,编排的顺序特别,有大量插图.对话,不感觉枯燥 古心:通熟易懂,配有 ...

  10. MY_使用selenium自动登录126/163邮箱并发送邮件

    转自:https://www.cnblogs.com/yin-tao/p/7244082.html 我使用的是python2.7.13+selenium ps:几天之前,我曾多次尝试写这段代码,但是在 ...