Skip to content

Commit 157744c

Browse files
committed
add monitorMethod decorator
1 parent 3247358 commit 157744c

3 files changed

Lines changed: 28 additions & 3 deletions

File tree

example/run.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import 'dotenv/config';
22

3-
import {setGlobalInstance, StatsdPlugin, monitored, Monitor, increment} from '../src';
3+
import {setGlobalInstance, StatsdPlugin, monitored, Monitor, increment, monitorMethod} from '../src';
44

55
setGlobalInstance(
66
new Monitor({
@@ -104,3 +104,17 @@ increment('metric1');
104104
// Increment with type restriction
105105
type Color = 'red' | 'orange' | 'green';
106106
increment<Color>('red');
107+
108+
// monitor method using decorator
109+
class Person {
110+
firstName: string = 'Jon';
111+
lastName: string = 'Doe';
112+
113+
@monitorMethod('person', {logErrorAsInfo: true})
114+
getFullName() {
115+
return `${this.firstName} ${this.lastName}`;
116+
}
117+
}
118+
const person = new Person();
119+
const name = person.getFullName();
120+
console.log(`person's name is ${name}`);

src/globalInstance.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Monitor from './Monitor';
2+
import {MonitoredOptions} from './types';
23

34
let instance: Monitor | undefined;
45

@@ -15,10 +16,19 @@ export function getGlobalInstance(): Monitor {
1516
}
1617

1718
export const monitored: Monitor['monitored'] = (...args) => getGlobalInstance().monitored(...args);
19+
1820
/**
1921
* @deprecated since version 2.0
2022
*/
2123
export const getStatsdClient: Monitor['getStatsdClient'] = (...args) => getGlobalInstance().getStatsdClient(...args);
2224
export const increment: Monitor['increment'] = (...args) => getGlobalInstance().increment(...args);
2325
export const gauge: Monitor['gauge'] = (...args) => getGlobalInstance().gauge(...args);
2426
export const timing: Monitor['timing'] = (...args) => getGlobalInstance().timing(...args);
27+
28+
export const monitorMethod = <T>(prefix?: string, options: MonitoredOptions<T> = {}) => {
29+
return function (_target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
30+
const originalMethod = descriptor.value;
31+
const metricName = `${prefix}${prefix ? '.' : ''}${propertyKey}`;
32+
descriptor.value = monitored(metricName, originalMethod, options);
33+
};
34+
};

tsconfig.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@
1818
"lib": ["dom", "es2017"],
1919
"skipLibCheck": true,
2020
"noImplicitAny": false,
21-
"useUnknownInCatchVariables": false
21+
"useUnknownInCatchVariables": false,
22+
"experimentalDecorators": true
2223
},
23-
"include": ["src/**/*", "types/*.d.ts"],
24+
"include": ["src/**/*", "types/*.d.ts", "example/**/*"],
2425
"exclude": ["__tests__", "dist"]
2526
}

0 commit comments

Comments
 (0)