Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lbx-persistence-logger

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lbx-persistence-logger

Open Source

  • 0.0.1
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

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 the global error interceptor

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

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

constructor() {
    //...
    this.interceptor(ErrorInterceptorProvider, { global: true, group: 'error-handling' });
    //...
}

WARNING:
The interceptor will NOT rethrow the error. If you use global interceptors on >your own, you need to make sure that the error interceptor is called last (see loopback order of invocation for interceptors).

This is because loopback would otherwise log the error internally => you would have 2 logs for the same error.

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.

Keywords

FAQs

Package last updated on 15 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc