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. Android webView输出自定义网页

    这次来使用webview输出网页型数据.因为这样的数据好使用富文本编辑器,有各种各样的拓展. 上代码: package controller.hzl.com.testcall; import andr ...

  2. Oracel扩展表空间

    --表空间查看 SELECT tbs, sum(totalM) as total, sum(usedM) as UserdM, sum(remainedM) as remainedM, as User ...

  3. JQuery Table 合并单元格-解决Bug版本

    网络中提供的方法是: <script type="text/javascript"> function _w_table_rowspan(_w_table_id, _w ...

  4. 百度网盘 http://pandownload.com/index.html

    https://github.com/high-speed-downloader/high-speed-downloader

  5. eclipse配置代码自动提示

    Eclipse默认只有"."之后才有代码提示. [windows-->preferences] 把这里的点改成[.abcdefghijklmnopqrstuvwxyzABCD ...

  6. 半个月使用rust语言的体验

    从第一次下载rust语言的编译器到今天刚好第14天. 简单说一下对这个语言的感觉吧. 一.性能 把以前用java写的一个中文地址切分的算法,用rust重新实现了一下(https://github.co ...

  7. minerd

    云服务器 ECS Linux 异常进程 minerd 导致系统 CPU 跑满 问题现象 云服务器 ECS Linux 服务器 CPU 跑满,或者使用服务器越来越慢. 问题原因 使用 top 命令看到有 ...

  8. [hadoop读书笔记]译者序

    一.并行数据库系统 新一代高性能的数据库系统,是在MPP和集群并行计算环境的基础上建立的数据库系统. MPP:大规模并行处理计算机:Massive Parallel Processor.指的是一种处理 ...

  9. OSPF的特征、术语、包类型、邻居关系的建立、RID的选择、DR和BDR的选举、度量值的计算、默认路由、验证

    链路状态路由协议OSPF的特征.术语.包类型.邻居关系的建立.RID的选择.DR和BDR的选举.度量值的计算.默认路由.验证等. 文章目录 [*1*].链路状态路由协议概述 工作过程 优缺点 [*2* ...

  10. 启动LINUX系统后,进入图形化界面的命令

    1.进入xWindow的命令 $startx回车 或者修改/etc/inittab文件 cd /etc vi inittab 寻找: id:3:initdefault: 改为: id:5:initde ...