@angular-ru/cdk/logger

Lightweight and configurable Angular logger

import { LoggerModule } from '@angular-ru/cdk/logger';
...

@NgModule({
 imports: [
    LoggerModule.forRoot()
 ],
 ...
})
export class AppModule {}

Motivation

This logger is a handy tool that can be useful in the design and development of the enterprise application level. Easy setting of logging levels and convenient work with groups. Among other things, you can use meta programming (decorators).

Table of contents

Logging

$ npm install @angular-ru/cdk --save
import { LoggerModule } from '@angular-ru/cdk/logger';
...

@NgModule({
 imports: [
    LoggerModule.forRoot()
 ],
 ...
})
export class AppModule {}

Online demo: https://angular-ru.github.io/angular-ru-logger-example-app/

Example: basic methods

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.trace('trace is worked', 1, { a: 1 });
        this.logger.debug('debug is worked', 2, {});
        this.logger.info('info is worked', 3, Object);
        this.logger.warn('warn is worked', 4, String);
        this.logger.error('error is worked', 5, (2.55).toFixed());
    }
}
  • Default level: All

  • Disable trace on console (filter):

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.group('Show trace in opened group', ({ trace }: LoggerService): void => {
            for (let i: number = 0; i < 20; i++) {
                trace('trace is worked', i);
            }
        });
    }
}

Example: groups

  • Logger groups with auto closed (usage callback):

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.groupCollapsed('EXAMPLE 2: show stack', () => {
            this.logger.trace('trace is worked', 1, { a: 1 });
            this.logger.debug('debug is worked', 2, console);
            this.logger.info('info is worked', 3, Object);
            this.logger.warn('warn is worked', 4, String);
            this.logger.error('error is worked', 5, (2.55).toFixed());
        });

        this.logger.group('Show trace in opened group', ({ trace }: LoggerService): void => {
            for (let i: number = 0; i < 20; i++) {
                trace('trace is worked', i);
            }
        });

        this.logger.groupCollapsed('Show trace in collapsed group', ({ debug }: LoggerService): void => {
            for (let i: number = 0; i < 15; i++) {
                debug('debug is worked', i);
            }
        });
    }
}

Example: nested groups

  • Logger nested groups (with pipe):

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger
            .groupCollapsed('GROUP TEST')
            .pipe(({ trace, debug, info, warn, error }: LoggerService) => {
                trace('trace is worked');
                debug('debug is worked');
                info('info is worked');
                warn('warn is worked');
                error('error is worked');
            })
            .close();

        this.logger
            .group('A')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .groupCollapsed('B')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .group('C')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .closeAll();
    }
}

Example: set minimal logging level

Basic parameterization

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.trace('trace is worked', 1, { a: 1 });
        this.logger.debug('debug is worked', 2, console);
        this.logger.info('info is worked', 3, Object);
        this.logger.warn('warn is worked', 4, String);
        this.logger.error('error is worked', 5, (2.55).toFixed());

        this.logger.level = LoggerLevel.INFO;
        this.logger.log('Set new logger level');

        this.logger.trace('trace is worked', 1, { a: 1 });
        this.logger.debug('debug is worked', 2, console);
        this.logger.info('info is worked', 3, Object);
        this.logger.warn('warn is worked', 4, String);
        this.logger.error('error is worked', 5, (2.55).toFixed());
    }
}
  • Logger level groups (pretty usage API):

import { LoggerService, LoggerLevel } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.level = LoggerLevel.INFO;

        this.logger.trace
            .group('A')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .close()

            .debug.group('B')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .close()

            .info.group('C')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .close()

            .warn.group('D')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .close()

            .error.group('E')
            .pipe(
                ({ trace }: LoggerService) => trace('trace is worked'),
                ({ debug }: LoggerService) => debug('debug is worked'),
                ({ info }: LoggerService) => info('info is worked'),
                ({ warn }: LoggerService) => warn('warn is worked'),
                ({ error }: LoggerService) => error('error is worked')
            )
            .close();

        this.logger.level = LoggerLevel.ALL;
    }
}

Example: set style line

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.clear();

        this.logger.css('text-transform: uppercase; font-weight: bold').debug('window current ', window);
        this.logger.css('color: red; text-decoration: underline; font-weight: bold').info('It is awesome logger');
        this.logger.debug({ a: 1 });

        this.logger.warn(setStyle);
        this.logger.info('For global configuration, use the constructor parameters');
    }
}

Example: set global style line

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.clear();

        this.logger.css('font-weight: normal; text-decoration: none; font-style: italic').info(3.14);
        this.logger.css('font-weight: normal;').info(3.14);
        this.logger.warn('global format with style!');
    }
}

Example: CSS classes

import { LoggerModule } from '@angular-ru/cdk/logger';

@NgModule({
    // ..
    imports: [
        LoggerModule.forRoot({
            cssClassMap: {
                bold: 'font-weight: bold',
                'line-through': 'text-decoration: line-through',
                'code-sandbox': `
                  color: #666;
                  background: #f4f4f4;
                  border-left: 3px solid #f36d33;
                  font-family: monospace;
                  font-size: 15px;`
            }
        })
    ]
    // ..
})
import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.cssClass('bold line-through').log('JavaScript sucks', 'JavaScript is the best');

        this.logger
            .cssClass('code-sandbox')
            .log('\n   @Component({ .. })' + '\n   export class AppComponent { .. }    \n\n');

        this.logger.cssClass('bold line-through').debug('JavaScript sucks', 'JavaScript is the best');
    }
}
export class AppModule {}

