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';
|
2023-08-22 11:14:11 +00:00
|
|
|
import { useEffect, useMemo } from 'react';
|
2023-07-22 11:03:56 +00:00
|
|
|
import { ROARR, Roarr } from 'roarr';
|
2023-12-28 13:03:21 +00:00
|
|
|
|
|
|
|
import type { LoggerNamespace } from './logger';
|
|
|
|
import { $logger, BASE_CONTEXT, LOG_LEVEL_MAP, logger } from './logger';
|
2023-04-29 06:50:54 +00:00
|
|
|
|
2023-08-22 11:14:11 +00:00
|
|
|
export const useLogger = (namespace: LoggerNamespace) => {
|
2024-01-05 09:39:13 +00:00
|
|
|
const consoleLogLevel = useAppSelector((s) => s.system.consoleLogLevel);
|
|
|
|
const shouldLogToConsole = useAppSelector((s) => s.system.shouldLogToConsole);
|
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(() => {
|
2023-07-22 13:26:14 +00:00
|
|
|
// TODO: type this properly
|
|
|
|
//eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2023-04-29 06:50:54 +00:00
|
|
|
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-08-22 11:14:11 +00:00
|
|
|
const log = useMemo(() => logger(namespace), [namespace]);
|
2023-04-29 06:50:54 +00:00
|
|
|
|
2023-08-22 11:14:11 +00:00
|
|
|
return log;
|
2023-04-29 06:50:54 +00:00
|
|
|
};
|