@procore/web-sdk-logging
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Web Platform Logging

A flexible logging solution for Procore front-end applications, providing a standardized interface and integration with various logging services.

Installation

You can install @procore/web-sdk-logging via yarn:

yarn add @procore/web-sdk-logging

Features

  • Initialize and manage logging with configurable options.
  • Provides a React context-based LoggerProvider for easy integration.
  • Hooks (useLogger) for seamless logging integration within React components.
  • Error handling and fallback mechanisms included.

Usage

Initialize Logger

To initialize the logger in a non-React environment, you can use the getLogger function directly. Here's an example:

import { getLogger, LoggerOptions } from '@procore/web-sdk-logging';

function initializeLogger() {
  const options: LoggerOptions = {
    level: 'debug',
    endpoint: 'https://api.sumologic.com/receiver/v1/http/<unique_id>',
    name: 'MyApp',
    category: 'ApplicationLogs',
  };

  try {
    const logger = getLogger(options);
    logger.info('Logger initialized.');
  } catch (error) {
    console.error('Failed to initialize logger:', error);
  }
}

initializeLogger();

Note: If the getLogger method cannot initialize the SumoLogic logger, it will initialize a console logger instead.

LoggerProvider

Wrap your application with LoggerProvider to manage the logger instance throughout your app:

import { LoggerProvider } from '@procore/web-sdk-logging';

function Index() {
  return (
    <LoggerProvider initialContext={initialContext}>
      <App />
    </LoggerProvider>
  );
}

Note: If the logger provider cannot initialize the SumoLogic logger, it will initialize and provide a console logger instead.

useLogger Hook

Use the useLogger hook in functional components to access the logger instance:

import { useLogger } from '@procore/web-sdk-logging';

function Component() {
  const logger = useLogger();

  React.useEffect(() => {
    if (logger) {
      logger.info('Component initialized.');
    }
  }, [logger]);


  return </div>;
}

Logging Methods

Use the logger instance to log messages with different severity levels:

if (logger) {
  logger.info('Informational message');
  logger.warn('Warning message');
  logger.error('Error message');
  logger.debug('Debug message');
}

Custom Backend Integration

Adding Custom Backends

You can extend the logging capabilities by adding custom backend implementations to getLogger. Here's an example of adding a custom backend:

import { getLogger, Backend } from '@procore/web-sdk-logging';
import { LoggerOptions } from '@procore/web-sdk-logging/types';

class CustomBackend implements Backend {
  async log(
    level: LogLevel,
    message: string,
    metadata: Record<string, unknown>
  ): Promise<void> {
    // Implement custom logging logic here
    console.log(`Custom logging ${level}: ${message}`, metadata);
  }
}

function initializeLoggerWithCustomBackend() {
  const options: LoggerOptions = {
    level: 'debug',
    endpoint: 'https://api.sumologic.com/receiver/v1/http/<unique_id>',
    name: 'MyApp',
    category: 'ApplicationLogs',
  };

  const customBackend = new CustomBackend();

  try {
    const logger = getLogger(options, [customBackend]);
    logger.debug('Logger initialized with custom backend.');
  } catch (error) {
    console.error('Failed to initialize logger:', error);
  }
}

In this example, CustomBackend implements the Backend interface from @procore/web-sdk-logging, allowing you to integrate your custom logging logic seamlessly into the logging framework provided by @procore/web-sdk-logging.

If you prefer using hooks (useLogger) or the LoggerProvider from our library, typically, you work with the default or configured logger instances, which internally utilize getLogger for initialization. Therefore, the process of adding custom backends would involve directly using getLogger as shown above.

API

Types
type LogLevel = 'error' | 'warn' | 'info' | 'debug';

interface LoggerOptions {
  /**
   * The logger filters messages based on the log level.
   * @default - error
   * level priority:
   * {
   *  error: 0,
   *  warn: 1,
   *  info: 2,
   *  debug: 3
   * }
   * Specifying "error" would only send calls from the logger.error() method.
   * Specifying "info" would send calls from logger.error(), logger.warn(), and logger.info() methods.
   */
  level?: LogLevel;
  /**
   * The URL of the logging service
   */
  endpoint: string;
  /**
   * The name of the application
   */
  name?: string;
  /**
   * The category of the application
   */
  category?: string;
  /**
   * The name of the host from which the log is being sent.
   */
  hostName?: string;
}

