How do I show a general_query log with Sequel gem in terminal - ruby

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.

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

Related

How to turn off logging into the console in Mockserver Ruby client

I am creating an expectation using the Ruby client for mockserver and getting a bunch of logging messages in the console(terminal). I was wondering how to turn that off, but not print it out to a file.
I have tried this but it only prints it out to a file
client = MockServerClient.new(Config.mockserver.host, Config.mockserver.port)
client.logger = LoggingFactory::DEFAULT_FACTORY.log('yo', output: 'tmp.log', truncate: true)
You can chose whichever of these.
Logging in console: client.logger = Logger.new(STDOUT)
Logging into file: client.logger = Logger.new('log/foo.log', 'daily')
Logging nothing: client.logger = Logger.new(nil)

Create Postgresql database in Heroku with Ruby (without Rails)

I'm currently hosting a simple Ruby script that stores URLs and Scores and saving them to YAML. However, I'd like to save to a Postgresql database instead since the yaml file is deleted every time I restart the app. Here's the error I'm getting in Heroku:
could not connect to server: No such file or directory (PG::ConnectionBad)
Here's an example script that works locally, but throws me the above error in Heroku:
require 'pg'
conn = PG.connect( dbname: 'template1' )
res1 = conn.exec('SELECT * from pg_database where datname = $1', ['words'])
if res1.ntuples == 1 # db exists
# do nothing
else
conn.exec('CREATE DATABASE words')
words_conn = PGconn.connect( :dbname => 'words')
words_conn.exec("create table top (url varchar, score integer);")
words_conn.exec("INSERT INTO top (url, score) VALUES ('http://apple.com', 1);")
end
Thanks in advance for any help or suggestions!
Assuming you have created a Postgres database using the Heroku toolchain via heroku addons:add heroku-postgresql:dev (or the plan of your choice) you should have a DATABASE_URL environmental variable that contains your connection string. You can check that locally through heroku pg:config.
Using the pg gem (docs: http://deveiate.org/code/pg/PG/Connection.html) - and modifying the example from there to suit -
require 'pg'
# source the connection string from the DATABASE_URL environmental variable
conn = PG::Connection.new(ENV['DATABASE_URL'])
res = conn.exec_params('create table top (url varchar, score integer;")
Update: A slightly more complete example for the purposes of error handling:
conn = PG::Connection.new(ENV['TEST_DATABASE_URL'])
begin
# Ensures the table is created if it doesn't exist
res = conn.exec("CREATE TABLE IF NOT EXISTS top (url varchar, score integer);")
res.result_status
rescue PG::Error => pg_error
puts "Table creation failed: #{pg_error.message}"
end

metriks log to file not working

I wrote a basic program to test the ruby metriks gem
require 'metriks'
require 'metriks/reporter/logger'
#registry = Metriks::Registry.new
#logger = Logger.new('/tmp/metrics.log')
#reporter = Metriks::Reporter::Logger.new(:logger => #logger)
#reporter.start
#registry.meter('tasks').mark
print "Hello"
#registry.meter('tasks').mark
#reporter.stop
After i execute the program, there is nothing in the log other than it got created.
$ cat /tmp/metrics.log
# Logfile created on 2015-06-15 14:23:40 -0700 by logger.rb/44203
You should either pass in your own registry while instantiating Metriks::Reporter::Logger or use the deafult registry (Metrics::Resgitry.default) if you are using a logger to log metrics.
Also the default log write interval is 60 seconds, your code completes before that so even if everything is setup okay it won't get recorded. So, since you want to use your own registry, this should work for you (I'm adding a little sleep since I'm gonna use an interval of 1 second) :
require 'metriks'
require 'metriks/reporter/logger'
#registry = Metriks::Registry.new
#logger = Logger.new('/tmp/metrics.log')
#reporter = Metriks::Reporter::Logger.new(:logger => #logger,
:registry => #registry
:interval => 1)
#reporter.start
#registry.meter('tasks').mark
print "Hello"
#registry.meter('tasks').mark
# Just giving it a little time so the metrics will be recorded.
sleep 2
#reporter.stop
But I don't really think short intervals are good.
UPDATE : Also I think #reporter.write will help you write down the logs instantly regardless of the time interval. So you don't have to use sleep (better).

Padrino custom log file

I need to create a custom log file within Padrino that contains all of the logging information that is in stdout as well as custom log messages. I have been able to get the custom log file created, but the stdout file (development.log, production.log, etc.) still gets created with logging statements in it. I have tried putting these lines in the boot.rb file, but none of these seem to work:
Padrino::Logger::Config[:development][:stream] = :to_file
Padrino::Logger::Config[:development] = { :log_level => :debug, :stream => :to_file }
Padrino::Logger::Config[:development][:stream] = :null
Padrino::Logger::Config[:development] = { :log_level => :debug, :stream => :null}
I have looked at Padrino's development commands and logger documentation but they didn't help.
In case it helps, this is the code that is generating the custom log file. (Whether I run this code or not, the stdout file keeps getting created):
log_path = File.join(custom_log_path, 'My Service')
FileUtils.mkdir_p log_path
log_file_path = File.join(log_path, "MyService_#{current_date_time_formatted}.log")
logger = File.open(log_file_path, "a+")
if defined?(PADRINO_ENV) && PADRINO_ENV == 'production'
$stdout.reopen(logger)
$stderr.reopen(logger)
end
Any help is greatly appreciated!
You should be able to do this:
Padrino::Logger::Config[:development][:stream] = logger
# or
Padrino::Logger::Config[:production][:stream] = logger
after you have defined logger. If config[:stream] doesn't receive a keyword, Padrino::Logger will use whatever is passed as the output stream.
For more information on the Padrino logger, check out the relevant Padrino Core code, especially self.setup!: https://github.com/padrino/padrino-framework/blob/master/padrino-core/lib/padrino-core/logger.rb.

Log4r and Chainsaw: gathering additional log message details (line number, etc.)?

I'm using Log4r's Log4j XML formatter to talk to Chainsaw as described here in Log4r's manual. However, basically all I'm getting is the message and warning level -- I'm not getting the additional details that seem to be shown there.
Here's the context in which I'm using it, which seems to me very similar to their (note I'm also using their example Chainsaw configuration file unmodified):
#log = Log4r::Logger.new "#{self.class.name}"
log4jformat = Log4r::Log4jXmlFormatter.new
hostname = opts[:chainsaw_hostname] || DEFAULT_CHAINSAW_HOST
port = opts[:chainsaw_port] || DEFAULT_CHAINSAW_PORT
udpout = Log4r::UDPOutputter.new 'udp', :hostname => hostname, :port => port
udpout.formatter = log4jformat
#log.outputters = [udpout]
#log.debug 'this is a message with level debug'
Any suggestions on this? Again I'm seeing the messages appear, they just don't have the additional details attached like the class/method/line where the log event occurred.
You have to explicitly turn tracing on for this to work. I just had to add the line:
#log.trace = true
and it worked immediately.

Resources