0
votes

I need to collect the user access log in the application, mainly the name and version of the browser he is using. However, morgan is bringing many details that I don't need, can you help me?

Currently:

Firefox

  • ::1 - OPTIONS - /signin - 204 - 0 - 0.126 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0 -

Chrome

  • ::1 - POST - /signin - 200 - 545 - 106.758 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

  • ::1 - OPTIONS - /signin - 204 - 0 - 0.163 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

Expected:

Firefox

Chrome

My code:

app.use((req,res,next) => {
    const logger = morgan(function (tokens, req, res) {     
        return [
            tokens['remote-addr'](req, res), '-',
            tokens.method(req, res), '-',
            tokens.url(req, res), '-',
            tokens.status(req, res), '-',
            tokens.res(req, res, 'content-length'), '-',
            tokens['response-time'](req, res), 'ms',
            tokens.referrer(req, res), '-',
            tokens['user-agent'](req, res), '-',
            ].join(' ')
        })
    logger(req,res,next)
})
2
We need more information if you want a regex solution for this. More than 2 example strings would be ideal.emsimpson92
@emsimpson92 update!rufus05
this is close but I still need a bit more information to fine tune it. Looking at your 2nd example for chrome, it lists both chrome and safari. How do you determine which they are using?emsimpson92
He's using chrome, I don't know why he identified safari ...rufus05

2 Answers

0
votes

var result = accessLogEntry.replace(/(?<=auth\s-\s).*(?=(?:Firefox|Chrome)\/[\d\.]+)/g, "");

This takes care of most of your problem. In your 2nd chrome example it will leave both the Chrome and Safari versions listed. You'll need to determine which one is the correct browser. This will trim out all the garbage in the middle of the log entry.

Demo

0
votes

I'm use a component called: app.use(require('express-useragent').express())

const navigator = req.useragent.browser