Logging with angular2-logger in Ionic 2 apps
As far as I am aware Ionic 2 does not yet have any decent logging options. But as Ionic 2 uses AngularJS 2, we can make use of the angular2-logger module
Angular2-logger is a Log4j inspired logger for Angular 2 apps allowing you to set your desired log level (OFF, WARN, ERROR, LOG, DEBUG etc)
I’ve found it best to implement the angular2-logger as a provider in Ionic 2 apps and inject it into your classes rather than instantiating a new instance of the logger for each component in your app.
Once you have the npm module installed, create a LoggerService provider in your app with the following ionic command:
ionic g provider LoggerService
then add the following code to the generated logger-service.ts file
I’m configuring my log level using a config class but you can change the code above to use your own preferred method.
Now you can inject the LoggerService into your component’s like so
And then log messages in your components like this
And add the following references and providers to your app.component.ts file
Now say goodbye to your console.log naffness for good 🙂