expressjs / morgan

HTTP request logger middleware for node.js
MIT License
7.95k stars 536 forks source link

Use morgan as custom console logger #262

Closed loretoparisi closed 2 years ago

loretoparisi commented 2 years ago

I'm using morgan in my express app plus ecs-morgan-format to send logging to ElasticSearch Kibana (via FileSend):

const morgan = require('morgan');
const ecsFormat = require('@elastic/ecs-morgan-format');
self.app.use(morgan(ecsFormat({ format: 'combined' })));

This works ok. Now I'm using another logger in the server and the related SDKs, that writes to the console.log a string. Is it possible to use morgan as a writer in order to attach it to my custom logger as alternative to console.log even if I do not have a req and res objects to log?

In this way I would be able to use the ecs-morgan-format when writing to my custom logger.

dougwilson commented 2 years ago

Hi @loretoparisi , the purpose of morgan is to output logs of your http request/response activity to some output, like the default console.log. You can use the stream option of morgan to specify a stream to output your logs to, though. If your generic logging solution also provides a stream, then that would be the easiest method to output both to the same location. morgan itself is not a generic logging library for anything beyond its usage as a middleware.

loretoparisi commented 2 years ago

hey @dougwilson thank you! Are you then suggesting something like

class MyStream extends Writable {
    write(line) {
        console.log("Logger - ", line)
    }
}
let writer = new MyStream()
morgan.token("timed", myCustomFmtString)
app.use(morgan('timed', {
    stream: writer
}))

Assumed I have understood, if I then write to MyStream like

writer.write("hello world")

morgan will catch this write and send to stdout? Would I have then double logging?

Thank you!

dougwilson commented 2 years ago

Yea, that is the gist of it. Then you'll get morgan writing to your MyStream and if you then log to MyStream on other locations, you end up with everything getting output through that common medium. It will not result in double logging by morgan.