dbfannin / ngx-logger

Angular logger
MIT License
428 stars 110 forks source link

Setting log level for a specific service #287

Closed JanPhill closed 2 years ago

JanPhill commented 2 years ago

Hi, thank you very much for fixing #282.

Setting the log level for a specific component works fine now by directly providing the logger service to the component.

Could you please provide an example how the same behaviour can be achieved for services? For example I would like to set the log level for one service to TRACE and for another service to ERROR.

Thanks, Jan

bmtheo commented 2 years ago

You should look into angular DI to see how this can be done (I don't know it myself)

Starting path can be this SO post : https://stackoverflow.com/a/35758310/9880876

spyro2000 commented 2 years ago

I tried it this way:

logger.updateConfig({...logger.getConfigSnapshot(), level: NgxLoggerLevel.TRACE})

But it seems like it changed the config globally, not only for this logging instance.

It would be great if I could just use something simple as

log.setLogLevelFor(this, NgxLoggerLevel.TRACE) (just a suggestion, doesn't work as ngx-logger would need to store the caller into an internal map and than taking this info into account later when deciding wheter to log or not later)

bmtheo commented 2 years ago

@spyro2000 this is not exactly what @JanPhill asked

Your code works to change log level but @JanPhill wants to change it only in one service

For this to work, the instance needs to be specific to the service, and Angular DI should allow us to do that

bmtheo commented 2 years ago

Ok here is a way to do it (you need to have version 5.0.10 for this syntax to work)

@Injectable({
  providedIn: 'root'
})
export class BusinessService {
  private logger: NGXLogger;

  constructor(
    customNgxLoggerService: CustomNGXLoggerService,
  ) {
    this.logger = customNgxLoggerService.getNewInstance();

    const modifiedConfig = this.logger.getConfigSnapshot();
    modifiedConfig.level = NgxLoggerLevel.TRACE;
    this.logger.updateConfig(modifiedConfig);
  }

  doBusiness(): void {

    // Even if the appmodule has set ERROR level, this should be printed because we are using local instance of logger
    // And for that local instance the level is set to TRACE
    this.logger.trace('I do business');

    // Do stuff
  }
}
spyro2000 commented 2 years ago

Hi @bmtheo,

thanks for your code. But where is this CustomNGXLoggerService coming from?

bmtheo commented 2 years ago

It should come from ngx-logger, don't you have it ?