class Coralogix::LoggerManager

@private

Attributes

configured[RW]

Public Class Methods

new(proxy={}) click to toggle source
# File lib/manager.rb, line 13
def initialize proxy={}
    @logger_type = "Centralized Ruby"
    @bulk_template = {:privateKey => FAILED_PRIVATE_KEY, :applicationName => NO_APP_NAME, :subsystemName => NO_SUB_SYSTEM}
    @time_delta_last_update = 0
    @time_delta = 0
    @http_sender = CoralogixHTTPSender.new proxy
    @buffer = []
    @buffer_size = 0
    @mutex = Mutex.new
    run
end

Public Instance Methods

add_logline(message, severity, category, args={}) click to toggle source

Add a log line to our buffer.

@param message - The logs message. This is a must parameter. @param severity - The severity of the log message. This is a must parameter. @param category - The category (logger name) of the message. This is a must parameter. @param **args - Optional parameters. It can be:

className - The class name where the log message was sent from.
methodName - The method name where the log message was sent from.
threadId -  The thread id where the log message was sent from.
timestamp - The timestamp of the log message.

@return [boolean] return true for success or false for failure.

# File lib/manager.rb, line 68
def add_logline message, severity, category, args={}
    begin
        @mutex.synchronize do
            if @buffer_size < MAX_LOG_BUFFER_SIZE
                #Validate message
                message = (message.nil? || message.to_s.strip.empty?) ? "EMPTY_STRING" : msg2str(message)
                #Validate severity
                severity = (severity.nil? || severity.to_s < Severity::DEBUG.to_s || severity.to_s > Severity::CRITICAL.to_s) ? Severity::DEBUG : severity
                #Validate category
                category = (category.nil? || category.to_s.strip.empty?) ? CORALOGIX_CATEGORY : category.to_s
                #Combine a logentry from the must parameters together with the optional one.
                new_entry = {:text => message, :severity => severity, :category => category}.merge(args)
                if new_entry[:timestamp].nil?
                    new_entry[:timestamp] = Time.now.utc.to_f * 1000 + @time_delta
                end
                
                @buffer << new_entry
                #Update the buffer size to reflect the new size.
                @buffer_size+=new_entry.to_json.bytesize
            else
                DebugLogger.warn "max logs exceeded, dropping log"
            end
        end
    rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect
        return false
    end
    return true
end
configure(args={}) click to toggle source

Add a log line to our buffer.

@param **args - Customer parameters:

privateKey - Private Key
applicationName - Application name
subsystemName - Subsystem name

@return [boolean] return true for success or false for failure.

# File lib/manager.rb, line 32
def configure args={}
    begin
        @bulk_template = args.merge({:computerName => `hostname`.strip})
        DebugLogger.debug "Successfully configured Coralogix logger."
        @configured = true                
        add_logline "The Application Name #{@bulk_template[:applicationName]} and Subsystem Name #{@bulk_template[:subsystemName]} from the #{@logger_type} SDK, version #{version?} has started to send data.", Severity::INFO, CORALOGIX_CATEGORY 
    rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect
        @configured = false
    end
    return @configured
end
disable_proxy=(value) click to toggle source

A setter for disable_proxy. By default HTTP object will use proxy environment variable if exists. In some cases this migh be an issue When set to false the HTTP object will ignore any proxy.

@param value - true or false. (Default is false)

# File lib/manager.rb, line 172
def disable_proxy=(value)
    @http_sender.disable_proxy=value
end
flush() click to toggle source

Flush all messages in buffer and send them immediately on the current thread.

# File lib/manager.rb, line 122
def flush
    send_bulk false
end
force_compression=(value) click to toggle source

A setter for force data sending even if somehow the compression of data failed.

@param value - true or false. (Default is false)

# File lib/manager.rb, line 179
def force_compression=(value)
    @http_sender.force_compression=value
end
msg2str(msg) click to toggle source

Convert log message to string @param msg - log message to convert

@return [String] return log message as string

# File lib/manager.rb, line 103
def msg2str(msg)
    begin
        case msg
            when ::String
                msg
            when ::Exception
                "#{ msg.message } (#{ msg.class })\n" <<
                    (msg.backtrace || []).join("\n")
            else
                msg.inspect
        end
    rescue Exception => e
        DebugLogger.error e.message
        DebugLogger.error e.backtrace.inspect
        return msg
    end
end
run() click to toggle source

Start timer execution. The timer should send every X seconds logs from the buffer.

# File lib/manager.rb, line 204
def run
    begin
        timer_thread = Thread.new do
            while true
                # Send log bulk
                send_bulk

                # Check when is the next time we should send logs?
                # If we already have at least half of the max chunk size then we are working in fast mode
                next_check_interval = @buffer_size > (MAX_LOG_CHUNK_SIZE / 2) ? FAST_SEND_SPEED_INTERVAL : NORMAL_SEND_SPEED_INTERVAL
                DebugLogger.trace "Next buffer check is scheduled in #{next_check_interval} seconds"
                sleep next_check_interval
            end
        end

        #Set thread priority to a high number
        timer_thread.priority = 100
    rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect
        return false
    end
end
send_bulk(time_sync=true) click to toggle source

Send bulk from the buffer

# File lib/manager.rb, line 131
def send_bulk time_sync=true
    begin
        update_time_delta_interval if time_sync
        @mutex.synchronize do
            # Total buffer size
            size = @buffer.size
            return unless size > 0

            # If the size is bigger than the maximum allowed chunk size then split it by half.
            # Keep splitting it until the size is less than MAX_LOG_CHUNK_SIZE
            while (@buffer.take(size).join(",").bytesize > MAX_LOG_CHUNK_SIZE) && (size > 0) 
                size=size/2;
            end
            
            # We must take at leat one value. If the first message is bigger than MAX_LOG_CHUNK_SIZE
            # we need to take it anyway.
            size = size > 0 ? size : 1

            DebugLogger.debug "Checking buffer size. Total log entries is: #{size}"
            @bulk_template[:logEntries] = @buffer.shift(size)

            # Extract from the buffer size the total amount of the logs we removed from the buffer
            @buffer_size-= (@bulk_template[:logEntries].to_json.bytesize - 2 - (size-1))

            # Make sure we are always positive
            @buffer_size = @buffer_size >= 0 ? @buffer_size : 0

            DebugLogger.debug "Bufer size after removal is: #{@buffer.join(",").bytesize}"
        end
        @http_sender.send_request(@bulk_template) unless @bulk_template[:logEntries].empty?
    rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect  
    end
end
set_logger_type_name(name) click to toggle source
# File lib/manager.rb, line 126
def set_logger_type_name name
    @logger_type = name
end
update_time_delta_interval() click to toggle source

Sync log timestamps with coralogix server

# File lib/manager.rb, line 184
def update_time_delta_interval
    return
    begin
        #If more than 5 seconds passed from the last sync update
        if ((DateTime.now.strftime('%Q').to_i - @time_delta_last_update) / 1000) >= (60 * SYNC_TIME_UPDATE_INTERVAL) #5 minuts
            res, _time_delta = @http_sender.get_time_sync
            if res
                @time_delta = _time_delta
                @time_delta_last_update = DateTime.now.strftime('%Q').to_i
            end
        end
     rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect  
    end
end
version?() click to toggle source
# File lib/manager.rb, line 46
def version?
    begin
        Gem.loaded_specs['centralized_ruby_logger'].version.to_s
    rescue Exception => e  
        DebugLogger.error e.message  
        DebugLogger.error e.backtrace.inspect
        return '0.0.0'
    end
end