diff --git a/lib/se/api.rb b/lib/se/api.rb index cd41b5d..2ffedb9 100644 --- a/lib/se/api.rb +++ b/lib/se/api.rb @@ -19,7 +19,7 @@ class Client attr_reader :quota, :quota_used attr_accessor :params - def initialize(key = "", **params) + def initialize(key = "", log_api_raw: false, log_api_json: false, log_meta: true, **params) @key = key @params = params.merge({filter: '!*1_).BnZb8pdvWlZpJYNyauMekouxK9-RzUNUrwiB'}) @quota = nil @@ -27,6 +27,10 @@ def initialize(key = "", **params) @backoff = Time.now @logger_raw = Logger.new 'api_raw.log' @logger_json = Logger.new 'api_json.log' + @logger = Logger.new 'se-api.log' + @logger_raw.level = Logger::Severity::UNKNOWN unless log_api_raw + @logger_json.level = Logger::Severity::UNKNOWN unless log_api_json + @logger.level = Logger::Severity::UNKNOWN unless log_meta end def posts(*ids, **params) @@ -85,15 +89,16 @@ def json(uri, **params) backoff_for = @backoff-Time.now backoff_for = 0 if backoff_for <= 0 if backoff_for > 0 - puts "Backing off for #{backoff_for}" + @logger.warn "Backing off for #{backoff_for}" sleep backoff_for+2 - puts "Finished backing off!" + @logger.warn "Finished backing off!" end params = @params.merge(params).merge({key: @key}).map { |k,v| "#{k}=#{v}" }.join('&') - puts "Posting to https://api.stackexchange.com/#{API_VERSION}/#{uri}?#{params}" + @logger.info "Posting to https://api.stackexchange.com/#{API_VERSION}/#{uri}?#{params}" begin resp_raw = Net::HTTP.get_response(URI("https://api.stackexchange.com/#{API_VERSION}/#{uri}?#{params}")).body rescue Net::OpenTimeout, SocketError => e + @logger.warn "Got timeout on API request (#{e}). Retrying..." puts "Got timeout on API request (#{e}). Retrying..." sleep 0.3 retry