How can I disable MongoDB log messages in console? - ruby

I have this little test script:
require 'mongo'
mongo_client = Mongo::Client.new(['127.0.0.1:27017'], :database => 'test')
mongo_client[:collection].insert_one({a: 1})
An this is the console output:
$ ruby test.rb
D, [2015-05-17T21:12:05.504986 #25257] DEBUG -- : MONGODB | Adding 127.0.0.1:27017 to the cluster. | runtime: 0.0212ms
D, [2015-05-17T21:12:05.531238 #25257] DEBUG -- : MONGODB | COMMAND | namespace=admin.$cmd selector={:ismaster=>1} flags=[] limit=-1 skip=0 project=nil | runtime: 24.5481ms
D, [2015-05-17T21:12:05.554532 #25257] DEBUG -- : MONGODB | COMMAND | namespace=test.$cmd selector={:insert=>"collection", :documents=>[{:a=>1, :_id=><BSON::ObjectId:0x21935660 data=5558e80553657262a9000000>}], :writeConcern=>{:w=>1}, :ordered=>true} flags=[] limit=-1 skip=0 project=nil | runtime: 21.1718ms
I want to disable those log messages, I don't want a dirty STDOUT. I didn't found any option for this in the ruby driver, and also I've tried to edit /etc/mongod.conf with these directives (but it didn't fix it):
verbose = false
diaglog = 0
Any idea? I don't know what else I can try!

This logging is coming from the Ruby Mongo driver. The default logging level seems to be Logger::DEBUG. Change it to something higher to disable the debug output:
Mongo::Logger.logger.level = Logger::FATAL
To make the driver log to a logfile instead:
Mongo::Logger.logger = Logger.new('mongo.log')
Mongo::Logger.logger.level = Logger::INFO
Note that if you're using the Mongoid ODM, then you may want to adjust logging there too:
Mongoid.logger = Logger.new('mongoid.log')
Mongoid.logger.level = Logger::INFO
For Rails + Mongoid in application.rb:
config.mongoid.logger = Logger.new(Rails.root + '/log/mongoid.log', :warn)
# ...or change the logging level without a new file destination
config.mongoid.logger.level = Logger::INFO

To disable the debug output for Ruby Mongo Driver(mongoid)
we can add it specific environment file as
config.mongoid.logger.level = Logger::INFO

The other answers didn't work for me.
This works for newer Ruby / Rails Versions:
config.mongoid.logger = Logger.new(Rails.root.join('log/mongoid.log'), level: :warn)

Related

How to resolve Aerospike::Exceptions::Aerospike: Unsupported Server Feature for Ruby Client?

While I am trying to write into aerospike using ruby client I am getting the following exception:-
Aerospike::Exceptions::Aerospike: Unsupported Server Feature
Details:-
Aerospike version:- 4.3
Client: [Ruby] aerospike - 2.4.0
namespaces: NS1, NS2, NS3
Note: NS2 and NS3 have single-bin true data-in-index true
Code(which causes the exception):-
client = Aerospike::Client.new('aerospike:3000')
key = Aerospike::Key.new('NS2', 'set name', 'this is the key')
data = { 'record' => 1 }
client.put(key, data) # this line raises the exception
Aerospike::Exceptions::Aerospike: Unsupported Server Feature
The exception is not raised if I change NS2 in the key to NS1.
The "Unsupported Server Feature" error you are getting is because the Ruby client is sending the user key to the server by default, but the Aerospike server does not support storing the user key for the data-in-memory & single-bin setup. You should see an error message like this in your server logs:
Sep 13 2018 02:42:20 GMT: WARNING (rw): (rw_utils.c:153) {sbin} can't store key if data-in-memory & single-bin
You'll need to disable sending the key as part of the put request by setting the send_key write policy setting to false:
$ bundle exec irb
2.5.0 :001 > require 'aerospike'; include Aerospike;
=> Object
2.5.0 :002 > client = Client.new; key = Key.new('sbin', 'test', 'foo'); nil
=> nil
2.5.0 :003 > client.put(key, Bin.new('', 42), send_key: false)
=> nil
2.5.0 :004 > client.get(key).bins['']
=> 42

How to measure moped insert runtime in a ruby mongoid app?

I'm currently writing a moped log parser in order to monitor moped queries runtime.
It's work great for QUERY command using the runtime parameter, but INSERT and UPDATE have no runtime parameter. All INSERT and UPDATE are followed by a getLastError COMMAND which contains a runtime.
Here are some samples of moped logs:
QUERY with runtime
MOPED: 127.0.0.1:27017 QUERY database=X collection=X selector=X
flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 0.6950ms
INSERT without runtime but with COMMAND
MOPED: 127.0.0.1:27017 INSERT database=X collection=X documents=X flags=[]
COMMAND database=X command={:getlasterror=>1, :w=>1}
runtime: 0.4750ms
I'm pretty sure that COMMAND runtime is for the getlasterror call and not for my INSERT one.
So is there a way to get this runtime info for an INSERT query?
Instead of using a log parser, I use something like this and it works great:
ActiveSupport::Notifications.subscribe('query.moped') do |name, start, finish, id, payload|
runtime = (finish - start)*1000
moped_ops = payload[:ops]
moped_ops.each do |op|
unless op.collection == '$cmd'
query = op.class.name.split('::').last.downcase
query = op.selector.first[0].to_s.gsub(/\$/, '') if query == 'command'
DO SOMETHING WITH #{op.database}.#{op.collection}.#{query}
end
end
end

cucumber ActiveRecord::ConnectionNotEstablished

The exception I am getting is "ActiveRecord::ConnectionNotEstablished: No connection pool for ActiveRecord::Base". I am really on the deep end of the pool (no pun intended) with this one. I really don't understand the connection and connection pool handling, even as much as I have studied this problem. I'm assuming this might be scope related inside of Cucumber, but I do not know. Any and all assistance is appreciated.
Here are the details:
The exception occurs when I perform a count from a Then clause:
WorkTable.where('? is not null',col['COLUMN_NAME']).count
It does not occur if I send the sql directly through the connection:
WorkTable.connection.select_all(st.encode('utf-8')).first['nulls']
My scenario reads as follows:
Scenario: CompanyMaster test for null value
Given table dbo.base_table in stage
Then these columns are expected to be not null
| COLUMN_NAME | nulls |
| id | 0 |
| company_name | 0 |
I establish my class in my env.rb:
class WorkTable < ActiveRecord::Base
end
ActiveRecord::Base.configurations = YAML.load_file(yaml) # yaml is database.yml file name
I establish my connection in a Given clause:
Given(/^table (\w+)\.?([\w_]+) in (\w+)(?: as (\w+))?$/) do |schema,name,env,id|
#sc_name = schema_file_name(schema,name)
WorkTable.logger.info title_line("* Active table(#{#sc_name}) *")
case id
# ActiveRecord::Base.configurations[env]
...
else
WorkTable.table_name = #sc_name
WorkTable.establish_connection(env.to_sym)
# ary = get_tables(WorkTable,schema:schema)
# expect( ary.any?{|s| s.casecmp(name)==0 } ).to eq(true)
end
end
I execute my test in a Then clause:
Then(/^these columns are expected to be not null$/) do |columns|
# expected is an instance of Cucumber::Ast::Table
WorkTable.logger.info title_line('Columns cannot be null')
results = []
columns.hashes.each {|col|
results << {
'COLUMN_NAME' => col['COLUMN_NAME'],
'nulls' => WorkTable.where('? is not null',col['COLUMN_NAME']).count.to_s
}
}
columns.diff!(results,surplus_row: false)
end
It is the WorkTable.where that throws the "ActiveRecord::ConnectionNotEstablished: No connection pool for ActiveRecord::Base". Again, if I use the WorkTable.connection method, I do not get it. Also, it executes fine if I copy all the function code to single ruby script.
I see the following when I "pp WorkTable.connection":
#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>
And I see the following when I "pp WorkTable.connection_pool":
#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238
#automatic_reconnect=true,
#available=
#<ActiveRecord::ConnectionAdapters::ConnectionPool::Queue:0x42f4f20
#cond=
#<MonitorMixin::ConditionVariable:0x42f4ed8
#cond=
#<ConditionVariable:0x42f4de8
#waiters=[],
#waiters_mutex=#<Mutex:0x42f4d58>>,
#monitor=
#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>>,
#lock=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>,
#num_waiting=0,
#queue=[]>,
#checkout_timeout=5,
#connections=
[#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>],
#mon_count=0,
#mon_mutex=#<Mutex:0x42f51c0>,
#mon_owner=nil,
#reaper=
#<ActiveRecord::ConnectionAdapters::ConnectionPool::Reaper:0x42f51a8
#frequency=nil,
#pool=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>>,
#reserved_connections=
#<ThreadSafe::Cache:0x42f4fc8
#backend=
{16931712=>
#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>},
#default_proc=nil>,
#size=5,
#spec=
#<ActiveRecord::ConnectionAdapters::ConnectionSpecification:0x42f55c8
#adapter_method="sqlserver_connection",
#config=
{:host=>"server_name",
:database=>"mssb_stg",
:encoding=>"utf-8",
:adapter=>"sqlserver",
:timeout=>5000}>>
Ruby 1.9.3, activerecord (4.2.0), activerecord-sqlserver-adapter (4.2.2), and cucumber (1.3.18). And sql server 2014 [this has been a bugger for me].
Thank you for you time and consideration.
dvn
== Additional detail ==
Ignore the sql-server reference. I get the same exception when I reconfigure to work with SqLite. So it is not related to db platform.
Check your env.rb, conf in supports, it seems you are making connections in steps, ideally you should do it in before_scenario or before feature file rather than per steps.
It could be possible after steps your connection is not working properly.

dont append but overwrite log file of logger

I use logger in my application and direct the output to a file like this:
Logger.new("nemobuild.log")
My logger appends to this logfile once its created.
What i want it to do is to clear the logfile on each program start.
In the examples is a description for creating a new logfile:
file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
What File:: params would i have to use to get the desired behaivior?
Which gem do you use? Can you provide a MWE?
With
Logger.new("nemobuild.log")
I get the error:
`<main>': uninitialized constant Logger (NameError)
Do you use the standard Logger?
Then you can use a file object instead a filename for the logfile:
require 'logger'
log = Logger.new(File.new("nemobuild.log",'w'))
log.error('XX')
If you want back the append-mode, you can switch the w-option (write) to a (append):
log = Logger.new(File.new("nemobuild.log",'a'))
Assuming you can/want use log4r:
The feature you need is an option trunc of the FileOutputter:
require 'log4r'
log = Log4r::Logger.new('log')
log.outputters << Log4r::FileOutputter.new(
'log_file', :filename => 'mini_example.log',
:trunc => true, #Delete old log
)
I ended up deleting the file before setting up the logger:
File.delete("nemobuild.log")
logger = Logger.new("nemobuild.log")

How to change the prompt

I am trying to configure the prompt characters in ripl, an alternative to interactive ruby (irb). In irb, it is done using IRB.conf[:DEFAULT], but it does not seem to work with ripl. I am also having difficulty finding an instruction for it. Please guide to a link for an explanation or give a brief explanation.
Configuring a dynamic prompt in ~/.riplrc:
# Shows current directory
Ripl.config[:prompt] = lambda { Dir.pwd + '> ' }
# Print current line number
Ripl.config[:prompt] = lambda { "ripl(#{Ripl.shell.line})> " }
# Simple string prommpt
Ripl.config[:prompt] = '>>> '
Changing the prompt in the shell:
>> Ripl.shell.prompt = lambda { Dir.pwd + '> ' }
ripl loads your ~/.irbrc file, which
typically contains some irb specific
options (e.g. IRB.conf[:PROMPT]). To
avoid errors, you can install
ripl-irb, which catches calls to the
IRB constant and prints messages to
convert irb configuration to ripl
equivalents.
http://rbjl.net/44-ripl-why-should-you-use-an-irb-alternative

Resources