152

I want to see the SQL commands that are sent to the PostgreSQL server because I need to check if they are correct. In particular, I am interested in the table creation commands.

For instance, ActiveRecord (Ruby) prints its SQL statements to standard output. Is this possible with Node.js/ActionHero.js and Sequelize.js as well?

ideaboxer
  • 3,863
  • 8
  • 43
  • 62

4 Answers4

219

You can pass a logging option when initializing sequelize, which can either be a function or console.log

var sequelize = new Sequelize('database', 'username', 'password', {
    logging: console.log
    logging: function (str) {
        // do your own logging
    }
});

You can also pass a logging option to .sync if you only want to view the table creation queries

sequelize.sync({ logging: console.log })
Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66
  • Thanks, this is exactly what I want. `DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log` -- what does this mean? – ideaboxer Jan 29 '14 at 15:20
  • Means you should pass a function instead of true. – Mick Hansen Jan 31 '14 at 12:50
  • 5
    I never ever passed `true`. – ideaboxer Jan 31 '14 at 15:11
  • 3
    I'm a bit late to the party, but `console.log` works in mysterious ways. You should be able to avoid the log message using `{ logging: (msg) => console.log(msg) }` or `{ logging: function(msg) { console.log(msg) } }`. (untested so I could be totally wrong) – 3ocene Jan 29 '19 at 20:06
  • 5
    Is there any way I can see the generated query , but the query should not execute ? – NIKHIL C M Jun 26 '19 at 09:56
77

As stated in the log Error: Please note that find* was refactored and uses only one options object from now on.. For the latest sequelize version (4) if you want to have the result for only one command:

User.findAll({where: {...}, logging: console.log})

Adlen Afane
  • 1,422
  • 14
  • 24
33

If you want to look at the sequelize for one command you can listen to it and attach a function to the print the sql.

Check out this example:

User.find(1).on('sql', console.log).then(function(user) {
  // do whatever you want with the user here
vpontis
  • 733
  • 8
  • 15
  • 44
    You now pass in a logger as an option to log a single statement: `User.find(1, { logging: console.log })` – Stephen Watkins Jun 08 '15 at 01:42
  • 5
    Mine just says `.findOne(...).on is not a function` Using sequelize 3.30.4 – ginna Dec 21 '17 at 19:22
  • 1
    It appears that some of the association mixins do not support the logging option. Specifically, the `get*` on the source of a belongsTo relationship. – Tom Oct 30 '18 at 05:01
25

You can also take advantage of Sequelize's use of the Debug module, by setting your environment, thus: DEBUG=sequelize:sql* before starting your app.

steev
  • 916
  • 10
  • 24