gpt4 book ai didi

javascript - ExpressJS 中记录器模块定义的问题

转载 作者:行者123 更新时间:2023-12-03 07:24:49 36 4
gpt4 key购买 nike

我有我的nodejs项目,我想将记录器与我的route.js分开以获得干净的代码。

但是我遇到了下一个问题,当我尝试将记录器加载到route.js 文件时,它会显示下一个错误:

TypeError: loggers.getTicketLogger is not a function
at Object.<anonymous> (/home/ismael/projects/nodejs-ticketing/routes/ticket.js:3:23)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/ismael/projects/nodejs-ticketing/server.js:49:1)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:141:18)
at node.js:933:3

我的记录器目录中有下一个代码:

loggers/ticket.js

var log4js = require('log4js');

module.exports = function(){

getTicketLogger = function(){
var logger = null;

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(__dirname + '/../log/ticket.log'), 'ticket-log');

logger = log4js.getLogger('ticket-log');
logger.setLevel('DEBUG');

return logger;
}

};

我的route.js 文件有下一个头

routes/ticket.js

var Ticket  = require('../models/ticket'),
loggers = require('../loggers/ticket.js'),
log = loggers.getTicketLogger();

module.exports = function(app){
}

我做错了什么,以及如何改进代码以将记录器与route.js 文件分开。

谢谢你。

最佳答案

loggers/ticket.js 应返回一个具有 getTicketLogger 方法的对象。

var log4js = require('log4js');

module.exports = function() {

var getTicketLogger = function(){
var logger = null;

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(__dirname + '/../log/ticket.log'), 'ticket-log');

logger = log4js.getLogger('ticket-log');
logger.setLevel('DEBUG');

return logger;

}

return { getTicketLogger: getTicketLogger };

};

然后在routes/ticket.js

var loggers = require('./../loggers/ticket.js')();
var log = loggers.getTicketLogger;

typeof loggers; // => object
typeof log; // => function

关于javascript - ExpressJS 中记录器模块定义的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36044638/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com