Example: pretty json

import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        // default browser print json
        this.logger.debug('Classic output json', jsonExample);

        // for pretty json usage logger.log method
        this.logger.log(...this.logger.prettyJSON(jsonExample));
    }
}

Example: decorators

import {
    LoggerService,
    Logger,
    DebugLog,
    TraceLog,
    InfoLog,
    WarnLog,
    ErrorLog,
    Log,
    LogFn
} from '@angular-ru/cdk/logger';

export class AppComponent {
    @Logger() public logger: LoggerService;
    @TraceLog() public trace: LogFn;
    @DebugLog() public debug: LogFn;
    @InfoLog() public info: LogFn;
    @ErrorLog() public error: LogFn;
    @WarnLog() public warn: LogFn;
    @Log() public log: LogFn;

    public showExample(): void {
        this.logger.clear();
        this.logger.log('log is worked');
        this.trace('trace is worked', 1, { a: 1 });
        this.debug('debug is worked', 2, console);
        this.info('info is worked', 3, Object);
        this.warn('warn is worked', 4, String);
        this.error('error is worked', 5, (2.55).toFixed());
    }
}

Example: decorator groups

import { LoggerService, Logger, LoggerLevel, Group } from '@angular-ru/cdk/logger';

export class AppComponent {
    @Logger() public logger: LoggerService;

    @Group('test title', LoggerLevel.WARN)
    private helloWorld(name: string): string {
        this.logger.log('log only in group', name);
        return 'hello world';
    }

    public showExample11(): void {
        this.logger.log(this.helloWorld('Hello'));
    }
}

Example: decorator group with function title

import { Log, LogFn, Group } from '@angular-ru/cdk/logger';

export class AppComponent {
    @Log() public log: LogFn;

    @Group((name: string) => `Test group with ${name}`)
    public method(name: string): string {
        this.log('group is worked');
        return name;
    }

    public showExample(): void {
        this.method('hello world');
    }
}

Example: timer decorator

import { Log, LogFn, TimerLog, LoggerLevel, LoggerService, Logger } from '@angular-ru/cdk/logger';
export class AppComponent {
    @Log() public log: LogFn;
    @Logger() public logger: LoggerService;

    @TimerLog('Test timer')
    public showExample(): void {
        this.logger.clear();
        this.log('test log');
    }

    @TimerLog('Advanced timer', LoggerLevel.WARN, false)
    public showExample(): void {
        this.logger.clear();
        this.log('Advanced test log');
    }
}

Example: format output

import { LoggerModule, NgModule, FormatOutput } from '@angular-ru/cdk/logger';

@NgModule({
    //..
    imports: [
        LoggerModule.forRoot({
            format(label: string, labelStyle: string): FormatOutput {
                const date = new Date().toLocaleString('ru-RU').replace(',', '');
                const customLabel: string = `${date} ${label}`;
                return { label: customLabel, style: labelStyle };
            }
        })
    ]
})
export class AppModule {}
import { LoggerService, OnInit } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {
    constructor(private readonly logger: LoggerService) {}

    public ngOnInit(): void {
        this.logger.trace('trace is worked', 1, { a: 1 });
        this.logger.debug('debug is worked', 2, {});
        this.logger.info('info is worked', 3, Object);
        this.logger.warn('warn is worked', 4, String);
        this.logger.error('error is worked', 5, (2.55).toFixed());
    }
}

Example: full configurations

import { LoggerModule, NgModule, LoggerLevel } from '@angular-ru/cdk/logger';

@NgModule({
    // ..
    imports: [
        LoggerModule.forRoot({
            useLevelGroup: true,
            globalLineStyle: 'color: red; text-decoration: underline; font-weight: bold; font-size: 15px',
            cssClassMap: {
                bold: 'font-weight: bold',
                'line-through': 'text-decoration: line-through',
                'code-sandbox': `
                  color: #666;
                  background: #f4f4f4;
                  border-left: 3px solid #f36d33;
                  font-family: monospace;
                  font-size: 15px;`
            },
            labelNames: {
                [LoggerLevel.TRACE]: '[trace]',
                [LoggerLevel.DEBUG]: '[debug]',
                [LoggerLevel.INFO]: '[info]',
                [LoggerLevel.WARN]: '[warn]',
                [LoggerLevel.ERROR]: '[error]'
            },
            labelColors: {
                [LoggerLevel.TRACE]: 'violet',
                [LoggerLevel.DEBUG]: 'black',
                [LoggerLevel.INFO]: 'tomato',
                [LoggerLevel.WARN]: 'green',
                [LoggerLevel.ERROR]: 'cyan'
            }
        })
    ]
    // ..
})
export class AppModule {}
import { LoggerService } from '@angular-ru/cdk/logger';

export class AppComponent implements OnInit {

  public ngOnInit(): void {
    constructor(private readonly logger: LoggerService) {}

    public showExample(): void {
        this.logger.log('Example');
        this.logger.trace('trace is worked', 1, { a: 1 });
        this.logger.debug('debug is worked', 2, console);
        this.logger.info('info is worked', 3, Object);
        this.logger.warn('warn is worked', 4, String);
        this.logger.error('error is worked', 5, (2.55).toFixed());
    }
}

Todo

Authors

Eleonora Zbarskaya, Ivanov Maxim

Last updated