Skip to content

Commit

Permalink
Adds option to set origin index
Browse files Browse the repository at this point in the history
  • Loading branch information
Izabela Cardoso committed Dec 3, 2020
1 parent ad4603c commit ea3afe1
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/logger-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export interface LoggerOptions {
includeBlackList?: string[];
excludeBlackList?: string[];
whiteList?: string[];
originIndex?: number;
}
5 changes: 4 additions & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export class Logger {

private readonly level: string;

private readonly originIndex: number;

private readonly filter: LoggerFilter;

public constructor(context?: object, options?: LoggerOptions) {
Expand All @@ -29,6 +31,7 @@ export class Logger {
options?.excludeBlackList,
options?.whiteList
);
this.originIndex = options?.originIndex ?? 3;
}

public debug(message: string, extra?: object): void {
Expand Down Expand Up @@ -72,7 +75,7 @@ export class Logger {
}

protected getOrigin(): string {
const origin = callSites()[3];
const origin = callSites()[this.originIndex];

const methodName = origin.getMethodName();
if (methodName !== null) {
Expand Down
43 changes: 43 additions & 0 deletions test/logger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,49 @@ describe("simple-json-logger", () => {
expect(mock).toBeCalledWith(expectedMessage);
});

it("Should log class and method using originIndex stack level", () => {
// given
const context = {
requestId: faker.random.uuid(),
};
delete process.env.LOG_LEVEL;
const message = faker.lorem.paragraph();
const mock = jest.fn();
const extra = {
name: faker.name.findName(),
};
const expectedMessage = JSON.stringify({
context,
level: "debug",
datetime: new Date().toISOString(),
message: `TestClass.testMethodCaller(): ${message}`,
extra,
});
console.debug = mock;

class TestClass {
private readonly logger: Logger;

public constructor() {
this.logger = new Logger(context, { originIndex: 4 });
}

public testMethod(): void {
this.logger.debug(message, extra);
}

public testMethodCaller(): void {
this.testMethod();
}
}

// when
new TestClass().testMethodCaller();

// then
expect(mock).toBeCalledWith(expectedMessage);
});

it("Should log function name when log from a function", () => {
// given
const context = {
Expand Down

0 comments on commit ea3afe1

Please sign in to comment.