From 8db484ce414c285a9755922d47872f974a2206e5 Mon Sep 17 00:00:00 2001 From: Daniel Molina Date: Mon, 27 Feb 2012 17:34:49 +0100 Subject: [PATCH] feature #924: Add CloudLogger module --- src/cloud/common/CloudAuth.rb | 5 ++-- src/cloud/common/CloudServer.rb | 53 +++++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/cloud/common/CloudAuth.rb b/src/cloud/common/CloudAuth.rb index 23331f79f8..b6203a11ea 100644 --- a/src/cloud/common/CloudAuth.rb +++ b/src/cloud/common/CloudAuth.rb @@ -39,11 +39,12 @@ class CloudAuth # Tokens will be generated if time > EXPIRE_TIME - EXPIRE_MARGIN EXPIRE_MARGIN = 300 - attr_reader :client, :token + attr_reader :client, :token, :logger # conf a hash with the configuration attributes as symbols - def initialize(conf) + def initialize(conf, logger=nil) @conf = conf + @logger = logger @token_expiration_time = Time.now.to_i + EXPIRE_DELTA diff --git a/src/cloud/common/CloudServer.rb b/src/cloud/common/CloudServer.rb index ec3b86134d..feb698a04d 100755 --- a/src/cloud/common/CloudServer.rb +++ b/src/cloud/common/CloudServer.rb @@ -37,7 +37,7 @@ class CloudServer ########################################################################## # Public attributes ########################################################################## - attr_reader :config + attr_reader :config, :logger # Initializes the Cloud server based on a config file # config_file:: _String_ for the server. MUST include the following @@ -45,9 +45,10 @@ class CloudServer # AUTH # VM_TYPE # XMLRPC - def initialize(config) + def initialize(config, logger=nil) # --- Load the Cloud Server configuration file --- @config = config + @logger = logger end # # Prints the configuration of the server @@ -82,3 +83,51 @@ class CloudServer return false end end + +module CloudLogger + require 'logger' + + DEBUG_LEVEL = [ + Logger::ERROR, # 0 + Logger::WARN, # 1 + Logger::INFO, # 2 + Logger::DEBUG # 3 + ] + + # Mon Feb 27 06:02:30 2012 [Clo] [E]: Error message example + MSG_FORMAT = %{%s [Clo] [%s]: %s\n} + + # Mon Feb 27 06:02:30 2012 + DATE_FORMAT = "%a %b %d %H:%M:%S %Y" + + # Patch logger class to be compatible with Rack::CommonLogger + class ::Logger + def write(msg) + info msg.chop + end + end + + def enable_logging(path=nil, debug_level=3) + path ||= $stdout + logger = ::Logger.new(path) + logger.level = DEBUG_LEVEL[debug_level] + logger.formatter = proc do |severity, datetime, progname, msg| + MSG_FORMAT % [ + datetime.strftime(DATE_FORMAT), + severity[0..0], + msg ] + end + + # Add the logger instance to the Sinatra settings + set :logger, logger + + # Use the logger instance in the Rack methods + use Rack::CommonLogger, logger + + helpers do + def logger + settings.logger + end + end + end +end