Skip to content

Commit

Permalink
Feat(functions): added support for prefixing traced function name wit…
Browse files Browse the repository at this point in the history
…h layer
  • Loading branch information
Akalanka47000 committed Jan 14, 2024
1 parent 6f8d322 commit 22ec0bf
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
3 changes: 2 additions & 1 deletion packages/functions/src/traced.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export const _traced = (fn, loggable = {}, fnName) => {
const disableTracing =
process.env.DISABLE_FUNCTION_TRACING === "true" || process.env.DISABLE_FUNCTION_TRACING === "1";
if (!disableTracing) {
fnName = fnName ?? _fnName(fn);
fnName = fnName ?? _fnName(fn, loggable.layer);
delete loggable.layer;
logger.info(`${fnName} execution initiated`, loggable);
startTime = performance.now();
}
Expand Down
8 changes: 4 additions & 4 deletions packages/functions/src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import chalk from "chalk";

export const fnName = (fn) => {
export const fnName = (fn, prefix) => {
let name = fn.name;
while (1) {
const replaced = name?.replace("bound", "");
if (name.startsWith("bound") && replaced?.startsWith(" ")) name = replaced?.trim();
else break;
}
if (!name) return coloredFnName("Unnamed function");
if (!name) return coloredFnName("Unnamed function", prefix);
if (name.startsWith(" ")) return name.slice(1);
return coloredFnName(name);
return coloredFnName(name, prefix);
};

export const coloredFnName = (fn) => chalk.bold(chalk.magentaBright(fn));
export const coloredFnName = (fn, prefix) => chalk.bold(chalk.magentaBright(prefix ? `${prefix}->${fn}` : fn));
10 changes: 10 additions & 0 deletions packages/functions/test/traced.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ 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" }
)();
expect(res).toStrictEqual(_mockResult);
expect(mockLogger.info).toBeCalledWith(`${coloredFnName("controller->testFunction")} execution initiated`, {});
});
test("test arrow function", () => {
const testArrowFunction = () => _mockResult;
const res = traced(testArrowFunction)();
Expand Down

0 comments on commit 22ec0bf

Please sign in to comment.