As part of the project I am currently working on we want to log our UI component errors as well. I developed this package as a base. It's a factory (basically, not sure if it's correctly a factory). There is one function exposed configure that takes the parameters that each service (of the project) needs to supply and returns a logger; an object with four functions - debug, info, warn and error.

I am not sure if this is the right way to do it in javascript. Or in general. Is this how a factory should look? I have seen some that expose a function rather than an object that has a function on it but in my mind these two seem equivalent.

import uuid from 'uuid/v4';
import post from './post';

function requiredParam(param) {
  const requiredParamError = new Error(`Required parameter, "${param}" is missing.`);
  // preserve original stack trace
  if (typeof Error.captureStackTrace === 'function') {
  throw requiredParamError;

const Logger = {
  configure: ({
    url = requiredParam('url'),
    service = requiredParam('service'),
    version = requiredParam('version'),
    apigeeClientId = requiredParam('apigeeClientId')
  }) => {
    const prepareForwardLogFunction = function prepareForwardLogFunction(logLevel) {
      return async function forwardLog(details, exception) {
        const payload = {
          loggername: 'UiLogger',
          serviceType: 'reactjs',
          level: logLevel,
          eventType: logLevel === 'error' ? 'Exception' : 'Trace',
          correlationId: uuid(),
          timestamp: new Date(),
          exception: exception !== undefined ? exception : null,
          request: global.window.location.href

        try {
          await post(url, payload, apigeeClientId);
        } catch (error) {
          console.warn('UI Logger failed:', { url, payload, error }); // eslint-disable-line no-console

    return {
      debug: prepareForwardLogFunction('debug'),
      info: prepareForwardLogFunction('info'),
      warn: prepareForwardLogFunction('warn'),
      error: prepareForwardLogFunction('error')

export default Logger;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.