首页 文章

防止Sequelize在执行查询时将SQL输出到控制台?

提问于
浏览
113

我有一个功能来检索用户的 Profiles .

app.get('/api/user/profile', function (request, response)
{
  // Create the default error container
  var error = new Error();

  var User = db.User;
  User.find({
    where: { emailAddress: request.user.username}
  }).then(function(user)
  {
    if(!user)
    {
      error.status = 500; error.message = "ERROR_INVALID_USER"; error.code = 301;
      return next(error);
    }

    // Build the profile from the user object
    profile = {
      "firstName": user.firstName,
      "lastName": user.lastName,
      "emailAddress": user.emailAddress
    }
    response.status(200).send(profile);
  });
});

调用“find”函数时,它会在启动服务器的控制台上显示select语句 .

Executing (default): SELECT `id`, `firstName`, `lastName`, `emailAddress`, `password`, `passwordRecoveryToken`, `passwordRecoveryTokenExpire`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`emailAddress` = 'johndoe@doe.com' LIMIT 1;

有没有办法让这不显示?我在某个配置文件中设置的一些标志?

4 回答

  • 21

    创建Sequelize对象时,将 false 传递给 logging 参数:

    var sequelize = new Sequelize('database', 'username', 'password', {
    
      // disable logging; default: console.log
      logging: false
    
    });
    

    有关更多选项,请查看docs .

  • 203

    如果使用'config / config.json'文件,则在开发配置部分的本例中将config.json添加'logging':false .

    // file config/config.json
      {
          {
          "development": {
            "username": "username",
            "password": "password",
            "database": "db_name",
            "host": "127.0.0.1",
            "dialect": "mysql",
            "logging": false
          },
          "test": {
        ...
       }
    
  • 10

    与其他答案一样,您可以设置 logging:false ,但我认为比完全禁用日志记录要好,您可以在应用中使用日志级别 . 有时您可能希望查看已执行的查询,因此最好将Sequelize配置为在详细级别或调试时进行日志记录 . 例如(我在这里使用winston作为日志框架,但您可以使用任何其他框架):

    var sequelize = new Sequelize('database', 'username', 'password', {
      logging: winston.debug
    });
    

    仅当winston日志级别设置为debug或降低调试级别时,才会输出SQL语句 . 如果日志级别是警告或信息,例如SQL将不会被记录

  • 1

    基于这个讨论,我构建了完美的 config.json

    {
      "development": {
        "username": "root",
        "password": null,
        "logging" : false,
        "database": "posts_db_dev",
        "host": "127.0.0.1",
        "dialect": "mysql",
        "operatorsAliases": false 
      }
    }
    

相关问题