Andris Krauze Andris Krauze - 1 year ago 889
Javascript Question

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:


function mylogger(msg){


import 'commons/mylogger';
export class UserService{
mylogger('About to get something');
return 'something';

Answer Source

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.
export class MyLogger {

  public log(logMsg:string) {

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download