Node.js 模塊之 morgan中間件記錄日志


NodeJs中Express框架使用morgan中間件記錄日志

Express中的app.js文件已經默認引入了該中間件var logger = require('morgan');

使用app.use(logger('dev'));可以將請求信息打印在控制台,便於開發調試,但實際生產環境中,需要將日志記錄在log文件里,可以使用如下代碼

    var express = require('express'); var fs = require('fs'); var logger = require('morgan'); var app = express(); var accessLog = fs.createWriteStream('../access.log', {flags : 'a'}); var errorLog = fs.createWriteStream('../error.log', {flags : 'a'}); app.use(logger('dev'));     //打印到控制台 
    app.use(logger('combined', {stream : accessLog}));      //打印到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() }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM