I have an Express application that I would like to add logging to. I installed Morgan and set up the middleware in the file which manages my API calls:
/src/api/calls.js
the morgan middleware is set up to send the logging results to a file: errors.txt
var express = require('express'),
app = express(),
dbConfig = require('../config/db.config'),
connectToMongo = require('./db.js'),
bodyParser = require("body-parser"),
ObjectId = require('mongodb').ObjectID,
morgan = require('morgan'),
fs = require('fs'),
Sb;
//middleware
var accessLogStream = fs.createWriteStream('../sample/errors.txt', {flags: 'a'})
app.use(morgan('combined', {stream: accessLogStream}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
module.exports = function apiRoutes(app) {
app.get("/v1/api/sample/:call", function(req, res, next) {
//route db calls and code here
});
}
/app.js
the api routes are required into the app.js file and the apiRoutes function is called:
var express = require('express');
var app = express();
var config = require('./src/config/server.config');
//api and server
var http = require('http');
var server = new http.Server(app);
//load the api calls for the server
var apiRoutes = require('./src/api/calls.js');
apiRoutes(app);
the problem is - I'm not getting any logging data written into my errors.txt file or even in the console when I change the code to simply STDOUT. What am I missing here?
I figured it out- the logging code needed to be located in the app.js file, not in the file that holds the api calls. I knew the logging code needed to be the first piece of middleware, but I didn't realize it needed to be right after the new instance of the server is instantiated.
var express = require('express'),
app = express(),
config = require('./src/config/server.config'),
morgan = require('morgan'),
fs = require('fs'),
//api and server
http = require('http'),
server = new http.Server(app);
//set up the logger
var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})
app.use(morgan('combined', {"stream": accessLogStream}));
//load the api calls for the server
var apiRoutes = require('./src/api/calls.js');
apiRoutes(app);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With