npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lbx-persistence-logger

v7.0.0

Published

Open Source

Downloads

2

Readme

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.