如何在回送4服务器级别实现记录器。对于每个请求,都需要捕获状态码和请求ip。
我尝试使用log4j创建记录器,但是我只能在班级内部调用。 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";
}
}
答案 0 :(得分:0)
我发现通过拦截器我们可以创建日志。
import pandas as pd
year = 2014
while year > 2019:
day = 1
while day < 31:
infile = 'p24i_{0:4.0f}06{1:02.0f}_sortbyvalue.txt'.format(year, day)
data_in = pd.read_csv(infile, skiprows=6, delim_whitespace=True, header=None).values
precip = data_in[:,0]
print(precip)
day+=1
year+=1
在您的类中,添加带有该日志对象的拦截器对象
班级:
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;
}
};
答案 1 :(得分:0)
还有一个概念调用序列,在传递给其余API之前已收到请求
我们也可以在Sequence.ts文件中添加记录器