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

application-metrics

v1.2.2

Published

Metrics for a NodeJS application

Downloads

304

Readme

A set of metrics used for analyzing application state, based on prometheus metrics.

Usage

npm i application-metrics

Counter

import {MetricsService} from 'application-metrics';


for (let i = 0; i < 100; i++) {
    MetricsService.counter('items_processed').inc();
}

Labels

import {MetricsService} from 'application-metrics';

const conf = {};// read conf  
MetricsService.label('conf_value', conf.someValue)

Timers

import {MetricsService} from 'application-metrics';

function process(): void {
    for (let i = 0; i < 100; i++) {
        // do some stuff
    }
}

async function processAsync(): Promise<void> {
    for (let i = 0; i < 100; i++) {
        // do some stuff
    }
}

MetricsService.timer('process_ms').time(() => process());
MetricsService.timer('process_async_ms').time(() => processAsync());

or use @Metric() to observe the method:

import {MetricsService} from 'application-metrics';

class EntriesDao {
    
    @Metric('saveEntries')
    async saveEntries(entries: object[]): Promise<void> {
        // ...
    }
}

Metric name can be skipped, the method name will be used instead:

import {MetricsService} from 'application-metrics';

class EntriesDao {
    
    @Metric()
    async saveEntries(entries: object[]): Promise<void> {
        // ...
    }
}

You can also pass parameters to the underlying summary object. See prom-client summary documentation.

import {MetricsService} from 'application-metrics';

class EntriesDao {
    
    @Metric({maxAgeSeconds: 300, ageBuckets: 5, pruneAgedBuckets: true})
    async saveEntries(entries: object[]): Promise<void> {
        // ...
    }
}

Gauges

import {MetricsService} from 'application-metrics';

MetricsService.gauge('memory_external', () => process.memoryUsage().external);
MetricsService.gauge('memory_rss', () => process.memoryUsage().rss);
MetricsService.gauge('memory_heapTotal', () => process.memoryUsage().heapTotal);
MetricsService.gauge('memory_heapUsed', () => process.memoryUsage().heapUsed);

Histograms

import {MetricsService} from 'application-metrics';
import * as fs from 'fs';

const files = fs.readdirSync('.');
files.forEach(f => {
    MetricsService.histogram('file_size_bytes').observe(fs.statSync(f).size);
});

MetricsService.toConsole().then(msg => {
    console.log(msg);
});

outputs something like

****** METRICS ******
Histograms:       
  file_size_bytes:  {"50":543,"90":11328,"95":300966,"99":397512,"count":15}

Output

You can periodically print metrics to console:

import {MetricsService} from 'application-metrics';

MetricsService.gauge('memory_external', () => process.memoryUsage().external);
MetricsService.gauge('memory_rss', () => process.memoryUsage().rss);
MetricsService.gauge('memory_heapTotal', () => process.memoryUsage().heapTotal);
MetricsService.gauge('memory_heapUsed', () => process.memoryUsage().heapUsed);


setInterval(async () => {
    console.log(await MetricsService.toConsole());
}, 60000);

will produce something like:

 ****** METRICS ******
Gauges:                                                   
  memory_external:                           104,763,523
  memory_rss:                                440,160,256
  memory_heapTotal:                          255,873,024
  memory_heapUsed:                           229,729,176

Also, you can have an endpoint to show metrics as json or in prometheus format (example uses NestJS):

import {MetricsService} from 'application-metrics';
import {Controller, Get, Header} from '@nestjs/common';
import {
    ApiOkResponse,
    ApiOperation,
    ApiProduces,
    ApiTags,
} from '@nestjs/swagger';

@Controller()
@ApiTags('metrics')
export class MetricsController {
    
    @ApiOperation({
        description: 'Get metrics in json format',
        summary: 'Get metrics in json format',
    })
    @ApiOkResponse({description: 'Success', type: Object})
    @Get('metrics')
    @Header('Content-Type', 'application/json')
    async getMetrics(): Promise<string> {
        return JSON.stringify(await MetricsService.toJson(), null, 4);
    }

    
    @ApiOperation({
        description: 'prometheus metrics export endpoint',
        summary: 'Get metrics in prometheus format',
    })
    @ApiOkResponse({description: 'Success', type: String})
    @ApiProduces('text/plain')
    @Get('prometheusmetrics')
    @Header('Content-Type', 'text/plain')
    async getPrometheusMetrics(): Promise<string> {
        return MetricsService.toPrometheus();
    }
}
curl localhost:3000/metrics
{
    "gauges": {
        "memory_external": 17936815,
        "memory_rss": 291016704,
        "memory_heapTotal": 202420224,
        "memory_heapUsed": 180871624
    }
}
curl localhost:3000/prometheusmetrics
# HELP gauge_memory_external gauge_memory_external
# TYPE gauge_memory_external gauge
memory_external 85052806

# HELP gauge_memory_rss gauge_memory_rss
# TYPE gauge_memory_rss gauge
memory_rss 401350656

# HELP gauge_memory_heapTotal gauge_memory_heapTotal
# TYPE gauge_memory_heapTotal gauge
memory_heapTotal 224940032

# HELP gauge_memory_heapUsed gauge_memory_heapUsed
# TYPE gauge_memory_heapUsed gauge
memory_heapUsed 185016864