Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write console.log wrapper for Angular2 in Typescript?

Is there a way to write a global selfmade mylogger function that I could use in Angular2 typescript project for my services or components instead of console.log function ?

My desired result would be something like this:

mylogger.ts

function mylogger(msg){
    console.log(msg);
};

user.service.ts

import 'commons/mylogger';
export class UserService{
  loadUserData(){
    mylogger('About to get something');
    return 'something';
  };
};
like image 965
Andris Krauze Avatar asked Dec 23 '15 14:12

Andris Krauze


2 Answers

You could write this as a service and then use dependency injection to make the class available to your components.

import {Injectable, provide} from 'angular2/core';

// do whatever you want for logging here, add methods for log levels etc.
@Injectable()
export class MyLogger {

  public log(logMsg:string) {
    console.log(logMsg); 
  }
}

export var LOGGING_PROVIDERS:Provider[] = [
      provide(MyLogger, {useClass: MyLogger}),
    ];

You'll want to place this in the top level injector of your application by adding it to the providers array of bootstrap.

import {LOGGING_PROVIDERS} from './mylogger';

bootstrap(App, [LOGGING_PROVIDERS])
  .catch(err => console.error(err));

A super simple example here: http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview

like image 130
Zyzle Avatar answered Oct 09 '22 06:10

Zyzle


The example given by the accepted answer will print logs from the logger class, MyLogger, instead of from the class that is actually logging.

I have modified the provided example to get logs to be printed from the exact line that calls MyLogger.log(), for example:

get debug() {
    return console.debug.bind(console);
}
get log() {
    return console.log.bind(console);
}

I found how to do it here: https://github.com/angular/angular/issues/5458

Plunker: http://plnkr.co/edit/0ldN08?p=preview

As per the docs in developers.mozilla,

The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of 
arguments preceding any provided when the new function is called.

More information about bind here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

like image 24
Francisco C. Avatar answered Oct 09 '22 06:10

Francisco C.