Attempting to change the format of morgan's logging through the application run time.
The value will change pending on some remote value in a database and I would like morgan's output to change as a result. ie. If in the database the value is 1 morgan's formatting is 'dev', if the value is 3 the formatting is 'combined'
I have the been using the following line to set up morgan with formatting:
app.use(morgan(get_verbose()))
.use ....
where get_verbose will correspond to the format options. However it is not giving the dynamic results I was wishing for - it's only setting the formatting once.
Am I going about this incorrectly or is morgan limited to only 1 format at run time?
One approach would be to create a middleware function that "wraps" the Morgan middleware:
var morganDev = mordan('dev');
var morganCombined = morgan('combined');
app.use(function(req, res, next) {
var value = /* get value somehow */
if (value === 1) {
morganDev(req, res, next);
} else if (value === 3) {
morganCombined(req, res, next);
}
});
Up front, you create one logger for each log format you would like, but don't attach either of them to the app. In their place, a custom function reads the value and chooses which logger should handle the processing for this request.
Safety update: There should be a catch-all else block to handle the case where value is neither 1 or 3. This block should call next() directly, otherwise the request handling will stall and never return a response to the client.
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