npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@procore/web-sdk-logging

v0.1.5

Published

Procore Web Platform Logging

Downloads

154

Maintainers

conner-procoreconner-procorechaitra-m-15chaitra-m-15vsobol-cvsobol-cabhishekkumar123abhishekkumar123jasaswinijasaswinialeh.haurylenia-contractoraleh.haurylenia-contractorkellikearnskellikearnsviktoriia_azarovskaviktoriia_azarovskafabriciobdfabriciobdyoussefameryoussefamerbrockpcorbrockpcorkani-procorekani-procoreantonyayoubantonyayoubashish.sharma2024ashish.sharma2024glidenorglidenordaniel-pierre-procoredaniel-pierre-procoreamitk030amitk030mathenes_procoremathenes_procorevinoth.kuppusamyvinoth.kuppusamymariia.solodovnikmariia.solodovniksflang-procoresflang-procorecassianomatos-procorecassianomatos-procorealan.facchini-contractoralan.facchini-contractorzayterzayterbohdan-horai-procorebohdan-horai-procorenigeld-procorenigeld-procoresamad.viranisamad.viranifernandocamilottifernandocamilotticonnie-feng-procoreconnie-feng-procoreroger-procoreroger-procoreganesh.raghupathyganesh.raghupathyyzhou2024yzhou2024alyelashram_procorealyelashram_procoremelch-procoremelch-procorepeterknifpeterknifmoaz-ashrafmoaz-ashrafattachiattachia.elbadaweia.elbadaweihyogmanhyogmandmitri_wmdmitri_wmstephanie.breretonstephanie.breretonprocore-oss-userprocore-oss-userstevenkang3stevenkang3max.helmetagmax.helmetagcodyrobertsprocorecodyrobertsprocoremiguel.garcia-procoremiguel.garcia-procoremagdyyxmagdyyxatoaimaatoaimamustafa-abdelrahmanmustafa-abdelrahmanelewando-procoreelewando-procoreahmed.ghorabahmed.ghorablnspatz914lnspatz914richard.bunnrichard.bunnomar.wagdyomar.wagdymona.khairbekmona.khairbekmbartlett413mbartlett413cody_schindler_procorecody_schindler_procoreyoasyo25yoasyo25ritchleeritchleeandersontr15andersontr15steven.hinklesteven.hinklejamie-dugan-procorejamie-dugan-procorehgouhierprocorehgouhierprocoredenzylbalramdenzylbalramsarah.freitassarah.freitasalan.bresanialan.bresaniamyprocoreamyprocoreyoyis3000yoyis3000elijah.procoreelijah.procoremike-arndt-procoremike-arndt-procorejnhoang1jnhoang1pam-whisenhuntpam-whisenhuntshradha.khardshradha.kharddavid-christensen-procoredavid-christensen-procorejavio-procorejavio-procorechance.eakin.procorechance.eakin.procoregideon-procoregideon-procoreihor.diachenko_procoreihor.diachenko_procorejustinmwattsjustinmwattstedyangtedyangjyang-procorejyang-procorepwhisenhunt-procorepwhisenhunt-procorefairchildfairchildrodayna.ehabrodayna.ehabneil1023neil1023scottsternscottsternbrian.smith1brian.smith1g2mitchellg2mitchelldlameter-procoredlameter-procorekylepietzkylepietzabhijit-procoreabhijit-procorelhuang325lhuang325jake-pitkinjake-pitkinerikthoresonerikthoresonsimona.iancusimona.iancudecha-sansondecha-sansonaberkowitzaberkowitzasamayasamaymustafa-u-abdelrahmanmustafa-u-abdelrahmanrajatmenhdirattarajatmenhdirattajacksonleach-procorejacksonleach-procorepmfrawleypmfrawleyphunguyen-pcorphunguyen-pcortatsiana.cliftontatsiana.cliftondeiabdeiabsrichaitanya.peddintisrichaitanya.peddintikenny.foisykenny.foisymatheusprocorematheusprocorejgreene_procorejgreene_procorehectorthielehectorthieleetokarevetokarevdaniel.ferreira-contractordaniel.ferreira-contractordmccraw-procoredmccraw-procorecyrille.baicyrille.baigreg.sparksgreg.sparksfabiomelo513fabiomelo513phil.custerphil.custerbbreyel921bbreyel921amir-iskanderamir-iskanderneil.mckeemanneil.mckeemannickprocorenickprocorelzhou888lzhou888davidshuredavidshurestevenliprocorestevenliprocoreramysaid2ramysaid2refaiepcnrefaiepcnjgentesjgentesfaraz.haniffaraz.hanifmostafaeltazymostafaeltazyagamaleldinagamaleldinandrew.isaacandrew.isaacsaranahal2saranahal2rodrigo.dejuanarodrigo.dejuanakellen.stewartkellen.stewartbill-wagnerbill-wagnerezrasimeloffezrasimeloffjeffgiaquintojeffgiaquintogturkadzegturkadzesean.spearman.procoresean.spearman.procorekylemartinez-procorekylemartinez-procoreroobo-romeskiroobo-romeskiandres-mendez-procoreandres-mendez-procoregaurav.sharma.procoregaurav.sharma.procoretracy.ottotracy.ottosarah.herediasarah.herediavictorbendeck-pcvictorbendeck-pccbathgatecbathgatedavidkangprodavidkangprokyle.liukyle.liuamin.jaipuriamin.jaipurigrafffffffgrafffffffmishaelowoyemimishaelowoyemievan.cerwonka.procoreevan.cerwonka.procoreilya.dryha-contractorilya.dryha-contractorvaromirvaromiryogevfine1yogevfine1timofeeetimofeeematt.harris0223matt.harris0223winson.chuwinson.chuandersonbispoprocoreandersonbispoprocorescorgiat-procorescorgiat-procoreladavargaladavargaprocore_halzyprocore_halzyenyagaenyagawillpankonienwillpankoniensateesh-kadiyala-procoresateesh-kadiyala-procorechris.berberchris.berbertxin1txin1epalinprocoreepalinprocoremehrdad-panahandehmehrdad-panahandehtyler.wasden.procoretyler.wasden.procorejeremy.lundjeremy.lunddineshkumar.jayakdineshkumar.jayakryanfuentesprocoreryanfuentesprocorestajicsstajicsbrocktillotsonprocorebrocktillotsonprocorekyle.williamskyle.williamsdtorres-procoredtorres-procorenoor.alinoor.aliari-procoreari-procorealanprocorealanprocorejl4everjl4everjames.lawsonjames.lawsonajaykumar-procoreajaykumar-procoredennis.heckmandennis.heckmantara.chamberstara.chamberslalovar-procorelalovar-procorejames.clearyjames.clearychadryderchadryderdevin.cunningham.procoredevin.cunningham.procoreabhijit.patwardhanabhijit.patwardhanlydiaharalydiaharasherylnapigkitsherylnapigkitchangprocorechangprocoreapcarroll_procoreapcarroll_procoreandy.mayerandy.mayerbob.laskowskibob.laskowskivinaya-procorevinaya-procorekahliholmeskahliholmesandrew.wheelerandrew.wheelerleandro-procleandro-procyadhu.prakashyadhu.prakashjason-kayejason-kayejesse.olsenjesse.olsenpatrick.lardinpatrick.lardinbrad.uranibrad.uraniallenanle.procoreallenanle.procorebrookyboy009brookyboy009uddhavjoglekaruddhavjoglekardancingshelldancingshellrysmithprocorerysmithprocorerobbiegprocorerobbiegprocorejadamsssjadamsssjeremy.bouzigardjeremy.bouzigardtimdohertytimdohertyb.bookoutb.bookoutjalyngjalynghtaelhtaeldev-account-admindev-account-adminsseanwangsseanwangbhargavrndbhargavrndfarismmkfarismmkdannyporrellodannyporrellodanny.oudanny.oumessanjahmessanjaheyvettesoueyvettesoujgee67jgee67cagmzcagmzmariah_delaneymariah_delaneylukenispellukenispelkimhin267kimhin267juliana.hernandezjuliana.hernandezjudy-lu-pcjudy-lu-pcprocore-it-supportprocore-it-supportandrewburke-pcandrewburke-pcjkleintechjkleintechrachel.arkebauerrachel.arkebauerprocore-npm-botprocore-npm-botjames.dabbs-procorejames.dabbs-procorelaurenbrandsteinprocorelaurenbrandsteinprocorescottbieser-procorescottbieser-procorezach.mckenzie.procorezach.mckenzie.procoreshayonj_procoreshayonj_procoreheplayskeysheplayskeysmike.southmike.souththomasoboylethomasoboyledischordedischordederek-carter-procorederek-carter-procoredlgasserdlgassercfprocorecfprocoreevan.waitsevan.waitsjeremy-marcusjeremy-marcusjmejia-fsljmejia-fslersgonzaloersgonzalostephan-procorestephan-procorealeclarsenprocorealeclarsenprocoreyihai.zweifelyihai.zweifeljay-rajanjay-rajanjacky-leijacky-leipeter.jinpeter.jin

Keywords

Readme

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';

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

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

initializeLogger();

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>
  );
}

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, isLoaded, error } = useLogger();

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

  if (error) {
    return <div>Error initializing logger: {error.message}</div>;
  }

  return <div>{isLoaded ? 'Logger is loaded' : 'Loading logger...'}</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);
  }
}

async 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 = await 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 LoggerContextType {
  logger: Logger | null;
  isLoaded: boolean;
  error: Error | null;
}

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.
  • isLoaded: Indicates if the logger is successfully initialized.
  • error: Error object if logger initialization fails.

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