interface LoggerProviderProps {
  initialContext: LoggerOptions;
  children: React.ReactNode;
}

interface Logger {
  log(logLevel: LogLevel, data: any): void;
  info(data: any): void;
  warn(data: any): void;
  error(data: any): void;
  debug(data: any): void;
}

LoggerProvider

A React context provider component to initialize and provide the logger instance.

Props

  • initialContext: Initial configuration options for the logger.

useLogger

A hook to initialize the logger instance within a functional React component.

Returns

  • logger: The logger instance.

LoggerOptions

Configuration options for initializing the logger:

  • level: Log level (default: 'error').
  • endpoint: URL of the logging service.
  • name: Name of the application.
  • category: Category of the application.

Logger

The logger interface with methods for logging messages:

  • log(level: LogLevel, data: any): void
  • info(data: any): void
  • warn(data: any): void
  • error(data: any): void
  • debug(data: any): void

getLogger

A function to initialize the logger instance with provided options and backends.

Props

  • options: Configuration options for the logger.
  • backends: (Optional) An array of custom backends to extend logging capabilities.

Returns

  • A Promise that resolves to a Logger instance.

Implementation Details

  • Utilizes SumoLogger for logging operations.
  • Error handling and fallback mechanisms included for robust logging.
  • Supports non-React environments with modular components.

Support

#team-ui-foundations

Readme

Keywords

none

Package Sidebar

Install

npm i @procore/web-sdk-logging

Weekly Downloads

44

Version

1.1.0

License

SEE LICENSE IN LICENSE

Unpacked Size

50.8 kB

Total Files

11

Last publish

