feat: use scope inherit system instead of call chain

This commit is contained in:
p-sw 2024-03-31 19:00:11 +09:00
parent 68fb9e4ac0
commit de0cf81f10
2 changed files with 18 additions and 21 deletions

View File

@ -138,18 +138,9 @@ function overrideBuild<F extends Array<any>, R>(
args.length <= metadatas.scopedLoggerInjectableParam ||
!(args[metadatas.scopedLoggerInjectableParam] instanceof ScopedLogger)
) {
args[metadatas.scopedLoggerInjectableParam] = new ScopedLogger(
baseLogger,
key,
true,
true,
);
args[metadatas.scopedLoggerInjectableParam] = ScopedLogger.fromRoot(baseLogger, key);
} else {
args[metadatas.scopedLoggerInjectableParam] = new ScopedLogger(
args[metadatas.scopedLoggerInjectableParam],
key,
false
);
args[metadatas.scopedLoggerInjectableParam] = ScopedLogger.fromSuper(baseLogger, args[metadatas.scopedLoggerInjectableParam], key);
}
injectedLogger = args[metadatas.scopedLoggerInjectableParam];

View File

@ -6,24 +6,19 @@ const createId = hyperid({ fixedLength: true })
type LogLevel = "debug" | "log" | "warn" | "verbose" | "error" | "fatal";
export class ScopedLogger extends Logger {
private readonly scopeId?: string;
constructor(
private logger: Logger,
private scope: string,
private root: boolean = false,
private createScopeId: boolean = false,
private scope: string[],
private scopeId: string = createId(),
) {
super();
if (this.createScopeId) this.scopeId = createId();
}
private scopedLog(method: LogLevel) {
return (message: string) => {
this.logger[method](
`${this.root ? "" : "-> "}${this.scope}${
this.scopeId ? `(${this.scopeId})` : ""
}: ${message}`
`${this.scopeId ? `(ID ${this.scopeId}) | ` : ""
}${this.scope.join(" -> ")}: ${message}`
);
};
}
@ -34,4 +29,15 @@ export class ScopedLogger extends Logger {
verbose = this.scopedLog("verbose");
error = this.scopedLog("error");
fatal = this.scopedLog("fatal");
}
static fromSuper(baseLogger: Logger, logger: ScopedLogger, scope: string): ScopedLogger {
return new ScopedLogger(
baseLogger, [...logger.scope, scope], logger.scopeId
)
};
static fromRoot(logger: Logger, scope: string): ScopedLogger {
return new ScopedLogger(
logger, [scope]
)
};
}