Skip to content

Commit

Permalink
feat: add store manager logger
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewPattell committed Aug 7, 2024
1 parent 565ded4 commit 954d037
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 12 deletions.
7 changes: 1 addition & 6 deletions src/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,7 @@ const StoreManagerProvider: FC<IStoreManagerProvider> = ({
return;
}

storeManager
.init()
.then(() => setInit(true))
.catch((e: Error) => {
console.error('Failed initialized store manager: ', e);
});
void storeManager.init().then(() => setInit(true));
}, [shouldInit, storeManager]);

return (
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ export { default as withStores } from './with-stores';
export * from './make-exported';

export { default as Events } from './events';

export { default as Logger } from './logger';
96 changes: 96 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import type Manager from './manager';

export interface ILoggerOpts {
/**
* 0 - disabled
* 1 - error
* 2 - warning
* 3 - info
* 4 - debug
*/
level: number;
manager: Manager;
}

export interface ILoggerLogOpts {
level: ILoggerOpts['level'];
err?: Error;
payload?: Record<string, any>;
}

class Logger {
/**
* Logger options
*/
protected options: ILoggerOpts;

/**
* @constructor
*/
constructor(opts: ILoggerOpts) {
this.options = opts;
}

/**
* Log message
*/
public log(msg: string, { level, err, payload }: ILoggerLogOpts): void {
if (this.options.level < level) {
return;
}

let type = 'log';

switch (level) {
case 1:
type = 'error';
break;

case 2:
type = 'warn';
break;

case 3:
type = 'info';
break;
}

console[type](...[msg, err, payload].filter(Boolean));
}

/**
* Log error message
*/
public err(msg: string, err?: unknown, payload?: Record<string, any>): void {
this.log(msg, { err: err as Error, level: 1, payload });
}

/**
* Log warning message
*/
public warn(msg: string, payload?: Record<string, any>): void {
this.log(msg, { level: 2, payload });
}

/**
* Log info message
*/
public info(msg: string, payload?: Record<string, any>): void {
this.log(msg, { level: 3, payload });
}

/**
* Log debug message
*/
public debug(msg: string, payload: Record<string, any> = {}, hasSnapshot = false): void {
if (hasSnapshot) {
payload.additional = {
relations: Object.fromEntries(this.options.manager.getStoresRelations().entries()),
};
}

this.log(`DEBUG: ${msg}`, { level: 4, payload: { ...payload } });
}
}

export default Logger;
34 changes: 28 additions & 6 deletions src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { isObservableProp, toJS } from 'mobx';
import { ROOT_CONTEXT_ID } from './constants';
import deepMerge from './deep-merge';
import Events from './events';
import Logger from './logger';
import {
isPropExcludedFromExport,
isPropObservableExported,
Expand Down Expand Up @@ -82,12 +83,21 @@ class Manager {
*/
protected suspenseRelations: Map<string, Set<string>> = new Map();

/**
* Mobx manager logger
*/
protected readonly logger: Logger;

/**
* @constructor
*/
public constructor({ initState, storesParams, storage, options }: IManagerParams = {}) {
public constructor({ initState, storesParams, storage, options, logger }: IManagerParams = {}) {
this.initState = initState || {};
this.storesParams = storesParams || {};
this.logger =
logger && 'log' in logger
? logger
: new Logger({ level: 3, ...(logger ?? {}), manager: this });
this.storage =
storage instanceof CombinedStorage
? storage
Expand All @@ -113,8 +123,12 @@ class Manager {
* Init store manager
*/
public async init(): Promise<Manager> {
if (this.storage) {
await this.storage.get();
try {
if (this.storage) {
await this.storage.get();
}
} catch (e) {
this.logger.err('Failed initialized store manager: ', e);
}

return this;
Expand Down Expand Up @@ -171,7 +185,6 @@ class Manager {

/**
* Get store identity
* @protected
*/
protected getStoreId<T extends TAnyStore>(
store: IConstructableStore<T> | TInitStore,
Expand Down Expand Up @@ -241,7 +254,7 @@ class Manager {
if (matchedIds.length === 1) {
return this.stores.get(matchedIds[0]);
} else if (matchedIds.length > 1) {
console.error(
this.logger.err(
'Parent context has multiple stores with the same id, please pass key to getStore function.',
);

Expand Down Expand Up @@ -338,6 +351,15 @@ class Manager {
: this.getStoreId(s, { key, contextId }));

if (!storeId) {
const msg = `Cannot find or create store '${key}': '${this.getStoreId(s)}'`;

this.logger.warn(msg);
this.logger.debug(
msg,
{ contextId, parentId, suspenseId, componentName, isParent },
true,
);

return res;
}

Expand Down Expand Up @@ -610,7 +632,7 @@ class Manager {

return true;
} catch (e) {
console.error('Failed to persist stores: ', e);
this.logger.err('Failed to persist stores: ', e);
}

return false;
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type Events from './events';
import type { ILoggerOpts } from './logger';
import type Logger from './logger';
import type Manager from './manager';
import type CombinedStorage from './storages/combined-storage';
import type StoreStatus from './store-status';
Expand Down Expand Up @@ -67,6 +69,7 @@ export interface IManagerParams {
storage?: IStorage | CombinedStorage;
options?: IManagerOptions;
initState?: Record<string, any>;
logger?: Logger | Omit<ILoggerOpts, 'manager'>;
}

export type TWakeup = (state: {
Expand Down

0 comments on commit 954d037

Please sign in to comment.