0.1.8 • Published 4 years ago

mira-logger-js v0.1.8

Weekly downloads
70
License
-
Repository
-
Last release
4 years ago

mira-logger-js

An opinionated logging client for Node and the browser.

Usage

Initializing the client

const { MiraLogger } = require('mira-logger-js');

const logger = new MiraLogger({
  token: env.LOGGLY_CUSTOMER_TOKEN,
  environment: env.ENVIRONMENT,
  revision: env.REVISION,
  service: 'my-service',
});

See MiraLoggerOptions for the full set of options.

Log levels

logger.debug('debug message');
logger.info('info message');
logger.warn('warning message');
logger.error('error message');
logger.error(new Error('error message'));

// Send logs.
await logger.flush();

Setting context (optional)

Set the context to send with each subsequent log.

logger.setContext({ requestId: 'some-uuid' });

...

// Context passed in with an individual log is merged in with
// the default context set with `setContext`.
logger.info('info message', { statusCode: 200 });

// Logs [{ message: 'info message', requestId: 'some-uuid', statusCode: 200 }]
await logger.flush();

See Context for the full set of options.

Wrapping functions

Wrap a function with logger.wrap to automatically log errors and flush on return. Works with async functions too.

logger.wrap(async event => {
  // Thrown errors are automatically logged.
  throw Error('Oops!');

  // logger.flush() is called when this function returns;
  const data = await doStuff();
  return data;
});

Examples

Http Errors

class HttpError extends Error {
  constructor(code, message) {
    super(message);
    this.name = 'HttpError';
    // statusCode will automatically be logged.
    this.statusCode = code;
  }
}

const res = await fetch('https://example.com');

if (!res.ok) {
  logger.error(new HttpError(res.status, res.statusText));
}

Lambda Scheduled Event

const logger = new MiraLogger({
  token: env.LOGGLY_CUSTOMER_TOKEN,
  environment: env.ENVIRONMENT,
  service: 'my-service',
  // We manually flush at the end of the lambda so there's not
  // much point in keeping auto flushing enabled.
  enableAutoFlush: false
});

module.exports.handler = logger.wrap(async event => {
  logger.setContext({
    requestId: event.id,
    source: event.resources.join(','),
  });

  logger.info('Doing stuff...');

  const res = await fetch('https://example.com');
  if (!res.ok) {
    throw new Error(`Failed to fetch: ${res.status} | ${res.statusText}`);
  }

  logger.info('Done doing stuff.');

  ...

  // logger will flush after returning.
  return data
})

Publishing to NPM

Publishing is currently manual. Grab the NPM login from 1password.

  1. Bump the version in package.json.
  2. Run yarn deploy.
  3. Commit with the version name and push (ie. git commit -m "v0.1.5")
0.1.8

4 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago