coralogix_logger 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c6cd392cb48af14a79cb7cf58d901c7d4e1b976e
4
+ data.tar.gz: db4691005c5c7d2056c24ab830d2225ba46d0157
5
+ SHA512:
6
+ metadata.gz: 955a9052ecceab5a80b59630272fb04ad09920c3488783f9c7530ec940ad873461720fde9a35716eb83a92bc0b7b3af5c860593c0b776f88d48cdf47f5d0853b
7
+ data.tar.gz: 63d0f88dc5404058e9ed03d659f79ec0fd21b7589f6f1f4b4c6e4e5bb989b43e210e6c0d099f5f97eb5883a557e22d8ab29272e326a5156c945ff9363e9f2018
data/README.md ADDED
@@ -0,0 +1,63 @@
1
+
2
+ # Croalogix SDK - Ruby Implementation
3
+ This is an implementation of Coralogix Ruby SDK.
4
+
5
+ ## INSTALL
6
+ gem install coralogix_logger
7
+
8
+
9
+ ## GENERAL
10
+
11
+ **Private Key** - A unique ID which represents your company, this Id will be sent to your mail once you register to Coralogix.
12
+
13
+ **Application Name** - The name of your main application, for example, a company named “SuperData” would probably insert the “SuperData” string parameter or if they want to debug their test environment they might insert the “SuperData– Test”.
14
+
15
+ **SubSystem Name** - Your application probably has multiple subsystems, for example: Backend servers, Middleware, Frontend servers etc. in order to help you examine the data you need, inserting the subsystem parameter is vital.
16
+
17
+
18
+
19
+ ## USAGE
20
+
21
+ You must provide the following four variables when creating a Coralogix logger instance.
22
+
23
+ **Private Key** - A unique ID which represents your company, this Id will be sent to your mail once you register to Coralogix.
24
+
25
+ **Application Name** - The name of your main application, for example, a company named “SuperData” would probably insert the “SuperData” string parameter or if they want to debug their test environment they might insert the “SuperData– Test”.
26
+
27
+ **SubSystem Name** - Your application probably has multiple subsystems, for example: Backend servers, Middleware, Frontend servers etc. in order to help you examine the data you need, inserting the subsystem parameter is vital.
28
+
29
+ ##### Example: Coralogix SDK ####
30
+ require 'coralogix_logger'
31
+
32
+ PRIVATE_KEY = "11111111-1111-1111-1111-111111111111"
33
+ APP_NAME = "MyTestApp"
34
+ SUB_SYSTEM = "BL"
35
+
36
+ Coralogix::CoralogixLogger.configure(PRIVATE_KEY, APP_NAME, SUB_SYSTEM)
37
+
38
+ #The common practice is to get an instance of the logger in each class and setting the logger name to the class name.
39
+ logger = Coralogix::CoralogixLogger.get_logger("category1")
40
+
41
+ #Send "Hello World!" message with severity verbose.
42
+ logger.log(Coralogix::Severity::VERBOSE, "Hello World!")
43
+
44
+ #Additional options
45
+ #Severity, category and message parameters are mandatory. The rest of the parameters are optional.
46
+ #If category is not specified, logger name will be used instead
47
+ logger.log(Coralogix::Severity::DEBUG, "Hello World!", category: "my category")
48
+ logger.log(Coralogix::Severity::INFO, "Hello World!", category: "my category", className: "my class")
49
+ logger.log(Coralogix::Severity::WARNING, "Hello World!", category: "my category", className: "my class", methodName: "my method")
50
+ logger.log(Coralogix::Severity::ERROR, "Hello World!", category: "my category", className: "my class", methodName: "my method", threadId: "thread id")
51
+ logger.log(Coralogix::Severity::CRITICAL, "Hello World!", className: "my class", methodName: "my method", threadId: "thread id")
52
+
53
+
54
+ #Using severity methods
55
+ #Only message is mandatory. The rest of the parameters are optional.
56
+ logger.debug("Hello World!")
57
+ logger.verbose("Hello World!", className: "my class")
58
+ logger.info("Hello World!", className: "my class", methodName: "my method")
59
+ logger.warning("Hello World!", className: "my class", methodName: "my method", threadId="thread id")
60
+ logger.error("Hello World!", className: "my class", methodName: "my method", threadId="thread id")
61
+ logger.critical("Hello World!", category: "my category", className: "my class", methodName: "my method", threadId="thread id")
62
+
63
+
data/lib/constants.rb ADDED
@@ -0,0 +1,53 @@
1
+ module Coralogix
2
+
3
+ #Maximum log buffer size
4
+ MAX_LOG_BUFFER_SIZE = 12582912 #12mb
5
+
6
+ #Maximum chunk size
7
+ MAX_LOG_CHUNK_SIZE = 1572864 #1.5 mb
8
+
9
+ #Bulk send interval in normal mode.
10
+ NORMAL_SEND_SPEED_INTERVAL = 500.0 / 1000
11
+
12
+ #Bulk send interval in fast mode.
13
+ FAST_SEND_SPEED_INTERVAL = 100.0 / 1000
14
+
15
+ #Corologix severity mapper
16
+ SEVERITIES = {:debug => 1, :verbose => 2, :info => 3, :warning => 4, :error => 5, :critical => 6}
17
+
18
+
19
+ module Severity
20
+ DEBUG = 1
21
+ VERBOSE = 2
22
+ INFO = 3
23
+ WARNING = 4
24
+ ERROR = 5
25
+ CRITICAL = 6
26
+ end
27
+
28
+
29
+ #Coralogix logs url
30
+ CORALOGIX_LOG_URL = "https://api.coralogix.com:443/api/v1/logs"
31
+
32
+ #Default private key
33
+ FAILED_PRIVATE_KEY = "9626c7dd-8174-5015-a3fe-5572e042b6d9"
34
+
35
+ #Default application name
36
+ FAILED_APP_NAME = "FAILED_APP_NAME"
37
+
38
+ #Default subsystem name
39
+ FAILED_SUB_SYSTEM = "FAILED_SUB_NAME"
40
+
41
+ #Default log file name
42
+ LOG_FILE_NAME = "coralogix.sdk.log"
43
+
44
+ #Default http timeout
45
+ HTTP_TIMEOUT = 30
46
+
47
+ #Number of attempts to retry http post
48
+ HTTP_SEND_RETRY_COUNT = 5
49
+
50
+ #Interval between failed http post requests
51
+ HTTP_SEND_RETRY_INTERVAL = 2
52
+
53
+ end
@@ -0,0 +1,90 @@
1
+ require_relative 'manager'
2
+ require_relative 'debug_logger'
3
+ require_relative 'httpsender'
4
+ require_relative 'constants'
5
+
6
+ module Coralogix
7
+
8
+ class CoralogixLogger
9
+ # Set 'new' method to be a private method.
10
+ # This way it won't be possible to create a new intance of this class from outside.
11
+ private_class_method :new
12
+
13
+ # Constructor.
14
+ #
15
+ # @param name - logger name.
16
+ def initialize name
17
+ @category = name
18
+ end
19
+
20
+ # A getter for debug_mode.
21
+ # Default value is false.
22
+ # When set to true the coralogix logger will print output messages to a console and a file.
23
+ #
24
+ # @return [boolean] - true or false. (Default is false)
25
+ def self.debug_mode?
26
+ DebugLogger.debug_mode
27
+ end
28
+
29
+ # A setter for debug_mode.
30
+ # Default value is false.
31
+ # When set to true the coralogix logger will print output messages to a console and a file.
32
+ #
33
+ # @param value - true or false. (Default is false)
34
+ def self.debug_mode=(value)
35
+ DebugLogger.debug_mode=value
36
+ end
37
+
38
+ # A setter for disable_proxy.
39
+ # By default HTTP object will use proxy environment variable if exists. In some cases this migh be an issue
40
+ # When set to false the HTTP object will ignore any proxy.
41
+ #
42
+ # @param value - true or false. (Default is false)
43
+ def self.disable_proxy=(value)
44
+ CoralogixHTTPSender.disable_proxy=value
45
+ end
46
+
47
+ # A class method (static) to return a new instance of the current class.
48
+ # This is the most common pattern when using logging.
49
+ #
50
+ # @param name - name of the logger. The category. Usually this will be a new name for every class or a logical unit.
51
+ # @return [CoralogixLogger] return a new instance of CoralogixLogger.
52
+ def self.get_logger name
53
+ #Return a new instance of the current class.
54
+ CoralogixLogger.send(:new, name)
55
+ end
56
+
57
+ # Configure coralogix logger with customer specific values
58
+ #
59
+ # @param private_key - private key
60
+ # @param app_name - application name
61
+ # @param sub_system - sub system name
62
+ # @return [boolean] return a true or false.
63
+ def self.configure private_key, app_name, sub_system
64
+ LoggerManager.configure(:privateKey => private_key, :applicationName => app_name, :subsystemName => sub_system) unless LoggerManager.configured
65
+ end
66
+
67
+ # Log a message.
68
+ #
69
+ # @param severity - log severity
70
+ # @param message - log message
71
+ # @param category - log category
72
+ # @param className - log class name
73
+ # @param methodName - log method name
74
+ # @param threadId - log thread id
75
+ def log severity, message, category: @category, className: "", methodName: "", threadId: ""
76
+ LoggerManager.add_logline message, severity, category, :className => className, :methodName => methodName, :threadId => threadId
77
+ end
78
+
79
+ # Create log methods for each severity.
80
+ # This is a ruby thing. If you are writing in other languages just create a method for each severity.
81
+ # For instance, for info severity it will create a method:
82
+ # def info message, category: @category, className: "", methodName: "", threadId: ""
83
+ SEVERITIES.keys.each do |severity|
84
+ define_method("#{severity}") do |message, category: @category, className: "", methodName: "", threadId: ""|
85
+ LoggerManager.add_logline message, SEVERITIES["#{__method__}".to_sym], category, :className => className, :methodName => methodName, :threadId => threadId
86
+ end
87
+ end
88
+ end
89
+
90
+ end
@@ -0,0 +1,56 @@
1
+ require 'logger'
2
+
3
+ module Coralogix
4
+ # @private
5
+ class DebugLogger
6
+
7
+ def self.initialize
8
+ begin
9
+ @mutex = Mutex.new
10
+ @debug = false
11
+ rescue Exception => e
12
+ if @debug
13
+ puts e.message
14
+ puts e.backtrace.inspect
15
+ end
16
+ end
17
+ end
18
+
19
+ def self.debug_mode?
20
+ @debug
21
+ end
22
+
23
+ def self.debug_mode=(value)
24
+ begin
25
+ @debug = value
26
+ if value
27
+ @logger = Logger.new(LOG_FILE_NAME, 1, 10485760)
28
+ else
29
+ @logger.close unless @logger == nil
30
+ @logger = nil
31
+ end
32
+ rescue Exception => e
33
+ if @debug
34
+ puts e.message
35
+ puts e.backtrace.inspect
36
+ end
37
+ end
38
+ end
39
+
40
+ Logger::Severity.constants.each do |level|
41
+ define_singleton_method("#{level.downcase}") do |*args|
42
+ @mutex.synchronize do
43
+ if @debug
44
+ puts "#{__method__.upcase}: #{Time.now.strftime('%H:%M:%S.%L')} - #{args}"
45
+ @logger.send("#{__method__}", args)
46
+ end
47
+ end
48
+ end
49
+ end
50
+
51
+
52
+ initialize
53
+
54
+ end
55
+
56
+ end
data/lib/httpsender.rb ADDED
@@ -0,0 +1,73 @@
1
+ require 'net/http'
2
+ require 'json'
3
+ require_relative 'constants'
4
+ require_relative 'debug_logger'
5
+ require 'openssl'
6
+ require 'benchmark'
7
+
8
+ module Coralogix
9
+ # @private
10
+ module CoralogixHTTPSender
11
+
12
+ @initialized = false
13
+
14
+ def CoralogixHTTPSender.disable_proxy value
15
+ @disable_proxy = value
16
+ end
17
+
18
+ def CoralogixHTTPSender.disable_proxy=(value)
19
+ @disable_proxy = value
20
+ end
21
+
22
+ def CoralogixHTTPSender.initialize
23
+ begin
24
+ @uri = URI(CORALOGIX_LOG_URL)
25
+ if(@disable_proxy)
26
+ #@http = Net::HTTP.start(@uri.host, @uri.port, p_addr=nil, p_port=nil, :use_ssl => true, :verify_mode=> OpenSSL::SSL::VERIFY_NONE)
27
+ @http = Net::HTTP.new(@uri.host, @uri.port, p_addr=nil, p_port=nil)
28
+ else
29
+ #@http = Net::HTTP.start(@uri.host, @uri.port, :use_ssl => true, :verify_mode=> OpenSSL::SSL::VERIFY_NONE)
30
+ @http = Net::HTTP.new(@uri.host, @uri.port)
31
+ end
32
+ @http.use_ssl = true
33
+ @http.keep_alive_timeout = 10
34
+ @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
35
+ @http.read_timeout = HTTP_TIMEOUT # seconds
36
+ @req = Net::HTTP::Post.new(@uri.path, 'Content-Type' => 'application/json')
37
+ @initialized = true
38
+ rescue Exception => e
39
+ DebugLogger.error e.message
40
+ DebugLogger.error e.backtrace.inspect
41
+ @initialized = false
42
+ end
43
+ return @initialized
44
+ end
45
+
46
+ # A helper method to post http request
47
+ #
48
+ # @param bulk - JSON bulk containing the log entries
49
+ def CoralogixHTTPSender.send_request bulk
50
+
51
+ self.initialize unless @initialized
52
+ attempt = 0
53
+ while attempt < HTTP_SEND_RETRY_COUNT
54
+ begin
55
+ DebugLogger.info "About to send bulk to Coralogix server. Attempt number: #{attempt+1}"
56
+ @req.body = bulk.to_json
57
+ DebugLogger.debug Benchmark.measure {
58
+ res = @http.request(@req)
59
+ DebugLogger.info "Successfully sent bulk to Coralogix server. Result is: #{res.code}"
60
+ }.to_s
61
+ return true
62
+ rescue Exception => e
63
+ DebugLogger.error e.message
64
+ DebugLogger.error e.backtrace.inspect
65
+ end
66
+ attempt+=1;
67
+ DebugLogger.error "Failed to send bulk. Will retry in: #{HTTP_SEND_RETRY_INTERVAL} seconds..."
68
+ sleep HTTP_SEND_RETRY_INTERVAL
69
+ end
70
+ end
71
+ end
72
+
73
+ end
data/lib/manager.rb ADDED
@@ -0,0 +1,128 @@
1
+ #require 'net/http'
2
+ #require 'json'
3
+ require_relative 'httpsender'
4
+ require_relative 'constants'
5
+ require_relative 'debug_logger'
6
+ #require "benchmark"
7
+
8
+ module Coralogix
9
+ # @private
10
+ class LoggerManager
11
+
12
+ class << self
13
+ attr_accessor :configured
14
+ end
15
+
16
+ def self.initialize
17
+ @buffer = []
18
+ @buffer_size = 0
19
+ @bulk_template = {:privateKey => FAILED_PRIVATE_KEY, :applicationName => FAILED_APP_NAME, :subsystemName => FAILED_SUB_SYSTEM}
20
+ @mutex = Mutex.new
21
+ self.run
22
+ end
23
+
24
+ # Add a log line to our buffer.
25
+ #
26
+ # @param **args - Customer parameters:
27
+ # privateKey - Private Key
28
+ # applicationName - Application name
29
+ # subsystemName - Subsystem name
30
+ # @return [boolean] return true for success or false for failure.
31
+ def self.configure **args
32
+ begin
33
+ @bulk_template = args.merge({:computerName => `hostname`.strip})
34
+ configured = true
35
+ rescue
36
+ return false
37
+ end
38
+ end
39
+
40
+ # Add a log line to our buffer.
41
+ #
42
+ # @param message - The logs message. This is a must parameter.
43
+ # @param severity - The severity of the log message. This is a must parameter.
44
+ # @param category - The category (logger name) of the message. This is a must parameter.
45
+ # @param **args - Optional parameters. It can be:
46
+ # className - The class name where the log message was sent from.
47
+ # methodName - The method name where the log message was sent from.
48
+ # threadId - The thread id where the log message was sent from.
49
+ # @return [boolean] return true for success or false for failure.
50
+ def self.add_logline message, severity, category, **args
51
+ begin
52
+ @mutex.synchronize do
53
+ if @buffer_size < MAX_LOG_BUFFER_SIZE
54
+ #Combine a logentry from the must parameters together with the optional one.
55
+ new_entry = {:text => message, :timestamp => Time.now.utc.to_f * 1000, :severity => severity, :category => category}.merge(args)
56
+ @buffer << new_entry
57
+ #Updte the buffer size to reflect the new size.
58
+ @buffer_size+=new_entry.to_json.bytesize
59
+ else
60
+ DebugLogger.warn "Buffer is full. Ignoring current message."
61
+ end
62
+ end
63
+ rescue Exception => e
64
+ DebugLogger.error e.message
65
+ DebugLogger.error e.backtrace.inspect
66
+ return false
67
+ end
68
+ return true
69
+ end
70
+
71
+ # Send bulk from the buffer
72
+ def self.send_bulk
73
+ begin
74
+ @mutex.synchronize do
75
+ # Total buffer size
76
+ size = @buffer.size
77
+
78
+ # If the size is bigger than the maximum allowed chunk size then split it by half.
79
+ # Keep splitting it until the size is less than MAX_LOG_CHUNK_SIZE
80
+ while @buffer.take(size).join(",").bytesize > MAX_LOG_CHUNK_SIZE
81
+ size=size/2;
82
+ end
83
+
84
+ DebugLogger.info "Checking buffer size. Total log entries is: #{size}"
85
+ @bulk_template[:logEntries] = @buffer.shift(size)
86
+
87
+ # Extract from the buffer size the total amount of the logs we removed from the buffer
88
+ @buffer_size-= (@bulk_template[:logEntries].to_json.bytesize - 2 - size-1)
89
+
90
+ DebugLogger.info "Bufer size after removal is: #{@buffer.join(",").bytesize}"
91
+ end
92
+ CoralogixHTTPSender.send_request(@bulk_template) unless @bulk_template[:logEntries].empty?
93
+ rescue Exception => e
94
+ DebugLogger.error e.message
95
+ DebugLogger.error e.backtrace.inspect
96
+ end
97
+ end
98
+
99
+ # Start timer execution.
100
+ # The timer should send every X seconds logs from the buffer.
101
+ def self.run
102
+ begin
103
+ timer_thread = Thread.new do
104
+ while true
105
+ # Send log bulk
106
+ self.send_bulk
107
+
108
+ # Check when is the next time we should send logs?
109
+ # If we already have at least half of the max chunk size then we are working in fast mode
110
+ next_check_interval = @buffer_size > (MAX_LOG_CHUNK_SIZE / 2) ? FAST_SEND_SPEED_INTERVAL : NORMAL_SEND_SPEED_INTERVAL
111
+ DebugLogger.debug "Next buffer check is scheduled in #{next_check_interval} seconds"
112
+ sleep next_check_interval
113
+ end
114
+ end
115
+
116
+ #Set thread priority to a high number
117
+ timer_thread.priority = 100
118
+ rescue Exception => e
119
+ DebugLogger.error e.message
120
+ DebugLogger.error e.backtrace.inspect
121
+ return false
122
+ end
123
+ end
124
+
125
+ initialize
126
+ end
127
+
128
+ end
metadata ADDED
@@ -0,0 +1,48 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: coralogix_logger
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.4
5
+ platform: ruby
6
+ authors:
7
+ - Royee Goldberg
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-11-29 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Coralogix ruby sdk to send logs to Coralogix server.
14
+ email: royee@coralogix.com
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - README.md
20
+ - lib/constants.rb
21
+ - lib/coralogix_logger.rb
22
+ - lib/debug_logger.rb
23
+ - lib/httpsender.rb
24
+ - lib/manager.rb
25
+ homepage: http://www.coralogix.com
26
+ licenses: []
27
+ metadata: {}
28
+ post_install_message:
29
+ rdoc_options: []
30
+ require_paths:
31
+ - lib
32
+ required_ruby_version: !ruby/object:Gem::Requirement
33
+ requirements:
34
+ - - '>='
35
+ - !ruby/object:Gem::Version
36
+ version: 2.0.0
37
+ required_rubygems_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - '>='
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ requirements: []
43
+ rubyforge_project:
44
+ rubygems_version: 2.4.8
45
+ signing_key:
46
+ specification_version: 4
47
+ summary: Coralogix Ruby Logger SDK
48
+ test_files: []