使用log4js运行logger.js时,logger.setLevel不起作用

时间:2019-03-08 11:24:53

标签: javascript node.js express logging log4js-node

我正在尝试使用log4js创建日志文件。完成所有配置后运行node app.js时,出现以下错误。

错误:

TypeError: logger.setLevel is not a function
at Object.<anonymous> (E:\Angular\logging_project\routes\logger.js:14:20)
at Object.<anonymous> (E:\Angular\logging_project\routes\index.js:3:13)

请看一下我的代码。

logger.js

  var log4js = require('log4js');
  log4js.configure({
     appenders: {
        console: { type: 'console' },
        filelog: { type: 'file', filename: "c://test.log", category: 'my_project' }
      },
      categories: {
         file: { appenders:['filelog'],level:'error'},
         another: {appenders: ['console'],level: 'trace'},
         default: {appenders: ['console','filelog'],level: 'trace'}
      }
   });
  var logger  = log4js.getLogger('my_project');
        logger.setLevel('DEBUG');
        Object.defineProperty(exports, "LOG", {
                    value:logger,
 })

index.js:

var express = require('express');
var router = express.Router();
var logger= require('./logger.js');
var log=logger.LOG;
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

exports.index = function(req, res){
log.debug("testing the debug log here....................");
log.error("testing the error log here....................");
log.info("testing the info log here....................");
log.trace("testing the trace log here....................");
  res.render('index', { title: 'Express' });
};

module.exports = router;

app.js

var express = require('express');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var log = require('./routes/logger');
var app = express();

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

//use logger
app.use(log4js.connectLogger(log, { level: log4js.levels.DEBUG }));

app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('node Express server listening on port ' + server.address().port);
});

module.exports = app;

我是Node js的新手,这是我第一次使用Node js创建日志文件。任何人都可以帮助我解决问题。如果我得到一个有效的代码可能会更好。我整天都被困住了。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码设置记录器级别:

logger.level = 'DEBUG';