Skip to content

Commit 1f40998

Browse files
committed
feat: use on application bootstrap lifecycle event
1 parent 25fb49c commit 1f40998

File tree

4 files changed

+146
-171
lines changed

4 files changed

+146
-171
lines changed

README.md

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ ReporterService.counter('api_requests_total', { endpoint: '/users' });
4343
Unlike [@willsoto/nestjs-prometheus](https://github.com/willsoto/nestjs-prometheus), `nestjs-metrics-client` removes the need for cumbersome dependency injection, making your code cleaner and more portable.
4444

4545
🌟 **Effortless Integration**
46-
With minimal setup, you can start tracking metrics immediately. No need to configure a service in every file—just use the global `ReporterService`.
46+
With zero setup, you can start tracking metrics immediately. No need to configure a service in every file—just use the global `ReporterService`.
4747

4848
🎯 **Focus on Simplicity**
4949
Designed for developers who want powerful metrics without the complexity of managing dependencies or boilerplate code.
@@ -75,25 +75,7 @@ import { ReporterModule } from 'nestjs-metrics-client';
7575
export class AppModule {}
7676
```
7777

78-
### 2. Initialize the Global Reporter
79-
80-
Easily initialize the global `ReporterService` in your bootstrap function. No additional injections required.
81-
82-
```typescript
83-
import { NestFactory } from '@nestjs/core';
84-
import { MetricsService, ReporterService } from 'nestjs-metrics-client';
85-
86-
async function bootstrap() {
87-
const app = await NestFactory.create(AppModule);
88-
89-
// Initialize the global reporter
90-
ReporterService.init(app.get(MetricsService));
91-
92-
await app.listen(3000);
93-
}
94-
```
95-
96-
### 3. Report Metrics Anywhere
78+
### 2. Report Metrics Anywhere
9779

9880
Once initialized, you can start reporting metrics instantly from anywhere in your application.
9981

@@ -125,7 +107,6 @@ The global static service for reporting metrics:
125107

126108
| Method | Description | Parameters |
127109
|--------------|-----------------------------|-------------------------------------------------------------|
128-
| `init()` | Initialize the reporter | `metricsService: MetricsService` |
129110
| `counter()` | Increment a counter metric | `key: string, labels?: Record<string, string | number>` |
130111
| `gauge()` | Set a gauge value | `key: string, value: number, labels?: Record<string, string | number>` |
131112
| `histogram()`| Record a histogram value | `key: string, value: number, labels?: Record<string, string | number>, buckets?: number[]` |

src/reporter/reporter.service.ts

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,41 @@
1-
import { Logger } from '@nestjs/common';
1+
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
22
import { MetricsService } from '../metrics/metrics.service';
33

4-
export class ReporterService {
4+
@Injectable()
5+
export class ReporterService implements OnApplicationBootstrap {
56
private static readonly logger = new Logger( ReporterService.name );
67
private static metricsService: MetricsService;
78

8-
static init( metricsService: MetricsService ): void {
9-
ReporterService.metricsService = metricsService;
9+
constructor( private readonly metrics: MetricsService ) {}
10+
onApplicationBootstrap() {
11+
ReporterService.metricsService = this.metrics;
1012
}
1113

12-
static counter(
13-
key: string,
14-
labels?: Record<string, string | number>
15-
): void {
14+
static counter(key: string, labels?: Record<string, string | number>): void {
1615
try {
1716
ReporterService.metricsService.incCounter( key, labels );
1817
} catch ( error ) {
1918
this.logger.error( `Error while incrementing counter - ${ key }`, error );
2019
}
2120
}
2221

23-
static gauge(
24-
key: string,
25-
value: number,
26-
labels?: Record<string, string | number>
27-
): void {
22+
static gauge(key: string, value: number, labels?: Record<string, string | number>): void {
2823
try {
2924
ReporterService.metricsService.setGauge( key, value, labels );
3025
} catch ( error ) {
3126
this.logger.error( `Error while setting gauge - ${ key }, ${ value }`, error );
3227
}
3328
}
3429

35-
static histogram(
36-
key: string,
37-
value: number,
38-
labels?: Record<string, string | number>,
39-
buckets?: number[]
40-
): void {
30+
static histogram(key: string, value: number, labels?: Record<string, string | number>, buckets?: number[]): void {
4131
try {
4232
ReporterService.metricsService.observeHistogram( key, value, labels, buckets );
4333
} catch ( error ) {
4434
this.logger.error( `Error while observing histogram - ${ key }, ${ value }`, error );
4535
}
4636
}
4737

48-
static summary(
49-
key: string,
50-
value: number,
51-
labels?: Record<string, string | number>,
52-
percentiles?: number[]
53-
): void {
38+
static summary(key: string, value: number, labels?: Record<string, string | number>, percentiles?: number[]): void {
5439
try {
5540
ReporterService.metricsService.observeSummary( key, value, labels, percentiles );
5641
} catch ( error ) {

tests/reporter.module.spec.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ describe('ReporterModule', () => {
99
if (module) {
1010
await module.close();
1111
}
12+
(ReporterService as any).metricsService = undefined;
1213
});
1314

1415
describe('forRoot', () => {
@@ -23,28 +24,29 @@ describe('ReporterModule', () => {
2324
})
2425
],
2526
}).compile();
26-
27-
const metricsService = module.get<MetricsService>(MetricsService);
28-
ReporterService.init(metricsService);
27+
28+
const reporterService = module.get<ReporterService>(ReporterService);
29+
reporterService.onApplicationBootstrap();
30+
2931
ReporterService.counter('test_counter');
3032

3133
const registry = module.get<Registry>(Registry);
3234
const metrics = await registry.metrics();
33-
35+
3436
expect(metrics).toContain('app="test-app"');
3537
expect(metrics).toContain('environment="test"');
3638
});
37-
39+
3840
it('should work without configuration', async () => {
3941
module = await Test.createTestingModule({
4042
imports: [ReporterModule.forRoot()],
4143
}).compile();
42-
44+
4345
expect(module.get(Registry)).toBeDefined();
4446
expect(module.get(MetricsService)).toBeDefined();
4547
});
4648
});
47-
49+
4850
describe('forRootAsync', () => {
4951
it('should support async configuration', async () => {
5052
module = await Test.createTestingModule({
@@ -58,9 +60,10 @@ describe('ReporterModule', () => {
5860
})
5961
],
6062
}).compile();
61-
62-
const metricsService = module.get<MetricsService>(MetricsService);
63-
ReporterService.init(metricsService);
63+
64+
const reporterService = module.get<ReporterService>(ReporterService);
65+
reporterService.onApplicationBootstrap();
66+
6467
ReporterService.counter('test_counter');
6568

6669
const registry = module.get<Registry>(Registry);
@@ -98,4 +101,4 @@ describe('ReporterModule', () => {
98101
}).compile()).rejects.toThrow('Config error');
99102
});
100103
});
101-
});
104+
});

0 commit comments

Comments
 (0)