2023-07-22 11:03:56 +00:00
|
|
|
import { useStore } from '@nanostores/react';
|
2023-04-29 06:50:54 +00:00
|
|
|
import { createSelector } from '@reduxjs/toolkit';
|
2023-07-22 11:03:56 +00:00
|
|
|
import { createLogWriter } from '@roarr/browser-log-writer';
|
2023-04-29 06:50:54 +00:00
|
|
|
import { useAppSelector } from 'app/store/storeHooks';
|
|
|
|
import { systemSelector } from 'features/system/store/systemSelectors';
|
|
|
|
import { isEqual } from 'lodash-es';
|
|
|
|
import { useEffect } from 'react';
|
2023-07-22 11:03:56 +00:00
|
|
|
import { ROARR, Roarr } from 'roarr';
|
|
|
|
import { $logger, BASE_CONTEXT, LOG_LEVEL_MAP } from './logger';
|
2023-04-29 06:50:54 +00:00
|
|
|
|
|
|
|
const selector = createSelector(
|
|
|
|
systemSelector,
|
|
|
|
(system) => {
|
2023-07-22 11:03:56 +00:00
|
|
|
const { consoleLogLevel, shouldLogToConsole } = system;
|
2023-04-29 06:50:54 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
consoleLogLevel,
|
2023-04-29 07:55:39 +00:00
|
|
|
shouldLogToConsole,
|
2023-04-29 06:50:54 +00:00
|
|
|
};
|
|
|
|
},
|
|
|
|
{
|
|
|
|
memoizeOptions: {
|
|
|
|
resultEqualityCheck: isEqual,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
export const useLogger = () => {
|
2023-07-22 11:03:56 +00:00
|
|
|
const { consoleLogLevel, shouldLogToConsole } = useAppSelector(selector);
|
2023-04-29 06:50:54 +00:00
|
|
|
|
|
|
|
// The provided Roarr browser log writer uses localStorage to config logging to console
|
|
|
|
useEffect(() => {
|
2023-04-29 07:55:39 +00:00
|
|
|
if (shouldLogToConsole) {
|
2023-04-29 06:50:54 +00:00
|
|
|
// Enable console log output
|
|
|
|
localStorage.setItem('ROARR_LOG', 'true');
|
|
|
|
|
|
|
|
// Use a filter to show only logs of the given level
|
|
|
|
localStorage.setItem(
|
|
|
|
'ROARR_FILTER',
|
|
|
|
`context.logLevel:>=${LOG_LEVEL_MAP[consoleLogLevel]}`
|
|
|
|
);
|
2023-04-29 07:55:39 +00:00
|
|
|
} else {
|
|
|
|
// Disable console log output
|
|
|
|
localStorage.setItem('ROARR_LOG', 'false');
|
2023-04-29 06:50:54 +00:00
|
|
|
}
|
|
|
|
ROARR.write = createLogWriter();
|
2023-04-29 07:55:39 +00:00
|
|
|
}, [consoleLogLevel, shouldLogToConsole]);
|
2023-04-29 06:50:54 +00:00
|
|
|
|
|
|
|
// Update the module-scoped logger context as needed
|
|
|
|
useEffect(() => {
|
|
|
|
const newContext: Record<string, any> = {
|
2023-07-22 11:03:56 +00:00
|
|
|
...BASE_CONTEXT,
|
2023-04-29 06:50:54 +00:00
|
|
|
};
|
|
|
|
|
2023-07-22 11:03:56 +00:00
|
|
|
$logger.set(Roarr.child(newContext));
|
|
|
|
}, []);
|
2023-04-29 06:50:54 +00:00
|
|
|
|
2023-07-22 11:03:56 +00:00
|
|
|
const logger = useStore($logger);
|
2023-04-29 06:50:54 +00:00
|
|
|
|
2023-07-22 11:03:56 +00:00
|
|
|
return logger;
|
2023-04-29 06:50:54 +00:00
|
|
|
};
|