How to write a console.log shell for Angular2 in Typescript

Is there a way to write a global selflogy mylogger function that I could use in an Angular2 typescript project for my services or components instead of the 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'; }; }; 
+6
source share
8 answers

You can 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 want to put this in the top-level injector of your application by adding it to the bootstrap providers array.

 import {LOGGING_PROVIDERS} from './mylogger'; bootstrap(App, [LOGGING_PROVIDERS]) .catch(err => console.error(err)); 

The simplest example: http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview

+14
source

In the example presented by the accepted answer, logs will be printed from the log class, MyLogger , and not from the class that is actually being registered.

I modified the above example to get the logs that will 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

According to 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 about bind here:

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

+9
source

If you want to use the console.log function only in your component, you can do this:

 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'); } } 
+2
source

How about using the console on the main service, so we can configure and apply console.log conditionally:

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

(Note: the first parameter should be a string in this example);

+1
source

To switch 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(); } } } 
+1
source

I created a registrar based on the information provided here

It is currently very simple (hacker :-)), but it saves the line number

 @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

+1
source

enter safer (ish) version from angular 4, typescript 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) { //... 
+1
source

NPM now has an angular2 logger component that supports log levels. https://www.npmjs.com/package/angular2-logger

0
source

All Articles