Skip to content
Open
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
22 changes: 22 additions & 0 deletions src/consola.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@

// Track of last log
this._lastLog = {};

// Prevent infinite loop on logging
// Issue: https://github.com/unjs/consola/issues/298
this._logFn = _preventLoop(this._logFn).bind(this);
}

/**
Expand Down Expand Up @@ -474,6 +478,24 @@
return defaultLevel;
}

function _preventLoop<T extends (this: any, ...args: any[]) => any>(fn: T): T {
let doing = false;
return function (...args) {
if (doing) {
return false;
}
doing = true;
try {
const result = fn.apply(this, args);
doing = false;
return result;
} catch (error) {
doing = false;
throw error;
}

Check warning on line 495 in src/consola.ts

View check run for this annotation

Codecov / codecov/patch

src/consola.ts#L493-L495

Added lines #L493 - L495 were not covered by tests
} as T;
}

export interface LogFn {
(message: InputLogObject | any, ...args: any[]): void;
raw: (...args: any[]) => void;
Expand Down
24 changes: 24 additions & 0 deletions test/consola.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,30 @@ describe("consola", () => {

expect(logs.at(-1)!.args).toEqual(["SPAM", "(repeated 4 times)"]);
});

test("should avoid infinite loop", () => {
const logs: LogObject[] = [];
const TestReporter: ConsolaReporter = {
log(logObj) {
logs.push(logObj);
},
};
const consola = createConsola({
reporters: [TestReporter],
});

consola.wrapConsole();
const obj = {
get value() {
console.warn(obj);
return "anything";
},
};
consola.warn(obj);
consola.restoreConsole();

expect(logs.length).toBe(1);
});
});

function wait(delay) {
Expand Down