Javascript 如何在 Typescript 中为 Angular2 编写 console.log 包装器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34437627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write console.log wrapper for Angular2 in Typescript?
提问by Andris Krauze
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 ?
有没有办法编写一个全局自制的 mylogger 函数,我可以在 Angular2 打字稿项目中为我的服务或组件而不是 console.log 函数使用它?
My desired result would be something like this:
我想要的结果是这样的:
mylogger.ts
mylogger.ts
function mylogger(msg){
console.log(msg);
};
user.service.ts
用户服务.ts
import 'commons/mylogger';
export class UserService{
loadUserData(){
mylogger('About to get something');
return 'something';
};
};
回答by Zyzle
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
.
您需要通过将它添加到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
这里有一个超级简单的例子:http: //plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview
回答by Francisco C.
The example given by the accepted answer will print logs from the logger class, MyLogger
, instead of from the class that is actually logging.
接受的答案给出的示例将打印来自 logger 类的日志MyLogger
,而不是来自实际记录的类。
I have modified the provided example to get logs to be printed from the exact line that calls MyLogger.log()
, for example:
我修改了提供的示例,以便从调用 的确切行打印日志MyLogger.log()
,例如:
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
我在这里找到了方法:https: //github.com/angular/angular/issues/5458
Plunker: http://plnkr.co/edit/0ldN08?p=preview
Plunker:http://plnkr.co/edit/0ldN08?p=preview
As per the docs in developers.mozilla,
根据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:
关于bind
这里的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
回答by dapz17
If you want to use 'console.log' function just in your component you can do this:
如果您只想在组件中使用“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');
}
}
回答by Amit Portnoy
type safer(ish) version with angular 4, typescript 2.3
使用 angular 4 输入更安全(ish)版本,打字稿 2.3
logger.service.ts
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
我的模块.ts
// ...
@NgModule({
providers: [
ConsoleLoggerServiceProvider,
//...
],
// ...
my.service.ts
我的.service.ts
// ...
@Injectable()
export class MyService {
constructor(@Inject(LOGGER_SERVICE) log: LoggerService) {
//...
回答by vusan
How about using console on your main service, So we can customize and apply console.log
conditionally:
在你的主服务上使用控制台怎么样,所以我们可以console.log
有条件地自定义和应用:
myComponent.ts
myComponent.ts
export class myComponent implements OnInit {
constructor(
private config: GlobalService
) {}
ngOnInit() {
this.config.log('func name',{a:'aval'},'three');
}
}
global.service.ts
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);
}
}
}
(Note: first parameter should be string in this example);
(注意:在这个例子中第一个参数应该是字符串);
回答by Dudi
For toggling console.log ON\OFF:
要切换 console.log ON\OFF:
logger.service.ts:
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:
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();
}
}
}
回答by urbiwanus
I created a logger based on the provided information here
我根据此处提供的信息创建了一个记录器
Its very basic (hacky :-) ) at the moment, but it keeps the line number
目前它非常基本(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');
}
}
}
}
Hope this helps
希望这可以帮助
回答by BRass
There is now an angular2 logger component on NPM which supports log levels. https://www.npmjs.com/package/angular2-logger
NPM 上现在有一个支持日志级别的 angular2 记录器组件。 https://www.npmjs.com/package/angular2-logger