分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

Node.js 模块之 morgan中间件记录日志

发布时间:2023-09-06 01:24责任编辑:郭大石关键词:jsNode

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 loggerapp.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 existsfs.existsSync(logDirectory) || fs.mkdirSync(logDirectory) // create a rotating write streamvar accessLogStream = rfs(‘access.log‘, { ?interval: ‘1d‘, // rotate daily ?path: logDirectory}) // setup the loggerapp.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 consoleapp.use(morgan(‘dev‘, { ?skip: function (req, res) { return res.statusCode < 400 }})) // log all requests to access.logapp.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中间件记录日志

原文地址:http://www.cnblogs.com/jokerjason/p/7815040.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved