我正在使用Loopback3,并试图记录项目文件夹之外的共享模型的消息。我的项目文件夹结构如下
myprojserverlogger.js // using winston logger here
myProjcommonmodels // I've couple of models here and able to use above logger
此外,我在myproj文件夹(../../shared/models(之外还有一些模型。下面是我的server\model-config.json
"sources": [
"loopback/common/models",
"loopback/server/models",
"../common/models",
"../../shared/models", // Shared models
"./models"
],
Person位于共享模型文件夹中。如何将记录器对象传递给此。
module.exports = function(Person){
Person.greet = async function(msg) {
logger.info("received message: " + msg); // How to get here above winston logger object ?
console.log("received message: " + msg);
return 'Greetings... ' + msg;
}
Person.remoteMethod('greet', {
accepts: {arg: 'msg', type: 'string'},
returns: {arg: 'greeting', type: 'string'}
});
};
当您的环回模型分布在多个目录甚至存储库中时,可能会有些混乱。从附加到环回实例对象的静态全局引用中控制台常见部分(如记录器、验证、utils等(始终是一种很好的做法。此环回实例对象作为对其所有模型的引用而存在。我解决这个问题的方法是…
- 在环回3项目中添加一个新的启动脚本,并将
logger
类的实例附加到环回的app
实例
'use strict';
const { logger } = require("./logger");
module.exports = function (app) {
app.logger = logger;
};
- 现在,只要需要,您就可以从模型上的
app
引用中访问它
Person.greet = async function(msg) {
Person.app.logger.info("received message: " + msg);
return 'Greetings... ' + msg;
}
我确实喜欢下面的
在server\server.js 中
const {logger} = require("./logger");
app.start = function() {
return app.listen(function() {
app.emit('started');
:
:
app.models.Person.logger = logger; // Adding new property to Person model
});
};
在人员模型中
Person.greet = async function(msg) {
Person.logger.info("received message: " + msg); // using logger object like this
this.logger.info("received message: " + msg); // or like this
console.log("received message: " + msg);
return 'Greetings... ' + msg;
}