4

I have a webserver that uses Sinatra and the Sequel gem. I would like to know if it is possible to print every query executed into the console.

I found in the Sequel documentation that I can setup a log file path.

You can also specify optional parameters, such as the connection pool size, or loggers for logging SQL queries:

DB = Sequel.connect("postgres://user:password@host:port/database_name",  
:max_connections => 10, :logger => Logger.new('log/db.log'))

However I was unable to find anything about printing the queries into the console rather than a log.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sean Larkin
  • 6,290
  • 1
  • 28
  • 43

1 Answers1

3

You can, and you can log to multiple loggers too, see example below

db_location_test = "/db/reservation.accdb"
log_file_path = "#{__FILE__}_#{Time.now.strftime("%Y%m%d")}.txt"
log_file = File.open(log_file_path, "a")
$filelog = Logger.new log_file
$console = Logger.new STDOUT

$console.info "connecting to access database" #only logged to console
sConnectionStringAccess = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=#{db_location_test}"
#sql will be logged to both file and console
DBA = Sequel.ado(:conn_string=>sConnectionStringAccess, :loggers=>[$filelog,$console])

class Reservations < Sequel::Model(:TABLE_RESERVATIONS);end

Reservations.all.each do |record|
  $console.info Hash[record]
end
peter
  • 41,770
  • 5
  • 64
  • 108
  • Don't use camel-case variables in Ruby. `sConnectionStringAccess` should be `connection_string_access`. Ruby isn't Java or C#. – the Tin Man Feb 09 '16 at 18:27
  • yep, you are right, copied that line from a vbscript and forgot to change, nowadays it's most of the time the opposite, I use Ruby style in vbscript if I have to use it once in a while. I notice I even used an 's' to indicate a string, oldfashioned indeed. – peter Feb 09 '16 at 21:04
  • 2
    This works. Also, if you already have an established connection you can add loggers with something like `some_connection.loggers << $filelog` – MegaTux Jun 22 '20 at 15:07