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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28927836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:30:47  来源:igfitidea点击:

Prevent Sequelize from outputting SQL to the console on execution of query?

node.jssequelize.js

提问by thenetimp

I have a function to retrieve a user's profile.

我有一个功能来检索用户的个人资料。

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);
  });
});

When the "find" function is called it displays the select statement on the console where the server was started.

当“查找”函数被调用时,它会在启动服务器的控制台上显示选择语句。

Executing (default): SELECT `id`, `firstName`, `lastName`, `emailAddress`, `password`, `passwordRecoveryToken`, `passwordRecoveryTokenExpire`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`emailAddress` = '[email protected]' LIMIT 1;

Is there a way to get this not to be display? Some flag that I set in a config file somewhere?

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

回答by victorkohl

When you create your Sequelize object, pass falseto the loggingparameter:

创建 Sequelize 对象时,传递falselogging参数:

var sequelize = new Sequelize('database', 'username', 'password', {

  // disable logging; default: console.log
  logging: false

});

For more options, check the docs.

有关更多选项,请查看文档

回答by Supawat Pusavanno

If 'config/config.json' file is used then add 'logging': false to the config.json in this case under development configuration section.

如果使用 'config/config.json' 文件,则在这种情况下在开发配置部分下将 'logging': false 添加到 config.json。

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

回答by Mostafa Abdellateef

As in other answers, you can just set logging:false, but I think better than completely disabling logging, you can just embrace log levels in your app. Sometimes you may want to take a look at the executed queries so it may be better to configure Sequelize to log at level verbose or debug. for example (I'm using winston here as a logging framework but you can use any other framework) :

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

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

This will output SQL statements only if winston log level is set to debug or lower debugging levels. If log level is warn or info for example SQL will not be logged

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

回答by Ratul Sharker

All of these answers are turned off the loggingat creation time.

所有这些答案都在创建时关闭日志记录

But what if we need to turn off the loggingon runtime ?

但是如果我们需要关闭运行时的日志记录怎么办?

By runtime i mean after initializing the sequelizeobject using new Sequelize(..function.

运行时我的意思是在sequelize使用new Sequelize(..函数初始化对象之后。

I peeked into the github source, found a way to turn off logging in runtime.

我查看了github 源代码,找到了一种关闭运行时登录的方法。

// Somewhere your code, turn off the logging
sequelize.options.logging = false

// Somewhere your code, turn on the logging
sequelize.options.logging = true 

回答by Stephen Hulme

Based on this discussion, I built this config.jsonthat works perfectly:

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

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

回答by STREET MONEY

I am using Sequelize ORM 6.0.0 and am using "logging": false as the rest but posted my answer for latest version of the ORM.

我正在使用 Sequelize ORM 6.0.0 并使用 "logging": false 作为其余部分,但发布了我对最新版本 ORM 的答案。

const sequelize = new Sequelize(
        process.env.databaseName,
        process.env.databaseUser,
        process.env.password,
        {
            host: process.env.databaseHost,
            dialect: process.env.dialect,
            "logging": false,
            define: {
                // Table names won't be pluralized.
                freezeTableName: true,
                // All tables won't have "createdAt" and "updatedAt" Auto fields.
                timestamps: false
            }
        }
    );

Note: I am storing my secretes in a configuration file .envobserving the 12-factor methodology.

注意:我将我的秘密存储在一个配置文件中,.env观察 12 因素方法。

回答by STREET MONEY

I solved a lot of issues by using the following code. Issues were : -

我通过使用以下代码解决了很多问题。问题是: -

  1. Not connecting with database
  2. Database connection Rejection issues
  3. Getting rid of logs in console (specific for this).
  1. 不连接数据库
  2. 数据库连接拒绝问题
  3. 摆脱控制台中的日志(特定于此)。
const sequelize = new Sequelize("test", "root", "root", {
  host: "127.0.0.1",
  dialect: "mysql",
  port: "8889",
  connectionLimit: 10,
  socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
  // It will disable logging
  logging: false
});

回答by Vikash Kumar Choudhary

Here is my answer:

这是我的回答:

Brief: I was using typeormas a ORM library. So, to set the query logging level I have used the following option instead of directly setting the logging option as false.

简介:我typeorm用作 ORM 库。因此,为了设置查询日志记录级别,我使用了以下选项,而不是直接将日志记录选项设置为false.

Solution:File name - ormconfig.ts

解决方案:文件名-ormconfig.ts

{
    'type': process.env.DB_DRIVER,
    'host': process.env.DB_HOST,
    'port': process.env.DB_PORT,
    'username': process.env.DB_USER,
    'password': process.env.DB_PASS,
    'database': process.env.DB_NAME,
    'migrations': [process.env.MIGRATIONS_ENTITIES],
    'synchronize': false,
    'logging': process.env.DB_QUERY_LEVEL,
    'entities': [
        process.env.ORM_ENTITIES
    ],
    'cli': {
        'migrationsDir': 'migrations'
     }
}

And, in the envrionment variable set the DB_QUERY_LEVELas ["query", "error"].

并且,在环境变量中设置DB_QUERY_LEVEL为 ["query", "error"]。

Result:As a result it will log only when the query has error else it won't.

结果:因此它只会在查询有错误时记录,否则不会。

Ref link:typeorm db query logging doc

参考链接:typeorm db query logging doc

Hope this helps! Thanks.

希望这可以帮助!谢谢。