Mic*_*ick 5 javascript typescript console.log angular
我尝试为我的TypeScript/Angular 2 App制作日志服务.不幸的是,如果我调用console.log,行号是错误的.即使我试着return console.log().
这是我的代码:
LoggerService.ts
export class LoggerService {
log(message) {
// Server-side logging
// [...]
if (clientSideLogging) return console.log(message);
}
}
Run Code Online (Sandbox Code Playgroud)
SomewhereElse.ts
this.logger.log('hello world');
Run Code Online (Sandbox Code Playgroud)
- >显示LoggerService.ts而不是source的行号
You could use the .bind() method to bind window.console to your custom log method and then return the function so that the code is executed within the original scope when it is called.
In doing so, the line number will be preserved when calling the logger service's log method:
class LoggerService {
public log = console.log.bind(window.console);
}
// ...or annotated:
class LoggerService {
public log: (message) => void = console.log.bind(window.console);
}
Run Code Online (Sandbox Code Playgroud)
Then if you want to add in your conditional statement:
class LoggerService {
public log = clientSideLogging ? console.log.bind(window.console) : () => {};
}
Run Code Online (Sandbox Code Playgroud)
Here is an example with the compiled TypeScript code.
除了上面提到的单行解决方案,如果你想在log方法内部实现额外的逻辑,那么你可以使用一个getter,它将返回并调用console.log绑定到的函数window.console.
class LoggerService {
public get log (): Function {
// Implemnt server-side logging
return console.log.bind(window.console);
}
}
Run Code Online (Sandbox Code Playgroud)
如您所知,console.log返回函数很重要,因为当它在另一个作用域内直接调用时,它不会保留行号。
然后,如果您想添加条件语句:
class LoggerService {
public get log (): Function {
const log = console.log.bind(window.console);
// Implemnt server-side logging
return clientSideLogging ? log : () => {};
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用.trace()代替.log().
this.logger.trace('hello world');
这将为您提供原始行号的堆栈跟踪。
https://developer.mozilla.org/en-US/docs/Web/API/Console/trace
| 归档时间: |
|
| 查看次数: |
1226 次 |
| 最近记录: |