Skip to content

Commit

Permalink
Export namespace and fix req-id for end log (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
Santiago Foster authored and picollomartin committed Jul 22, 2019
1 parent 45c1364 commit 8beb2ff
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
18 changes: 9 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ const logger = pino({
}
});

const ns = createNamespace(NAMESPACE);
const namespace = createNamespace(NAMESPACE);

const getRequestId = () => {
return ns ? ns.get('requestId') : null;
return namespace ? namespace.get('requestId') : null;
};

const setRequestId = (id = uuid()) => {
ns.set('requestId', id);
namespace.set('requestId', id);
return id;
}

Expand All @@ -42,24 +42,24 @@ const expressMiddleware = (req, res, next) => {
`Started ${method} ${url} with params: ${params}, query: ${query}, body: ${body}.`
);
const begin = Date.now();
const foo = (error, response) => {
const foo = namespace.bind((error, response) => {
const end = Date.now();
const responseTime = error ? '-' : end - begin;
const status = response.statusCode;
info(`Ended ${method} ${url} with status: ${status} in ${responseTime} ms`);
};
});
onFinished(res, foo);
next();
};

const expressRequestIdMiddleware = (req, res, next) => {
ns.bindEmitter(req);
ns.bindEmitter(res);
return ns.run(() => {
namespace.bindEmitter(req);
namespace.bindEmitter(res);
return namespace.run(() => {
const requestId = req.headers['x-request-id'] || uuid();
setRequestId(requestId);
next();
});
};

module.exports = { logger: { ...logger, info, error }, expressMiddleware, expressRequestIdMiddleware, getRequestId, setRequestId };
module.exports = { logger: { ...logger, info, error }, expressMiddleware, expressRequestIdMiddleware, getRequestId, setRequestId, namespace };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "express-wolox-logger",
"version": "0.0.2",
"version": "0.0.3",
"description": "ExpressJS Wolox Logger",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 8beb2ff

Please sign in to comment.