Skip to content

Instantly share code, notes, and snippets.

@hbarcelos
Last active August 25, 2018 19:09
Show Gist options
  • Save hbarcelos/62c2e8bf5dfb20806204eef4303d1e59 to your computer and use it in GitHub Desktop.
Save hbarcelos/62c2e8bf5dfb20806204eef4303d1e59 to your computer and use it in GitHub Desktop.
Contextual Logger - Initial Implementation
const pino = require('pino');
function createLogger(opts, destination) {
return pino(opts, destination);
}
module.exports = createLogger;
const test = require('ava');
const parseJSONStream = require('./utils/parse-json-stream');
const streamToGenerator = require('./utils/stream-to-generator');
const createLogger = require('./logger');
async function testMethod(t, input = {}, expected = {}) {
const { method } = input;
const { level } = expected;
const stream = parseJSONStream();
const logger = createLogger({ level: 'trace' }, stream);
const gen = streamToGenerator(stream);
logger[method]('foo');
const data = await gen.next().value;
t.is(data.level, level);
}
const loggerMethodUseCases = [
{ input: { method: 'trace' }, expected: { level: 10 } },
{ input: { method: 'debug' }, expected: { level: 20 } },
{ input: { method: 'info' }, expected: { level: 30 } },
{ input: { method: 'warn' }, expected: { level: 40 } },
{ input: { method: 'error' }, expected: { level: 50 } },
{ input: { method: 'fatal' }, expected: { level: 60 } },
];
loggerMethodUseCases.forEach(({ input, expected }) => {
test(
`Logger methods: ${JSON.stringify(input)} - ${JSON.stringify(expected)}`,
testMethod,
input,
expected
);
});
const { Transform } = require('stream');
const parseJSONStream = () =>
new Transform({
objectMode: true,
transform(chunk, encoding, cb) {
try {
const data = JSON.parse(chunk.toString('utf8'));
return cb(null, data);
} catch (err) {
return cb(err);
}
},
});
module.exports = parseJSONStream;
function* streamToGenerator(stream) {
while (true) {
const res = yield Promise.race([
new Promise(resolve => stream.once('data', resolve)),
new Promise(resolve => stream.once('end', resolve)),
new Promise((resolve, reject) => stream.once('end', reject)),
]);
if (!res) {
break;
}
}
}
module.exports = streamToGenerator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment