forked from ontoportal/sparql-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
66bfa20
commit 6bc4415
Showing
2 changed files
with
115 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
require 'benchmark' | ||
class SPARQL::Client | ||
class Logging | ||
attr_accessor :logger | ||
attr_accessor :redis | ||
attr_accessor :enabled | ||
|
||
REDIS_EXPIRY = 86_400 # 24 hours | ||
|
||
def initialize(redis:, redis_key: 'query_logs', redis_expiry: REDIS_EXPIRY, logger: nil) | ||
@redis = redis | ||
@logger = logger | ||
@redis_key = redis_key | ||
@redis_expiry = redis_expiry | ||
@enabled = !logger.nil? | ||
end | ||
|
||
def log(query, id: SecureRandom.uuid, cached: nil, user: nil ,&block) | ||
return block.call unless @enabled | ||
|
||
time = Benchmark.realtime do | ||
result = block.call | ||
cached = !result.nil? if cached.nil? | ||
end | ||
info(query, id: id, cached: cached, user: user, execution_time: time) | ||
end | ||
|
||
|
||
def info(query, id: SecureRandom.uuid, cached: 'null', user: 'null', execution_time: 0) | ||
timestamp = Time.now.iso8601 | ||
entry = { | ||
id: id, | ||
timestamp: timestamp, | ||
query: query, | ||
cached: cached, | ||
user: user, | ||
execution_time: execution_time | ||
} | ||
|
||
|
||
@logger&.info("SPARQL: #{query} (#{execution_time}s) | Cached: #{cached} | User: #{user}") | ||
return if @redis.nil? | ||
|
||
key = "#{@redis_key}-#{id}-#{timestamp}" | ||
entry = encode_data(entry) | ||
return if entry.nil? | ||
|
||
@redis.set(key, entry) | ||
@redis.expire(key, @redis_expiry) | ||
end | ||
|
||
def get_logs | ||
keys = @redis.keys("#{@redis_key}-*") | ||
keys.map { |key| Marshal.load(@redis.get(key)) } | ||
end | ||
|
||
def logger=(logger) | ||
@logger = logger | ||
@enabled = !logger.nil? | ||
end | ||
|
||
private | ||
def encode_data(entry) | ||
data = Marshal.dump(entry.to_json) | ||
if data.length > 50e6 # 50MB of marshal object | ||
# avoid large entries to go in the cache | ||
return nil | ||
end | ||
data | ||
end | ||
|
||
def decode_data(data) | ||
Marshal.load(data) | ||
end | ||
|
||
end | ||
end |