Module: DatabaseLogger

Defined in:
lib/middleware/database_middleware.rb

Overview

Note:

While there were concerns about the performance impact of logging in the redis-rb gem, this middleware is designed to be optional and can be easily enabled or disabled as needed. The performance impact is minimal when logging is disabled, and the benefits during development and debugging often outweigh the slight performance cost when enabled.

DatabaseLogger is RedisClient middleware.

This middleware addresses the need for detailed Database command logging, which was removed from the redis-rb gem due to performance concerns. However, in many development and debugging scenarios, the ability to log Database commands can be invaluable.

Examples:

Enable Database command logging

DatabaseLogger.logger = Logger.new(STDOUT)
RedisClient.register(DatabaseLogger)

See Also:

Class Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.loggerLogger?

Gets/sets the logger instance used by DatabaseLogger.

Returns:

  • (Logger, nil)

    The current logger instance or nil if not set.



29
30
31
# File 'lib/middleware/database_middleware.rb', line 29

def logger
  @logger
end

Instance Method Details

#call(command, _config) ⇒ Object

Note:

The performance impact of this logging is negligible when no logger is set, as it quickly returns control to the Database client. When a logger is set, the minimal overhead is often offset by the valuable insights gained during development and debugging.

Logs the Database command and its execution time.

This method is called for each Database command when the middleware is active. It logs the command and its execution time only if a logger is set.

Parameters:

  • command (Array)

    The Database command and its arguments.

  • _config (Hash)

    The configuration options for the Redis connection.

Returns:

  • (Object)

    The result of the Database command execution.



46
47
48
49
50
51
52
53
54
# File 'lib/middleware/database_middleware.rb', line 46

def call(command, _config)
  return yield unless DatabaseLogger.logger

  start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :microsecond)
  result = yield
  duration = Process.clock_gettime(Process::CLOCK_MONOTONIC, :microsecond) - start
  DatabaseLogger.logger.debug("Redis: #{command.inspect} (#{duration}µs)")
  result
end