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. nginx封ip,禁用IP段的设置说明

    nginx的ngx_http_access_module 模块可以封配置内的ip或者ip段,语法如下: deny IP; deny subnet; allow IP; allow subnet; # ...

  2. 为什么hash作为内存使用的经典数据结构?

    听到这样说法:hash是内存中使用的经典数据结构.内存是典型的随机访问设备. 为什么hash这种数据结构很适合内存使用呢?如何理解内存是随机访问设备呢? 因为我想知其所以然,如何理解背后的原因,我花费 ...

  3. JAXP操作xml

    DOM对象详解1.基本的DOM对象 DOM的基本对象有5个:Document,Node,NodeList,Element和Attr.下面就这些对象的功能和实现的方法作一个大致的介绍. Document ...

  4. hbase源码系列(十二)Get、Scan在服务端是如何处理?

    继上一篇讲了Put和Delete之后,这一篇我们讲Get和Scan, 因为我发现这两个操作几乎是一样的过程,就像之前的Put和Delete一样,上一篇我本来只打算写Put的,结果发现Delete也可以 ...

  5. Web API(七):Basic基础认证

    1.WebApi中为什么需要身份认证 我们在使用WebApi的时候,都是通过URL去获取数据.也就是说,任何人只要知道了URL地址,就能随意的访问后台的服务接口,就可以访问或者修改数据库数据了,这样就 ...

  6. linux 木马清理过程

    服务器出现异常,完全无法访问,ssh登陆都极其缓慢 解决过程 top 查看系统状态,发现 load average 平均负载值非常高,再看排名第一的进程,是一个不认识的进程名:minerd 感觉是被入 ...

  7. nodejs应用在linux服务器中的部署

    1.(可选)添加用户: addgroup wmui添加用户组useradd -d /home/wmui -s /bin/bash -m wmui创建wmui用户passwd wmui设置密码,如果忘记 ...

  8. 【转】使用Maven的一些小建议,希望你能喜欢

    搭建私有仓库 Maven的仓库是用来存放Maven工程依赖的包的(通常为jar和pom,war包也可以依赖,在一些很复杂的项目中才能用到).仓库分为三种:中央仓库.第三方仓库.本地仓库. 中央仓库 由 ...

  9. linux刻录iso到u盘

    需要的工具:Linux系统.U盘.ISO镜像文件.首先在Linux系统中打开终端,使用dd命令,格式如下:sudo dd if=xxx.iso of=/dev/sdb命令中xxx.iso是你的ISO镜 ...

  10. C语言课程设计-保安值班系统支持任意输入保安值班时间

    //.cpp : Defines the entry point for the console application. // #include "string.h" #incl ...