I have an Express project and I have it set up to log to a file:
logPath = '/mnt/log/api.log'
logfile = fs.createWriteStream logPath, {flags: 'a'}
loggingOptions =
format: 'default'
stream: logfile
app.use express.logger(loggingOptions)
This works for logging requests, but I want to add my own messages to the log, but I can't figure out how. console.log
isn't redirected, and there doesn't seem to be a "logger" object created that I can write to.
So is my only option to pass around a reference to the file stream and write to that?
I don't know how to do exactly what you are asking but this is what I do and so far it has worked well.
I configure the express logger (which is actually the connect logger by the way if you are looking for documentation) like shown below and all the log output goes to stdout. I can print to the same output with console.log("blah blah").
app.use(express.logger("default"));
On the production server I redirect all the output of node to to the log file.
This works well during development too because I run node in a shell window and can see all the same output. (Actually I use express.logger("dev") during development because the output is much cleaner for dev work.)
You could create your own logging middleware:
app.use (req, res, next) ->
logFile.write "anything you want"
next()
Define error-handling middleware like other middleware, except with four arguments instead of three, specifically with the signature (err, req, res, next)):
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500).send('Something broke!');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.