lbx-persistence-logger
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

lbx-persistence-logger

This packages aims to take care of most of your logging concerns, including:

  • nicely formatted output that takes you directly to the error when developing
  • persisting logs in the database

This library was built with customization in mind, so most things can easily be modified.

Usage

Register the component

The minimum required code changes to use the library to its full extend is simply registering it in the application.ts:

import { LbxPersistenceLoggerComponent, LogRepository } from 'lbx-persistence-logger';

export class MyApplication extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
    constructor(options: ApplicationConfig = {}) {
        // ...
        this.component(LbxPersistenceLoggerComponent);
        this.repository(LogRepository);
        // ...
    }
}

If you don't want to use the predefined repositories you can create your own and bind them to the corresponding key in LbxPersistenceLoggerComponentBindings.

Everything above comes from the library out of the box.

(optional) Define a notification service

When your application has a fatal error, you will most likely want to be notified. For this the library provides the LbxPersistenceLoggerComponentBindings.LoggerNotificationService Binding, where you can provide a service for that.

import { BindingScope, bind } from '@loopback/core';
import { Log, LoggerNotificationService } from 'lbx-persistence-logger';

@bind({ scope: BindingScope.TRANSIENT })
export class EmailService implements LoggerNotificationService {
    async notify(log: Log): Promise<void> {
        console.log('Do something with the log')
    }
}

In the application.ts constructor:

this.bind(LbxPersistenceLoggerComponentBindings.LOGGER_NOTIFICATION_SERVICE).toClass(EmailService);

(optional) Define a global logger variable

If you want to use this library just as easy as console.log you can provide a global object. That way you don't need to inject the service all the time:

import { LbxPersistenceLoggerComponentBindings, LoggerService } from 'lbx-persistence-logger';

export let logger: LoggerService;

export async function main(options: ApplicationConfig = {}): Promise<ShowcaseApplication> {
    const app: ShowcaseApplication = new ShowcaseApplication(options);
    await app.boot();
    await app.migrateSchema();
    await app.start();

    // ...
    logger = await app.get(LbxPersistenceLoggerComponentBindings.LOGGER_SERVICE);
    // ...

    const url: string | undefined = app.restServer.url;
    logger.info(`Server is running at ${url}`, `Try ${url}/ping`);

    return app;
}

Create a controller

That's it, now you can use the logger inside your code.

This library does not provide a controller out of the box, because you will probably need to implenent auth and other things.

An example controller could be created like the following:

import { repository } from "@loopback/repository";
import { del, get, getModelSchemaRef, param, post, requestBody } from "@loopback/rest";
import { SecurityBindings, securityId } from '@loopback/security';
import { Log, LogRepository, LogWithRelations } from "lbx-persistence-logger";
import { logger } from "../index";

// ...
export class LogController {

    constructor(
        @repository(LogRepository)
        private readonly logRepository: LogRepository,
    ) { }

    @post('/logs', {
        responses: {
            '200': {
                content: {
                    'application/json': {
                        schema: getModelSchemaRef(Log)
                    }
                }
            }
        }
    })
    async create(
        @requestBody({
            content: {
                'application/json': {
                    schema: getModelSchemaRef(Log, {
                        exclude: ['id', 'createdAt', 'lifetime', 'userId']
                    })
                }
            }
        })
        log: Omit<Log, 'id' | 'createdAt' | 'lifetime' | 'userId'>,
        @inject(SecurityBindings.USER)
        userProfile: UserProfile
    ): Promise<LogWithRelations> {
        return logger.createLogAndNotify(new Date(), log.application, userProfile[securityId], log.level, log.error, log.data)
    }

    @get('/logs', {
        responses: {
            '200': {
                content: {
                    'application/json': {
                        schema: {
                            type: 'array',
                            items: getModelSchemaRef(Log)
                        }
                    }
                }
            }
        }
    })
    async find(): Promise<Log[]> {
        return this.logRepository.find();
    }

    @del('/logs/{id}')
    async deleteById(
        @param.path.string('id')
        id: string
    ): Promise<void> {
        await this.logRepository.deleteById(id);
    }
}

(optional) Use global error logging

If you want to log all errors that occur, you can use the provided LbxLogErrorProvider:

// application.ts
import { LbxLogErrorProvider } from 'lbx-persistence-logger';

constructor() {
    //...
    this.bind(RestBindings.SequenceActions.LOG_ERROR).toProvider(LbxLogErrorProvider);
    //...
}

Customization

The library is highly customizable through the usage of Bindings:

import { LbxInvoiceBindings } from 'lbx-persistence-logger';
// ...
Binding.bind(LbxPersistenceLoggerComponentBindings.LOGGER_SERVICE).toClass(MyCustomLoggerService),
// ...

All bindings can be accessed under LbxPersistenceLoggerComponentBindings.

Package Sidebar

Install

npm i lbx-persistence-logger

Weekly Downloads

1

Version

0.0.2

License

MIT

Unpacked Size

91.5 kB

Total Files

68

Last publish

Collaborators

  • tim-fabian