17.nodejs中koa2框架morgan写日志

const Koa = require('koa')

// session 有关模块
const session = require('koa-generic-session')
const redis = require('redis')
const RedisStore = require('koa-redis')
// 日志有关的模块
const morgan = require('koa-morgan')
const path = require('path')
const fs = require('fs')

const app = new Koa()

// 设置 session
app.keys = ['kaksk_12']
app.use(session({
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000
  },
  store: RedisStore({
    all: '127.0.0.1:6379'
  })
}))

// morgan 处理日志
const ENV = 'prd' //假设环境参数是prd
if (ENV === 'dev') {
  app.use(morgan('dev'))  // 测试环境,打印在控制台
} else {  // 线上环境,写入文件
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const logStream = fs.createWriteStream(logFileName, { flags: 'a' })
  app.use(morgan('combined', {
    stream: logStream
  }))
}


app.use(async (ctx, next) => {
  ctx.session.id = 3
  ctx.body = '测试session'
  await next()
})


app.listen(3000, () => {
  console.log(`the server is running on port 3000`)
})

在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页