环回 4 的记录器

Logger for loop back 4

如何在环回 4 服务器级别实现记录器。对于每个请求都需要捕获状态码和请求ip。

我曾尝试使用 log4j 创建记录器,但我只能在我的 class 级别内调用。 https://loopback.io/doc/en/lb4/Decorators_inject.html


    *application.ts:*

    const log4js = require('log4js');

    log4js.configure({
    appenders: { cheese: { type: 'file',     filename: 'cheese.log' } },
    categories: { default: { appenders:    ['cheese'], level: 'error' } }
    });
    const logger = log4js.getLogger('cheese');

    //inside application
    app.bind('logger.widget').to(logInfo)
    function logInfo(info: string) {
    logger.info(info);
    }


     *controller.ts class*:

    import {inject} from '@loopback/context';
    export class WidgetController {

    // injection for property
    @inject('logger.widget')
    private logger: Function;

    @get('/hello')
    greet() {
    this.logger("hello request called") 
    return "Hello world";
    }
    }



我发现通过拦截器我们可以创建日志。

var uniqid = require('uniqid');
import { RestBindings } from '@loopback/rest';
import { Interceptor } from '@loopback/context';

log4js.configure({
  appenders: { cheese: { type: 'dateFile', filename: 'cheese.log', pattern: '.yyyy-MM-dd-hh-mm', compress: true } },
  categories: { default: { appenders: ['cheese'], level: 'debug' } }
});

const logger = log4js.getLogger(process.env.NODE_ENV);

logger.info("Application starts and running")
export const log: Interceptor = async (invocationCtx, next) => {
  // Wait until the interceptor/method chain returns
  const req = await invocationCtx.get(RestBindings.Http.REQUEST);
  logger.info("Requestid - " + uniqid() + "| Request IP -" + req.ip);

  try {
    logger.info('Starting - Class-' + invocationCtx.targetClass.name + ' | Method-' + invocationCtx.methodName);
    //logger.debug("Requestid - " + uniqid() + "| Request IP -" + req.ip);
    const result = await next();
    const res = await invocationCtx.get(RestBindings.Http.RESPONSE);

    logger.info('Ending - Class-' + invocationCtx.targetClass.name + ' | Method-' + invocationCtx.methodName);
    logger.info("Response Status Code - " + res.statusCode);

    return result;
  } catch (e) {
    logger.error(e);
    throw e;
  }
};

在您的 class 中添加带有该日志对象的拦截器对象

Class:

import { intercept } from '@loopback/context';
import {Log} from './Log'
  @intercept(log) // `log` is an interceptor function and above object
export class PingController {
//Your code
 }

还有一个称为序列的概念,其中在传递给其余请求之前接收到请求API

我们还可以在 Sequence.ts 文件中添加记录器

参考:https://loopback.io/doc/en/lb4/Sequence.html