I am currently looking at learning Typescript Decorators. My first goal is to somewhat reproduce what @Slf4J from the Project Lombok does in Java to Typescript. The ideas is to annotate/decorate a class with e.g. @logger to receive a field log of type LogUtil within that same class in order to call e.g. log.info().
LogUtil class:
export class LoggerUtil {
logLevel: LogLevel;
constructor(logLevel: LogLevel) {
this.logLevel = logLevel;
}
error(className: string, message: string) {
if (this.logLevel >= LogLevel.ERROR) {
console.error(`${new Date()} [ERROR] ${className}: ${message}`);
}
}
warn(className: string, message: string) {
if (this.logLevel >= LogLevel.WARN) {
console.log(`${new Date()} [WARN] ${className}: ${message}`);
}
}
log(className: string, message: string): void {
console.log(`${new Date()} [LOG] ${className} ${message}`)
}
info(className: string, message: string): void {
if (this.logLevel >= LogLevel.INFO) {
console.log(`${new Date()} [INFO] ${className}: ${message}`)
}
}
call(className: string, message: string) {
if (this.logLevel >= LogLevel.INFO) {
console.log(`${new Date()} [CALL] ${className}.${message}`)
}
}
debug(className: string, message: string) {
if (this.logLevel >= LogLevel.DEBUG) {
console.log(`${new Date()} [DEBUG] ${className}: ${message}`)
}
}
}
LogLevel enum:
export enum LogLevel {
ERROR = 0,
WARN = 1,
INFO = 2,
DEBUG = 3
}
Example class using the @logger decorator to get an instance of LoggerUtil as log
@logger
export class SomeService {
exampleFunction() {
log.info("exampleFunction called")
}
}
I am currently trying to do this with the class-level decorators. Here I am trying to do different things:
Using the Reflect API to define a property on the class. Here I am not even sure if that even works.
export function logger() {
return function(target: Function) {
Reflect.defineProperty(target, "log", { value: new LoggerUtil(LogLevel.DEBUG) } )
}
}
Using the class prototype to define a property:
export function logger() {
return function(target: Function) {
target.prototype.log = new LoggerUtil(LogLevel.DEBUG);
}
}
With every approach I am getting "Cannot find name 'log'" when referencing the log instance within the Service:
@logger
export class SomeService {
exampleFunction() {
log.info("exampleFunction called") // Cannot find name 'log'
}
}
Is my idea possible at all? Is there something fundamental that I am missing?
Thank you vey much in advance for any feedback!