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

@defra/logging-metrics

v1.0.1

Published

Defra Common Platform logging metrics

Downloads

8

Readme

Defra Logging Metrics

This Defra Common Platform npm package provides a library to measure the duration of functions execution and log them into Azure Application Insights as custom metrics with optional custom dimensions.

Run tests

npm install
npm test

Use the package from npm

  1. Install the package

    npm install @defra/logging-metrics --save
  2. Import the module in your script

    import MetricsService from '@defra/logging-metrics'
  3. Initialize the metrics service

    let metricsService = new MetricsService()
  4. If you are already running application insights and already have a TelemetryClient configured in your application, you can create the metrics service and pass the telemetry client to the constructor:

    let metricsService = new MetricsService(telemetryClient)

    Alternatively you can create a new telemetry client and provide the configuration with a connection string and any other configuration options you wish e.g.:

    let telemetryClientConfig = {
       connectionString: "InstrumentationKey=myKey;IngestionEndpoint=https://applicationinsights.azure.com/;LiveEndpoint=https://livediagnostics.monitor.azure.com/",
       samplingPercentage: 100
    }
    
    [...]
    
    let { duration, result } = metricsService.execute(myFunction, metric, telemetryClientConfig)

    If you don't provide a telemetry client in the constructor and you don't provide a telemetry client configuration, a new telemetry client will be created by reading the connection string from the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.

  5. Name the metric you want to log with along with any other custom properties to be recorded e.g.:

    let metric = {
       name: "timeToCallDatabase",
       properties: { source: "CosmosDB" }
    }
  6. Execute your function via one of the following methods, providing the config and metric from the previous steps along with the function you want to call and measure:

    • If your function does not return any kind of Promise:
    let { duration, result } = metricsService.execute(myFunction, metric, config)
    console.log(`Took ${duration} seconds for ${result}`)
    • If your function returns a Promise:
    metricsService.executeAsync(asyncFunction, metric, config)
    .then(({ result, duration }) => {
       console.log(`Took ${duration} seconds for ${result}`)
    })
    • If you need to use a Promise.all()-like behavior and record each function call:
    metricsService.executeAllFailFastAsync(() => [asyncFunction1, asyncFunction2], metric, config)
    .then(({ results, durations }) => {
       results.forEach((result, i) => {
          console.log(`Took ${durations[i]} seconds for ${result}`)
       })
    })
    • If you need to use a Promise.allSettled()-like behavior and record each function call:
    metricsService.executeAllAsync(() => [asyncFunction1, asyncFunction2], metric, config)
    .then(({ results, durations }) => {
       results.forEach((result, i) => {
          console.log(`Took ${durations[i]} seconds for ${result}`)
       })
    })
  7. As advised in Application Insights documentation:

    If your application has a short lifespan, such as a CLI tool, it might be necessary to manually flush your buffered telemetry [...]

    Flush is supported by calling metricsService.flushClient()

  8. If you wish to further use, configure or access the Microsoft Azure Application Insights TelemetryClient within the metrics service, it can be accessed through the metricsService.telemetryClient variable

Full example

A full example can be found here.