如何在Typescript中为Angular2编写console.log包装器?

时间:2015-12-23 14:17:36

标签: javascript typescript angular

有没有办法编写一个全局自制的mylogger函数,我可以在Angular2 typescript项目中使用我的服务或组件而不是console.log函数?

我想要的结果是这样的:

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';
  };
};

8 个答案:

答案 0 :(得分:15)

您可以将其编写为服务,然后使用依赖注入使该类可用于您的组件。

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}),
    ];

您希望将其添加到应用程序的顶级注入器中,方法是将其添加到bootstrap的提供程序数组中。

import {LOGGING_PROVIDERS} from './mylogger';

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

这里有一个非常简单的例子:http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview

答案 1 :(得分:9)

接受的答案给出的示例将打印记录器类MyLogger中的日志,而不是实际记录的类。

我修改了提供的示例,以便从调用MyLogger.log()的确切行中打印日志,例如:

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

我在这里找到了如何做到这一点:https://github.com/angular/angular/issues/5458

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

根据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.

此处有关bind的更多信息:

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

答案 2 :(得分:2)

如果您想在组件中使用“console.log”功能,可以执行以下操作:

import { Component, OnInit } from '@angular/core';

var output = console.log;

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor() { }

  ngOnInit() { }

  printFunction(term: string): void {
    output('foo');
  }
}

答案 3 :(得分:1)

如何在主服务上使用控制台,我们可以有条件地自定义和应用console.log

<强> myComponent.ts

export class myComponent implements OnInit {
 constructor(
        private config: GlobalService
    ) {}

    ngOnInit() {
       this.config.log('func name',{a:'aval'},'three');
    }
}

<强> global.service.ts

@Injectable()
export class GlobalService {

   constructor() { }
   this.prod = true;
   public log(one: any, two?: any, three?: any, four?: any) {
        if (!this.prod) {
             console.log('%c'+one, 'background:red;color:#fff', two, three, four);
        }
    }
}

(注意:在这个例子中,第一个参数应该是字符串);

答案 4 :(得分:1)

用于切换console.log ON \ OFF:

<强> logger.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class LoggerService {

private oldConsoleLog = null;

enableLogger(){

    if (this.oldConsoleLog == null) { return; }

    window['console']['log'] = this.oldConsoleLog;
}

disableLogger() {
    this.oldConsoleLog = console.log;
    window['console']['log'] = function () { };
};

}

<强> app.component.ts:

@Component({
  selector: 'my-app',
  template: `your templ;ate`
})

export class AppComponent {

constructor(private loggerService: LoggerService) {
    var IS_PRODUCTION = true;

    if ( IS_PRODUCTION ) {
        console.log("LOGGER IS DISABBLED!!!");
        loggerService.disableLogger();
    }

}
}

答案 5 :(得分:1)

我根据这里提供的信息创建了一个记录器

目前非常基本(hacky :-)),但它保留了行号

@Injectable()
export class LoggerProvider {

constructor() {
  //inject what ever you want here
}

public getLogger(name: string) {
  return {

    get log() {
      //Transform the arguments 
      //Color output as an example
      let msg = '%c[' + name + ']';
      for (let i = 0; i < arguments.length; i++) {
        msg += arguments[i]
      }

      return console.log.bind(console, msg, 'color:blue');
    }

  }
 }
}

希望这有帮助

答案 6 :(得分:1)

类型更安全(ish)版本,角度为4,打字稿2.3

logger.service.ts

import { InjectionToken } from '@angular/core';

export type LoggerService = Pick<typeof console,
                                 'debug' | 'error' | 'info' | 'log' | 'trace' | 'warn'>;
export const LOGGER_SERVICE = new InjectionToken('LOGGER_SERVICE');
export const ConsoleLoggerServiceProvider = { provide: LOGGER_SERVICE, useValue: console };

my.module.ts

// ...
@NgModule({
  providers: [
    ConsoleLoggerServiceProvider,
    //...
  ],
// ...

my.service.ts

// ...
@Injectable()
export class MyService {

  constructor(@Inject(LOGGER_SERVICE) log: LoggerService) {
//...

答案 7 :(得分:0)

NPM上现在有一个angular2记录器组件,它支持日志级别。 https://www.npmjs.com/package/angular2-logger