4lessandrodev/ts-logs

Bind log to request

4lessandrodev opened this issue · 1 comments

Create middleware to bind log instance on request

// bind Global log to request
app.use((req, res, next) => {
    const name = req?.originalUrl?.replace(/\//, '') ?? 'index';
    const origin = req?.protocol + '://' + req?.headers['host'] + req?.originalUrl;
    let ip = req?.ip ?? req?.connection?.remoteAddress ?? req.headers?.['x-forwarded-for'];
    ip = ip?.replace(/[:]|[\s]|[f]/g, '');
    if (ip === '1') ip = '127.0.0.1';
    const uid = req.headers?.['uid'] as string ??  req.body?.["id"];
    req.log = Log.init({ name, uid, ip, origin });
    next();
});

And check on stackLog if exists log on request to use it

Bind

You also may use bind middleware to apply a log instance to request

import express from 'express';
import { bindLog } from 'ts-logs';

const app = express();
app.use(express.json());

// on top of routes you can bind a log instance
app.use(bindLog());

app.get("/log", (req: Request, res: Response) => {

    // you can do any with log instance
    req.log.addStep( /* any step */ );
    req.log.print(); // show steps on terminal

    res.status(200).json(req.log);
});

// ...

app.use(routes);