Skip to content

Instantly share code, notes, and snippets.

@hbarcelos

hbarcelos/logger.js

Last active Aug 25, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.