9

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?

5
  • did you tried using the different levels of logging like info, log, debug, etc.? Does it not give you required information?
    – KKS
    Jan 9, 2018 at 16:54
  • Yes I've tried but I they wouldn't help. Jan 11, 2018 at 4:19
  • Why not use console.log(...)? Jan 14, 2018 at 6:42
  • Cause if you use angular2-logger you can switch it off and on so easily with changing just one line. in large projects you cant use console.log() @junior-gantin Jan 14, 2018 at 6:46
  • @ValaKhosravi check the answer Jan 16, 2018 at 16:58

3 Answers 3

3

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);
        }
    }
}
3
+50

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.

0

You are using Logger's info method which is least verbose. There is no way to configure it in such way as you'd want to. The alternative is to use error and warning methods - they provide stack trace with filename and line number.

Logs in console from Angular2-logger methods

1
  • 2
    Sorry but I can't change all infos to warring or error Jan 11, 2018 at 4:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.