Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat(functions): updated usage of tracing layer prefix #138

Merged
merged 2 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/functions/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ tracedFoo();

- ### cleanTraced and cleanTrace `(Same as the above two but ignores tracing for anonymous functions to avoid polluting the logs)`

- ### tracing a function with a layer prefix (Works for all 4 functions above)

```js
const tracedFoo = traced["controller"](function foo() {
console.log(123);
})();

tracedFoo();

/*
controller >>> foo execution initiated
123
controller >>> foo execution completed - execution_time : 0.2069999985396862
*/
```

- ### bindKey `(Creates a bounded function from a passed object and function key with its context preserved)`
<br/>
- This method is distint from the `bindKey` function of lodash as this preserves the function's `name` property where lodash sets it as `wrapper`
Expand Down
43 changes: 22 additions & 21 deletions packages/functions/src/traced.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ import { fnName as _fnName } from "./utils";

const logger = moduleLogger("tracer");

export const _traced = (fn, loggable = {}, fnName) => {
export const _traced = (fn, loggable = {}, fnName, layer) => {
let startTime;
const disableTracing =
process.env.DISABLE_FUNCTION_TRACING === "true" || process.env.DISABLE_FUNCTION_TRACING === "1";
if (!disableTracing) {
fnName = fnName ?? _fnName(fn, loggable.layer);
delete loggable.layer;
fnName = fnName ?? _fnName(fn, layer);
logger.info(`${fnName} execution initiated`, loggable);
startTime = performance.now();
}
Expand Down Expand Up @@ -50,28 +49,30 @@ export const _traced = (fn, loggable = {}, fnName) => {
}
};

export const traced =
(fn, loggable) =>
(...params) =>
_traced(fn.bind(this, ...params), loggable);
const _proxyHandlers = { get: (target, prop) => (fn, loggable) => target(fn, loggable, prop) };

export const trace = (fn, loggable) => _traced(fn, loggable);
export const traced = new Proxy(
(fn, loggable, layer) =>
(...params) =>
_traced(fn.bind(this, ...params), loggable, null, layer),
_proxyHandlers
);

export const cleanTrace = (fn, loggable) => {
if (fn.name) {
return _traced(fn, loggable);
}
export const trace = new Proxy((fn, loggable, layer) => _traced(fn, loggable, null, layer), _proxyHandlers);

export const cleanTrace = new Proxy((fn, loggable, layer) => {
if (fn.name) return _traced(fn, loggable, null, layer);
return fn();
};
}, _proxyHandlers);

export const cleanTraced =
(fn, loggable) =>
(...params) => {
if (fn.name) {
return _traced(fn.bind(this, ...params), loggable);
}
return fn.call(this, ...params);
};
export const cleanTraced = new Proxy(
(fn, loggable, layer) =>
(...params) => {
if (fn.name) return _traced(fn.bind(this, ...params), loggable, null, layer);
return fn.call(this, ...params);
},
_proxyHandlers
);

export default {
traced,
Expand Down
2 changes: 1 addition & 1 deletion packages/functions/src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ export const fnName = (fn, prefix) => {
return coloredFnName(name, prefix);
};

export const coloredFnName = (fn, prefix) => chalk.bold(chalk.magentaBright(prefix ? `${prefix}->${fn}` : fn));
export const coloredFnName = (fn, prefix) => chalk.bold(chalk.magentaBright(prefix ? `${prefix} >>> ${fn}` : fn));
13 changes: 5 additions & 8 deletions packages/functions/test/traced.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,12 @@ describe("traced", () => {
expect(res).toStrictEqual(_mockResult);
expect(mockLogger.info).toBeCalledWith(`${coloredFnName("testFunction")} execution initiated`, {});
});
test("test function with layer log", async () => {
const res = await traced(
async function testFunction() {
return _mockResult;
},
{ layer: "controller" }
)();
test("test function with layer prefix", async () => {
const res = await traced["controller"](async function testFunction() {
return _mockResult;
})();
expect(res).toStrictEqual(_mockResult);
expect(mockLogger.info).toBeCalledWith(`${coloredFnName("controller->testFunction")} execution initiated`, {});
expect(mockLogger.info).toBeCalledWith(`${coloredFnName("controller >>> testFunction")} execution initiated`, {});
});
test("test arrow function", () => {
const testArrowFunction = () => _mockResult;
Expand Down
17 changes: 8 additions & 9 deletions packages/functions/types/traced.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
type BaseTracedFunction = <T extends (...args: any[]) => any>(fn: T, loggable?: Record<any, any>) => T;

interface TracedFunction extends BaseTracedFunction {
[key: string]: BaseTracedFunction;
}

/**
* @description Invokes the given function with tracing
* @param fn The function to be invoked asynchronously
Expand All @@ -12,7 +18,7 @@ export function trace(fn: Function, loggable?: Record<any, any>): Promise<void>;
* @param loggable Object with extra information to be logged
* @returns Returns the new function
*/
export function traced<T extends (...args: any[]) => any>(fn: T, loggable?: Record<any, any>): T;
export const traced: TracedFunction;

/**
* @description Invokes the given function with tracing. Tracing is however ignored if the function is an anonymous function
Expand All @@ -28,11 +34,4 @@ export function cleanTrace(fn: Function, loggable?: Record<any, any>): Promise<v
* @param loggable Object with extra information to be logged
* @returns Returns the new function
*/
export function cleanTraced<T extends (...args: any[]) => any>(fn: T, loggable?: Record<any, any>): T;

export default {
traced,
trace,
cleanTraced,
cleanTrace
};
export const cleanTraced: TracedFunction;