Nodejs, Connection log

Asked

Viewed 61 times

0

I have a problem to create a LOG database of connections, I can get virtually all the data, but the most essential that would be the body of Response, is returning with undefined, someone would know how to take that amount

Follows code:

const log = require('../utils/log');

function criaLog(req, res){
    let now = new Date;
    let dados = `Dados da requisicao:
    IP: ${req.ip},
    Headers: ${JSON.stringify(req.headers)},
    Rota: ${req.route.path},
    Metodo: ${req.route.stack[0].method},
    Data/Hora: ${now.getUTCDate()}/${(now.getMonth() + 1)}/${now.getFullYear()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}
    Corpo: ${JSON.stringify(req.body)},
    Resultado Codigo: ${res.statusCode}, Mensagem: ${res.statusMessage},
    Corpo do Resultado: ${JSON.stringify(res.Body)}
    `;  
    log.escreveLog(dados);
}

2 answers

2

  • I could be wrong but the correct syntax is with the body in tiny: res.body
  • Check if you are sending the body through the res.send(req.body) to access through Sponse

0

Insert an after event into your server file, within this method pass the desired parameters.

this.application.on('after', (req, res, next, err) => {

    let logger = {};
    let now = new Date();

    logger.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    logger.date = `[${req.date()}]`;

    logger.dataPesquisa = now.getUTCDate().toString() + '-' + (now.getMonth() + 1).toString() + '-' + now.getFullYear().toString();

    logger.method = req.method.toUpperCase();

    logger.url = req.url;

    logger.httpv = req.httpVersion;

    logger.status = res.statusCode;

    logger.body_Request = JSON.stringify(req.body);

    logger.body_Response = JSON.stringify(res._body);

    logger.headers = JSON.stringify(req.headers);
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.