Collaborators

  • dancingshell
  • justinmwatts
  • antonyayoub
  • rysmithprocore
  • robbiegprocore
  • jadamsss
  • jeremy.bouzigard
  • jgentes
  • faraz.hanif
  • timdoherty
  • ajaykumar-procore
  • b.bookout
  • jalyng
  • chadryder
  • htael
  • refaiepcn
  • james.lawson
  • vinayakaprabhu
  • davidshure
  • james.cleary
  • jl4ever
  • andersonbispoprocore
  • dev-account-admin
  • brockpcor
  • rowan.ibrahim
  • sseanwang
  • ramysaid2
  • vinaya-procore
  • lalovar-procore
  • bhargavrnd
  • ihor.diachenko_procore
  • farismmk
  • gideon-procore
  • dannyporrello
  • alanprocore
  • chance.eakin.procore
  • stevenliprocore
  • javio-procore
  • kani-procore
  • enyaga
  • danny.ou
  • messanjah
  • david-christensen-procore
  • shradha.khard
  • winson.chu
  • eyvettesou
  • lzhou888
  • jnhoang1
  • nickprocore
  • neil.mckeeman
  • pam-whisenhunt
  • jgee67
  • youssefamer
  • mike-arndt-procore
  • bob.laskowski
  • cagmz
  • mariah_delaney
  • lukenispel
  • fabriciobd
  • bikash.sahoo
  • bbreyel921
  • kimhin267
  • andy.mayer
  • phil.custer
  • elijah.procore
  • juliana.hernandez
  • judy-lu-pc
  • procore-it-support
  • andrewburke-pc
  • jkleintech
  • rachel.arkebauer
  • procore-npm-bot
  • grafffffff
  • yoyis3000
  • james.dabbs-procore
  • laurenbrandsteinprocore
  • scottbieser-procore
  • amir-iskander
  • zach.mckenzie.procore
  • amyprocore
  • shayonj_procore
  • heplayskeys
  • mike.south
  • thomasoboyle
  • dischorde
  • derek-carter-procore
  • dlgasser
  • cfprocore
  • evan.waits
  • jeremy-marcus
  • jmejia-fsl
  • ersgonzalo
  • timofeee
  • stephan-procore
  • aleclarsenprocore
  • sarah.freitas
  • yihai.zweifel
  • jay-rajan
  • jacky-lei
  • apcarroll_procore
  • procore_halzy
  • mehrdad-panahandeh
  • peter.jin
  • uddhavjoglekar
  • brookyboy009
  • denzylbalram
  • changprocore
  • allenanle.procore
  • devin.cunningham.procore
  • ari-procore
  • noor.ali
  • hgouhierprocore
  • cyrille.bai
  • brad.urani
  • dmccraw-procore
  • patrick.lardin
  • abhijit.patwardhan
  • matt.harris0223
  • alan.bresani
  • jesse.olsen
  • dtorres-procore
  • dineshkumar.jayak
  • jason-kaye
  • yadhu.prakash
  • leandro-proc
  • andrew.wheeler
  • sherylnapigkit
  • lydiahara
  • kahliholmes
  • sateesh-kadiyala-procore
  • epalinprocore
  • dennis.heckman
  • jamie-dugan-procore
  • viktoriia_azarovska
  • daniel.ferreira-contractor
  • willpankonien
  • ladavarga
  • steven.hinkle
  • txin1
  • chris.berber
  • etokarev
  • ritchlee
  • karina.mendez-contractor
  • worldofsatyaki
  • greg.sparks
  • kyle.williams
  • kuldeepsingh4556
  • jeremy.lund
  • brocktillotsonprocore
  • stajics
  • ryanfuentesprocore
  • tyler.wasden.procore
  • fabiomelo513
  • cody_schindler_procore
  • amit.gurav-contractor
  • yoasyo25
  • kalyani.gosavi
  • hectorthiele
  • andersontr15
  • vishal-procore
  • omar.wagdy
  • yogevfine1
  • charan_procore
  • scorgiat-procore
  • mbartlett413
  • attachi
  • ahmed.ghorab
  • varomir
  • alyelashram_procore
  • ilya.dryha-contractor
  • evan.cerwonka.procore
  • vsobol-c
  • dmitri_wm
  • kellikearns
  • richard.bunn
  • chaitra-m-15
  • conner-procore
  • mishaelowoyemi
  • peterknif
  • aleh.haurylenia-contractor
  • miguel.garcia-procore
  • codyrobertsprocore
  • a.elbadawei
  • lnspatz914
  • melch-procore
  • mustafa-abdelrahman
  • atoaima
  • jasaswini
  • adarsh.gautam
  • amin.jaipuri
  • max.helmetag
  • s_kudryk
  • hyogman
  • kyle.liu
  • davidkangpro
  • stevenkang3
  • cbathgate
  • victorbendeck-pc
  • sarah.heredia
  • moaz-ashraf
  • aly-el-kerdany
  • procore-oss-user
  • abhishekkumar123
  • stephanie.brereton
  • saurasumprocore
  • mona.khairbek
  • elewando-procore
  • jyang-procore
  • tedyang
  • deiab
  • jgreene_procore
  • asamay
  • kenny.foisy
  • ganesh.raghupathy
  • rajatmenhdiratta
  • yzhou2024
  • dlameter-procore
  • decha-sanson
  • kylepietz
  • connie-feng-procore
  • roger-procore
  • matheusprocore
  • fernandocamilotti
  • simona.iancu
  • jacksonleach-procore
  • g2mitchell
  • tatsiana.clifton
  • phunguyen-pcor
  • pmfrawley
  • brian.smith1
  • scottstern
  • neil1023
  • srichaitanya.peddinti
  • jake-pitkin
  • erikthoreson
  • lhuang325
  • abhijit-procore
  • rodayna.ehab
  • fairchild
  • mustafa-u-abdelrahman
  • aberkowitz
  • pwhisenhunt-procore
  • mariia.solodovnik
  • nigeld-procore
  • samad.virani
  • bohdan-horai-procore
  • mathenes_procore
  • vinoth.kuppusamy
  • zayter
  • alan.facchini-contractor
  • cassianomatos-procore
  • amitk030
  • sflang-procore
  • tracy.otto
  • daniel-pierre-procore
  • glidenor
  • ashish.sharma2024
  • gaurav.sharma.procore
  • andres-mendez-procore
  • roobo-romeski
  • kylemartinez-procore
  • sean.spearman.procore
  • gturkadze
  • jeffgiaquinto
  • ezrasimeloff
  • bill-wagner
  • kellen.stewart
  • rodrigo.dejuana
  • saranahal2
  • andrew.isaac
  • agamaleldin
  • mostafaeltazy
  • magdyyxx
  • andreszorrilla-procore
  • mohitsharma97
  • tejeshwar
  • swati.jadhav
  • squidbeaks
  • subham.panigrahi
  • deepak.kumarts
  • mahesh-s96
  • mohamed.adel
  • rana.eltayar
  • mahmoud-sharshar
  • syamphanindra
  • veroniaosama
  • imanselim
  • helmy162-procore
  • pclemons
  • samuelvelez8383
  • vinitdeshkar-procore