Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show line number and file name using angular2-logger

Tags:

angular

I'm using Angular2-logger inside my project.

import { Logger } from "angular2-logger/core";
...
logger: Logger;
...
logger.info('<log string>')

Output printed in console like image below

enter image description here

Is there any option in Angular2-logger or alternative class that I can use to show file name and line number of where I'm calling logger methods ? (same as console.log(...) like image bellow)

enter image description here

Is there any solution?

like image 587
Vala Khosravi Avatar asked Dec 13 '17 10:12

Vala Khosravi


2 Answers

I figured out the solution by this way:

1- I created a LoggerService.

2- I imported the service to app.module.ts and use it as a provider.

3- LoggerService looks like something like this:

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

@Injectable()
export class LoggerService {
    public error(message) {
        try { throw new Error(); } catch (e) {
            console.log(e.stack);
            const stackTraces = e.stack.split('at');
            const fileList = stackTraces[2].substr(
                stackTraces[2].lastIndexOf('/src'),
                stackTraces[2].length - 1 ).replace(')', ''
            );
            const functionName = stackTraces[2].substr(0, stackTraces[2].indexOf('(') - 1);

            // Do whatever you want, use console.log or angular2-logger service
            console.log(message);
        }
    }
}
like image 144
Roham Rafii Avatar answered Nov 09 '22 23:11

Roham Rafii


I would recommend you not to use any logger libraries for two reasons

  • when angular provides it by default.
  • These libraries are not dependable with the version updates.

As we log the errors on the front end (i.e browser environment), You could make a custom logger service.

Regarding the issue you mentioned, you can switch off the logs by overwriting the service via usevalue with an empty class/function depending on environment that you need.

like image 21
Sajeetharan Avatar answered Nov 10 '22 01:11

Sajeetharan