@@ -8,10 +8,68 @@ This is a simple AOP-ish toolset that lets to wrap sync and async functions and
88 - function's input parameters
99 - function's this arg
1010 - function itself (hook can conditionally do some extra wrapping)
11- - handle and override error ( onCatch, onFinally)
11+ - override onCatch, onFinally:
1212 - function's result
1313 - function's error to (re-)throw
14+ - log, measure all of those mentioned above
1415
15- It supports using as decorator, function wrapper or scope of anonymous function
16+ It supports using as decorator, function wrapper or scope of anonymous function:
17+
18+ It supports typescript
19+
20+ It supports sync and async functions/methods
21+
22+ ``` ts
23+ // / track.ts
24+ export const tracker = new TryCatchFinallyHooksBuilder ()
25+ .add (callStack )
26+ .add (measureDuration )
27+ .add (ctx => {
28+ console .log (` ℹ️ Action ${ctx .name } started... ` )
29+ return {
30+ onFinally() {
31+ if (ctx .funcOutcome .error )
32+ console .log (` ❌ Action ${ctx .name } failed with ${ctx .funcOutcome .error }. Took ${ctx .duration }ms to complete ` )
33+ else
34+ console .log (` ✅ Action ${ctx .name } succeed with result:${ctx .funcOutcome .result }. Took ${ctx .duration }ms to complete ` )
35+ // you can override either result or error here
36+ // if you set ctx.funcOutcome.error = undefined - function will not throw error
37+
38+ datadog .histogram (
39+ ` action-${ctx .name }-duration ` ,
40+ ctx .duration ,
41+ { tags: [' action:' + ctx .name , ' callstack:' + ctx .getCallStack ().map (c => c .name ).join (' /' )] }
42+ );
43+ },
44+ };
45+ })
46+
47+ export const trackFn = tracker .asFunctionWrapper .bind (tracker )
48+ export const trackMethod = tracker .asDecorator .bind (tracker )
49+
50+ // myClass.ts
51+
52+ class MyClass {
53+ @trackMethod ({name:' Hello world' })
54+ async helloWorld(url : string )
55+ {
56+ await doing ()
57+ await somethingLongRunning (url )
58+ return await andErroneous ()
59+ }
60+ }
61+
62+ // myFunc.ts
63+
64+ export const myFunc = trackFn ({name: ' My function' })((param1 : number )=> {
65+ // doing something long running and risky
66+ step1 ()
67+ step2 ()
68+ const res = tracker .scope ({name:' important step 3' },()=> {
69+ return step3 (param1 )
70+ })
71+ return res
72+ })
73+ ```
1674
1775See [ specs] ( ./specs ) for examples
0 commit comments