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.length <= metadatas.scopedLoggerInjectableParam ||
!(args[metadatas.scopedLoggerInjectableParam] instanceof ScopedLogger) !(args[metadatas.scopedLoggerInjectableParam] instanceof ScopedLogger)
) { ) {
args[metadatas.scopedLoggerInjectableParam] = new ScopedLogger( args[metadatas.scopedLoggerInjectableParam] = ScopedLogger.fromRoot(baseLogger, key);
baseLogger,
key,
true,
true,
);
} else { } else {
args[metadatas.scopedLoggerInjectableParam] = new ScopedLogger( args[metadatas.scopedLoggerInjectableParam] = ScopedLogger.fromSuper(baseLogger, args[metadatas.scopedLoggerInjectableParam], key);
args[metadatas.scopedLoggerInjectableParam],
key,
false
);
} }
injectedLogger = args[metadatas.scopedLoggerInjectableParam]; injectedLogger = args[metadatas.scopedLoggerInjectableParam];

View File

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