將 Express 日誌寫入旋轉日誌檔案

首先,在專案中安裝 fsfile-stream-rotatorpath

npm install --save fs file-stream-rotator path

將以下程式碼新增到 app.js 檔案中:

var FileStreamRotator = require('file-stream-rotator')
var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

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 = FileStreamRotator.getStream({
  date_format: 'YYYYMMDD',
  filename: path.join(logDirectory, 'access-%DATE%.log'),
  frequency: 'daily',
  verbose: false
})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

現在,當你訪問你的網站時,你將看到建立了 log 目錄,並在你的日誌目錄中建立了名稱格式為 access-%DATE%.log 的日誌檔案