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

loopback-log-extension

v1.0.14

Published

loopback log extension

Downloads

19

Readme

loopback-log-extension

log extension for LoopBack 4

Install npm i loopback-log-extension --save or yarn add loopback-log-extension

Overview

This repository shows you how to use @loopback/cli to write a complex logging extension that requires a Component, Decorator, and a Mixin.

To use this extension you can add the LogMixin to your Application which will provide you a function to set the Application wide log level as well as automatically load the LogComponent. Only Controller methods configured at or above the logLevel will be logged.

You may alternatively load LogComponent yourself and set the log level using the appropriate binding keys manually if you don't wish to use the LogMixin.

Possible levels are: DEBUG < INFO < WARN < ERROR < OFF

Possible levels are represented as numbers but users can use LOG_LEVEL.${level} to specify the value instead of using numbers.

A decorator enables you to set the log level for Controller methods, at or above which it should be logged.

Usage

1. Create datasource to save token

Sample:

datasources/token.datasource.config.json file

{
    "name": "token",
    "connector": "memory",
    "localStorage": "",
    "file": "../../data/token.json"
}

datasources/token.datasource.ts file

import {
  inject,
  lifeCycleObserver,
  LifeCycleObserver,
  ValueOrPromise,
} from '@loopback/core';
import { juggler } from '@loopback/repository';
import config from './token.datasource.config.json';
import * as path from 'path'

interface TokenDataSourceInterFace {
  name: string
  connector: string
  localStorage: string
  file: string
}

@lifeCycleObserver('datasource')
export class TokenDataSource extends juggler.DataSource
  implements LifeCycleObserver {
  static dataSourceName = 'token';

  constructor(
    @inject('datasources.config.token', { optional: true })
    dsConfig: TokenDataSourceInterFace = config,
  ) {
    const newPath = path.join(__dirname, dsConfig.file)
    dsConfig.file = newPath
    super(dsConfig);
  }

  /**
   * Start the datasource when application is started
   */
  start(): ValueOrPromise<void> {
    // Add your logic here to be invoked when the application is started
  }

  /**
   * Disconnect the datasource when application is stopped. This allows the
   * application to be shut down gracefully.
   */
  stop(): ValueOrPromise<void> {
    return super.disconnect();
  }
}
2. Create Token Repository

repositories/token.repository.ts file

import { DefaultCrudRepository } from '@loopback/repository';
import { Token, TokenRelations } from 'loopback-elog-extention';
import { TokenDataSource } from '../datasources';
import { inject } from '@loopback/core';

export class TokenRepository extends DefaultCrudRepository<
  Token,
  typeof Token.prototype.id,
  TokenRelations
  > {
  constructor(@inject('datasources.token') dataSource: TokenDataSource) {
    super(Token, dataSource);
  }
}

In application.ts file

import {LogMixin, LOG_BINDINGS} from 'loopback-log-extension';
import { TokenRepository } from './repositories';
// Other imports ...

class LogApp extends LogMixin(BootMixin(RestApplication)) {
  constructor(options?: ApplicationConfig) {
    super(options);

    this.projectRoot = __dirname;
    this.configure(LOG_BINDINGS.COMPONENT).to({
      enableElog: true
    })
    this.configure(LOG_BINDINGS.LOGGER).to({
      url: '${url_elog}',
      username: '${elog_username}',
      password: '${elog_password}',
      appCode: '${elog_appcode}',
      tokenRepo: TokenRepository
    })
  }
}

In controllers/my.controller.ts file

...

import {
  LOG_LEVEL,
  LOG_BINDINGS,
  ElogService,
  log
} from 'loopback-elog-extention';
class MyController {
  constructor(
    @inject(LOG_BINDINGS.LOGGER)
    private logger: ElogService
  ) { }

  @log({
    level: LOG_LEVEL.WARN,
    description: 'description for log',
    fn: {
      code: 'function code',
      name: 'function name'
    },
    // function parse request param for save to log
    parseInfo: () => {},
    // function parse result of method to get status of request and result code
    parseResult: result => { //result of method
      return {
        status: result.status,
        resultCode: result.responseCode
      }
    }
  })
  @get('/')
  hello() {
    ...
    this.logger.addTimeLine('test,', true, 'abc.txt', 'abc')
    ...
    return {
      status: true,
      resultCode: 'I001'
    };
  }
}

In sequence.ts file

...

import { LOG_BINDINGS, LogFn } from './loopback-elog-extention'
export class MySequence implements SequenceHandler {
  constructor(
    ...
    @inject(LOG_BINDINGS.LOG_ACTION)
    protected log: LogFn
  ) { }

  async handle(context: RequestContext) {
    try {
      const { request, response } = context;
      const route = this.findRoute(request);

      const args = await this.parseParams(request, route);
      const result = await this.invoke(route, args);
      this.send(response, result);

      this.log(request, args[0], result, true)
    } catch (err) {
      this.reject(context, err);
      this.log(context.request, context.request.body, err, false)
    }
  }
}