Skip to content

Commit

Permalink
fix: defer aynsc_hooks warning (fixes #50)
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Jul 27, 2021
1 parent 331289d commit 51be614
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 4 deletions.
17 changes: 17 additions & 0 deletions src/factories/createLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import type {
TranslateMessageFunction,
} from '../types';

let loggedWarning = false;

const globalThis = createGlobalThis();

const getAsyncLocalContext = () => {
Expand Down Expand Up @@ -167,6 +169,21 @@ const createLogger = (
const asyncLocalStorage = globalThis.ROARR.asyncLocalStorage;

if (!asyncLocalStorage) {
if (loggedWarning === false) {
loggedWarning = true;

onMessage({
context: {
logLevel: logLevels.warn,
package: 'roarr',
},
message: 'async_hooks are unavailable; Roarr.child will not function as expected',
sequence: getSequence(),
time: Date.now(),
version: ROARR_LOG_FORMAT_VERSION,
});
}

return routine();
}

Expand Down
6 changes: 2 additions & 4 deletions src/factories/createRoarrInitialGlobalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ export default (currentState: any): RoarrGlobalState => {
...createNodeWriter(),
asyncLocalStorage,
};
} catch {
// eslint-disable-next-line no-console
console.warn('async_hooks are unavailable; Roarr.child will not function as expected');
}
// eslint-disable-next-line no-empty
} catch {}
}

return newState;
Expand Down
35 changes: 35 additions & 0 deletions test/roarr/asyncLocalScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,41 @@ const createLoggerWithHistory = () => {
return log;
};

serial('warns if async_hooks are unavailable', async (t) => {
const firstLog = createLoggerWithHistory();

const log = firstLog.child({
// Ensure that we are not adding context to the internal warning.
foo: 'bar',
});

globalThis.ROARR.asyncLocalStorage = null;

await log.adopt(
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
);

// Ensure that we log only once.
await log.adopt(
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
);

t.deepEqual(firstLog.messages, [
{
context: {
logLevel: 40,
package: 'roarr',
},
message: 'async_hooks are unavailable; Roarr.child will not function as expected',
sequence: '0',
time,
version,
},
]);
});

serial('inherits context from async local scope', async (t) => {
const log = createLoggerWithHistory();

Expand Down

0 comments on commit 51be614

Please sign in to comment.