Article

Scalable Logging for Angular?

AOAnonymous One· Sep 1, 20221 min read
  • #Angular
  • #TypeScript
  • #Angular Material
  • #Console Log
  • #Logging

Scalable Logging for Angular?

Two simple solutions to handle console logging for your Angular Production application.

Remove console logs from Angular production application with a one liner.

It is most likely really common for any application to use logging and a quick solution some may use is console.log(). The only problem is you do not want end-users to see the logs so here is a solution to only show console logs in development of an Angular application.

Filename: main.ts

if (environment.production) {window.console.log = () = => {}}

The method above will overwrite all console logs and tell them to do nothing.

If you would like a more appealing solution that is a little more scalable, we will create a service for logging.

Filename: console-logger.service.ts

import { Injectable } from '@angular/core';
import {Logger} from "../interfaces/logger";
import {environment} from "../../../environments/environment";
import {MatSnackBar} from "@angular/material/snack-bar";

@Injectable({providedIn: 'root'})
export class ConsoleLoggerService implements Logger {
  readonly isInProduction: boolean;

  constructor(private snackBar: MatSnackBar) {
    this.isInProduction = environment.production;
  }

  public info(value: any, ...restOfError: any[]): void {
    if (!this.isInProduction) {console.info(value, restOfError)}
    this.openSnackBar(value, 'info')
  }

  public log(value: any, ...restOfError: any[]): void {
    if (!this.isInProduction) {console.log(value, restOfError)}
    this.openSnackBar(value, 'log')
  }

  public warn(value: any, ...restOfError: any[]): void {
    if (!this.isInProduction) {console.warn(value, restOfError)}
    this.openSnackBar(value, 'warn')
  }

  public error(value: any, ...restOfError: any[]): void {
    if (!this.isInProduction) {console.error(value, restOfError)}
    this.openSnackBar(value, 'error')
  }

  private openSnackBar(message: string, className: 'info' | 'log' | 'warn' | 'error'): void {
    this.snackBar.open(message, 'OK', {
      duration: 5000,
      horizontalPosition: 'center',
      verticalPosition: 'bottom',
      panelClass: className
    });
  }
}

Now every time you need to log something, just use this service. It will console log, warn, info, or error if not in production. If in production, it will display a simple message using Angular Material snackbar component.

0 Comments

Sign in to join the conversation.

Search

Jump to a page, story or project