GithubHelp home page GithubHelp logo

Logging about gimbal HOT 2 CLOSED

moduscreateorg avatar moduscreateorg commented on June 14, 2024
Logging

from gimbal.

Comments (2)

mitchellsimoens avatar mitchellsimoens commented on June 14, 2024

Here is an example of a custom class:

/**
 * Abstracts out the logging. This is more for
 * indention support but also for better testability
 * so that `console.log` doesn't pollute the test
 * runner's output.
 */
class Logger {
  /**
   * @property {Mixed} [logger=console]
   * The logger to use. For testing, this
   * can be set to a stub.
   */
  get logger () {
    return this._logger || console
  }

  set logger (logger) {
    this._logger = logger
  }

  /**
   * Indent subsequent logs to show grouping.
   *
   * @param {Number} [num=2]
   * The number of spaces to indent. Can pass
   * a negative number to undo indention.
   */
  indent (num = 2) {
    let level = (this.indentLevel || 0) + num

    if (level < 0) {
      level = 0
    }

    this.indentLevel = level
  }

  /**
   * @private
   * Log out a message. Can pass a variable number
   * of arguments like you can with `console.log`.
   * This will handle the indention also.
   *
   * @param {Mixed...} args
   */
  log (...args) {
    const indention = new Array(this.indentLevel || 0)
      .fill(' ')
      .join('')

    const parsed = args
      .map(arg => {
        if (arg instanceof Error) {
          // we need to split the callstack by
          // newline so we can add the indention
          // to each line
          return arg
            .stack
            .split(/\n/)
            .map(line => `${indention}${line}`)
            .join('\n')
        } else if (arg && arg.toString) {
          return arg.toString()
        } else {
          return arg
        }
      })
      .join(' ')

    this.logger.log(`${indention}${parsed}`)
  }

  /**
   * Start a log group. This will log the arguments
   * passed and then increate the indention for the
   * subsequent logs.
   *
   * @param {Mixed...} args
   */
  group (...args) {
    if (args.length) {
      this.log(...args)
    }

    this.indent()
  }

  /**
   * End a log group. This will decrease the indention
   * one level.
   */
  groupEnd () {
    this.indent(-2)
  }
}

const instance = new Logger()

module.exports = instance

This class supports indentions via grouping (or manual indenting) but doesn't support named output or log levels. It could be modified to support that easily.

Here is another that uses Bunyan that can optionally stream to the console and newrelic:

import bunyan, { Stream } from 'bunyan';
import { EventEmitter } from 'events';
import { getEnv } from './constants';

// more on the bunyan levels and the number values:
// https://www.npmjs.com/package/bunyan#levels
export const getLoggerLevel = (): number => {
    const level = process.env.LOG_LEVEL;

    if (level && level.match(/^\d+$/)) {
        // allows to pass in the number value
        // e.g. 40 (for warn level)
        return parseInt(level, 10);
    }

    // for dev, default to the lowest level
    // else default to info level
    return getEnv('dev') ? 10 : 30;
};

export const getExplicitErrorLogLevel = (): number => {
    return 50;
};

class NewrelicStream extends EventEmitter {
    public write({ err, ...options }: any): void {
        const newrelic = require('newrelic');

        if (
            typeof err === 'object' &&
            err.hasOwnProperty('stack') &&
            err.hasOwnProperty('message') &&
            err.hasOwnProperty('name')
        ) {
            const {
                stack,
                message,
                name,
                ...errRest
            } = err;

            const customParameters = { ...options, ...errRest };

            newrelic.noticeError(err, customParameters);
        } else {
            newrelic.noticeError(err, options);
        }
    }
}

export const newrelicStream = NewrelicStream;

const bunyanStreams = process.env.NEWRELIC_ENABLE
    ? [
        {
            level: getLoggerLevel(),
            name: 'stderr',
            stream: process.stderr
        },
        {
            level: getExplicitErrorLogLevel(),
            name: 'NewRelicErrorStream',
            stream: new NewrelicStream(),
            type: 'raw'
        }
    ] as Stream[]
    : undefined;

export default bunyan.createLogger({
    level: getLoggerLevel(),
    name: 'Foo',
    serializers: {
        err: bunyan.stdSerializers.err
    },
    streams: bunyanStreams
});

from gimbal.

slemmon avatar slemmon commented on June 14, 2024

#65

from gimbal.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.