Logging in express js to a output file?

后端 未结 7 1005
醉话见心
醉话见心 2020-12-12 23:26

What is best way to log my express js webserver? The inbuilt express.logger() just displays logs on screen. Can I also log them into a file in /log folder? Also the current

相关标签:
7条回答
  • 2020-12-13 00:04

    you should try cluster http://learnboost.github.com/cluster/ for Node. Use express to build the app, while the cluster take over the rest tasks including logging.

    1. app.use(express.logger()); // in your express apps, ex: app.js
    2. cluster.use(cluster.logger('logs')) ; // in your cluster server, ex: server.js
    0 讨论(0)
  • 2020-12-13 00:05

    winston is kinda silly, multi-transport logging == tee(1), or just tail the file and transfer the data off, easy as pie

    0 讨论(0)
  • 2020-12-13 00:16

    Look at the connect middleware that express extends. The express.logger() is the same as the connect.logger():

    http://expressjs.com/api.html#middleware

    http://www.senchalabs.org/connect/logger.html

    The logger has a stream option that can be set where you want the output to go. By default it sends it to stdout. Also you can specify the log format you want to use.

    0 讨论(0)
  • 2020-12-13 00:16

    You should try winston

    var logger = new (winston.Logger)({
      transports: [
        new (winston.transports.Console)(),
        new (winston.transports.File)({ filename: 'somefile.log' })
      ]
    });
    
    0 讨论(0)
  • 2020-12-13 00:21

    To send the express or connect logs to a file use Node's writeStream. For example to send the express logs to ./myLogFile.log :

    open the stream to your file in append mode with :

    var logFile = fs.createWriteStream('./myLogFile.log', {flags: 'a'}); //use {flags: 'w'} to open in write mode
    

    then, in your express config use :

    app.use(express.logger({stream: logFile}));
    

    should also work for connect.logger.

    0 讨论(0)
  • 2020-12-13 00:21

    For HTTP request logging: https://github.com/expressjs/morgan#write-logs-to-a-file

    var express = require('express')
    var fs = require('fs')
    var morgan = require('morgan')
    
    var app = express()
    
    // create a write stream (in append mode)
    var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
    
    // setup the logger
    app.use(morgan('combined', {stream: accessLogStream}))
    
    app.get('/', function (req, res) {
      res.send('hello, world!')
    })
    
    0 讨论(0)
提交回复
热议问题