DEV Community

Cover image for Consistent Console Logs in Angular
ng-conf
ng-conf

Posted on

Consistent Console Logs in Angular

Jared Youtsey | ng-conf | Apr 2019

When you have to log, do it consistently.

Logging is necessary. It allows us to debug in both development and production. But console is disallowed by tslint by default. And for good reason. Console logging is a mess most of the time. If you can just willy-nilly console.log(whatever) then your logs are pretty much useless.

We can end up with too much logging in production, which can slow our application down, and not enough in development where we need more details.

I’ve had to deal with this issue on multiple projects and have written a static logger class in Angular that allows us to control what we log and where.

Here is the gist https://gist.github.com/jkyoutsey/e99336d58c2c83bc0ba03cde78fcc64e

In a nutshell you have the following options:

Logger.(debug|info|warn|error|devOnly|techDebt)(module: string, method: string, message?: any)

debug|info|warn|error will log in all environments unless you also set the optional devOnly: boolean argument to true. Then the module and method will still log, but not the message argument. This allows for tracing without leaking sensitive data in a production environment.

devOnly|techDebt do not have the optional devOnly argument and will only ever log to the console in a non-production environment.

By environment I mean your src/environments/environment.ts’s production property value. If it’s false you’ll get all log statements. If it’s true you’ll only get debug|info|warn|error.

Your output will now be consistently formatted, making it easier to read, parse, or even analyze.

Image for post

Sample Logger Usage

The above commands result in the following output in Chrome DevTools:

Image for post

Readable Console Output

I’ve even created a VisualStudio Code snippet to make it easier:

"Log All The Things": {
    "prefix": "ll",
    "body": [
        "Logger.${LEVEL}('${CLASS}', '${METHOD}', `${message}`);"
    ]
}
Enter fullscreen mode Exit fullscreen mode
logger.ts.vscode.snippet.txt hosted by GitHub

And I’ve got unit tests for it so it won’t impact your coverage (but you shouldn’t worry too much about coverage): https://gist.github.com/jkyoutsey/01e3e2db4ba9a570245bd63d543960e1

If you find this useful or interesting, please clap!


ng-conf: Join us for the Reliable Web Summit

Come learn from community members and leaders the best ways to build reliable web applications, write quality code, choose scalable architectures, and create effective automated tests. Powered by ng-conf, join us for the Reliable Web Summit this August 26th & 27th, 2021.
https://reliablewebsummit.com/

Top comments (0)