将 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 的日志文件