Permalink
Browse files

release version 0.3.0 under MIT licensing

  • Loading branch information...
1 parent a690034 commit f6ed3b38dcd9c33d7775b0784655ca9bdbbcb2f6 @paukul paukul committed with paukul Aug 11, 2010
Showing with 324 additions and 0 deletions.
  1. +4 −0 .gitignore
  2. +6 −0 Gemfile
  3. +35 −0 LICENCES
  4. +11 −0 Rakefile
  5. +44 −0 Readme.rdoc
  6. +28 −0 amqp_logging.gemspec
  7. +84 −0 lib/amqp_logging.rb
  8. +97 −0 test/amqp_logger_test.rb
  9. +15 −0 test/test_helper.rb
View
@@ -0,0 +1,4 @@
+.bundle
+.rvmrc
+Gemfile.lock
+*.gem
View
@@ -0,0 +1,6 @@
+source :rubygems
+
+gem "mocha"
+gem "activesupport"
+gem "redgreen"
+gem "bunny"
View
@@ -0,0 +1,35 @@
+The MIT License
+
+Copyright © 2010 Pascal Friederich
+Copyright © 2010 XING AG
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Some portions of this code were derived from the Production Log Analyzer,
+and are subject to this license:
+
+Copyright 2005 Eric Hodel, The Robot Co-op. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+ 3. Neither the names of the authors nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS’’ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
@@ -0,0 +1,11 @@
+require 'rake'
+require 'rake/testtask'
+
+task :default => :test
+
+Rake::TestTask.new do |t|
+ t.libs << "test"
+ t.test_files = FileList['test/**/*_test.rb']
+ t.verbose = true
+end
+
View
@@ -0,0 +1,44 @@
+=AMQPLogging
+
+
+A ruby logger class that logs to an {AMQP}[http://www.amqp.org/] exchange in addition to your default log device.
+
+==Basic Configuration
+By default the logs are routed to the host, exchange and key specified in DEFAULT_OPTIONS.
+You can change the configuration when creating the logger object by specifying an argument hash:
+
+ require 'amqp_logging'
+
+ logging_config = { :routing_key => "applogging",
+ :host => AppConfig.amqp_logging.host,
+ :exchange => AppConfig.amqp_logging.exchange }
+
+ logger = AMQPLogging::Logger.new(config.log_path, logging_config)
+ config.logger = logger
+
+==Routing Keys
+
+You can set the routing key with a string or use a generator that respondes to call,
+receives the logline as the first argument and returns the routing key.
+
+Example:
+
+ # You can use a lambda or whatever responds to #call as the routing key generator
+ AMQPRoutingKeyGenerator = lambda do |logline|
+ if logline =~ /(?:engine\[([^\]]*)\])\: (Completed in|Processing|Session ID)?/
+ key = "logs.app.#{$1}"
+ key << ".statistics" unless $2.nil?
+ else
+ key = "logs.app.system"
+ end
+ key
+ end
+
+ AMQPLogging::Logger.new($stdout, :routing_key => AMQPRoutingKeyGenerator)
+
+==License
+
+Copyright © 2010 Pascal Friederich
+Copyright © 2010 XING AG
+
+See LICENSES for details.
View
@@ -0,0 +1,28 @@
+# Generated by jeweler
+# DO NOT EDIT THIS FILE DIRECTLY
+# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = "amqp_logging"
+ s.version = "0.3.0"
+
+ s.required_rubygems_version = ">= 1.3.1"
+ s.authors = ["Pascal Friederich"]
+ s.date = "2010-08-11"
+ s.email = ["pascal.friederich@xing.com"]
+ s.extra_rdoc_files = ["README.rdoc"]
+ s.files = Dir['lib/**/*.rb']
+ s.homepage = "http://github.com/paukul/amqp_logging"
+ s.rdoc_options = ["--charset=UTF-8"]
+ s.require_paths = ["lib"]
+ s.rubygems_version = "1.3.5"
+ s.summary = "A ruby logger class that logs to an AMQP exchange in addition to your default log device."
+ s.test_files = Dir['test/**/*.rb']
+
+ s.specification_version = 3
+ s.add_runtime_dependency("bunny", [">= 0.6.0"])
+ s.add_runtime_dependency("activesupport", [">= 2.3.0"])
+ s.add_development_dependency("mocha", [">= 0"])
+end
+
View
@@ -0,0 +1,84 @@
+require 'bunny'
+require 'active_support'
+
+module AMQPLogging
+
+ DEFAULT_OPTIONS = {
+ :shift_age => 0,
+ :shift_size => 1048576,
+ :host => "localhost",
+ :exchange => "logging_exchange",
+ :queue => "logging_queue",
+ :routing_key => "logs"
+ }
+
+ RETRY_AFTER = 10.seconds
+
+ class Logger < ::Logger
+ attr_accessor :extra_attributes
+ attr_accessor :errback
+
+ def initialize(logdev, *args)
+ options = args.first.is_a?(Hash) ? DEFAULT_OPTIONS.merge(args.first) : DEFAULT_OPTIONS
+ super(logdev, options[:shift_age], options[:shift_size])
+ @logdev = AMQPLogDevice.new(@logdev, options)
+ @logdev.logger = self
+ end
+ end
+
+ class AMQPLogDevice
+ attr_reader :exchange, :configuration
+ attr_accessor :logger
+
+ def initialize(dev, opts = {})
+ @configuration = opts
+ @fallback_logdev = dev
+ end
+
+ def write(msg)
+ begin
+ if !@paused || @paused <= RETRY_AFTER.ago
+ routing_key = configuration[:routing_key].respond_to?(:call) ? configuration[:routing_key].call(msg).to_s : configuration[:routing_key]
+ exchange.publish(msg, :key => routing_key)
+ end
+ rescue Exception => exception
+ pause_amqp_logging(exception)
+ ensure
+ @fallback_logdev.write(msg)
+ end
+ end
+
+ def close
+ @fallback_logdev.close
+ end
+
+ private
+ def pause_amqp_logging(exception)
+ @paused = Time.now
+ reset_amqp
+ logger.errback.call(exception) if logger.errback && logger.errback.respond_to?(:call)
+ end
+
+ def reset_amqp
+ begin
+ bunny.stop if bunny.connected?
+ rescue
+ # if bunny throws an exception here, its not usable anymore anyway
+ ensure
+ @exchange = @bunny = nil
+ end
+ end
+
+ def exchange
+ bunny.start unless bunny.connected?
+ @exchange ||= bunny.exchange(configuration[:exchange], :type => :topic)
+ end
+
+ def bunny
+ @bunny ||= Bunny.new(:host => @configuration[:host])
+ @bunny
+ end
+ end
+
+end
+
View
@@ -0,0 +1,97 @@
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+
+class TheAMQPLoggerTest < Test::Unit::TestCase
+ def setup
+ @io = StringIO.new
+ end
+
+ test "should be instanciated like a normal logger" do
+ assert_nothing_raised { AMQPLogging::Logger.new(@io) }
+ assert_nothing_raised { AMQPLogging::Logger.new(@io, 2) }
+ assert_nothing_raised { AMQPLogging::Logger.new(@io, 2, 1048576) }
+ end
+
+ test "should be instanciated with an amqp configuration hash" do
+ config = { :queue => "testqueue", :exchange => "testexchange", :host => "testhost", :shift_age => 4, :shift_size => 1338, :routing_key => "foobar" }
+ AMQPLogging::AMQPLogDevice.expects(:new).with(anything, config).returns(stub_everything)
+
+ logger = AMQPLogging::Logger.new(@io, config)
+ end
+
+ test "should write to the default io" do
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(stub_everything('test_exchange'))
+ logger = AMQPLogging::Logger.new(@io)
+ logger.debug "logging something"
+ assert_match "logging something", @io.string
+ end
+
+ test "should pause AMQP logging if exceptions during logging occure" do
+ # in case you ask why not just using mocha expectations here: the rescue in the tested code also rescues the mocha exception
+ # this fake exchange object increases a counter everytime publish is executed so we can check the number of executions
+ class TestExchange; attr_reader :counter; def publish(*args); @counter ||= 0; @counter += 1; raise 'Foo'; end; end
+ logger = AMQPLogging::Logger.new(@io)
+ exchange = TestExchange.new
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(exchange)
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:bunny).returns(stub_everything("bunny stub"))
+ 2.times { logger.debug "This will raise" }
+
+ assert_equal 1, exchange.counter
+ end
+
+ test "should call the logger errback with the exception that occured if one is set" do
+ class FooBarException < Exception; end
+ @called = false
+
+ errback = lambda {|exception| begin raise exception; rescue FooBarException; @called = true; end}
+ raising_exchange = mock("mocked exchange")
+ raising_exchange.expects(:publish).raises(FooBarException)
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(raising_exchange)
+ logger = AMQPLogging::Logger.new(@io)
+ logger.errback = errback
+
+ assert_nothing_raised do
+ logger.debug("this will raise")
+ end
+ assert @called
+ end
+
+ test "should reset the bunny and exchange instance if a exception occures" do
+ raising_exchange = mock("mocked exchange")
+ raising_exchange.expects(:publish).raises("FFFFFFFFUUUUUUUUUU")
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(raising_exchange)
+ logger = AMQPLogging::Logger.new(@io)
+
+ AMQPLogging::AMQPLogDevice.any_instance.expects(:reset_amqp)
+ logger.debug("This will raise and send a notification")
+ end
+
+end
+
+class TheLogDeviceTest < Test::Unit::TestCase
+ test "should initialize the AMQP components correctly" do
+ config = { :queue => "testqueue", :exchange => "testexchange", :host => "testhost", :shift_age => 4, :shift_size => 1338 }
+ bunny_stub = stub_everything("bunny_stub")
+ Bunny.expects(:new).with(:host => "testhost").returns(bunny_stub)
+ bunny_stub.expects(:exchange).with(config[:exchange], :type => :topic).returns(stub("exchange stub"))
+
+ logger = AMQPLogging::Logger.new(StringIO.new, config)
+ logger.debug("foobar")
+ end
+
+ test "should publish the messages with the default routing key" do
+ exchange = mock()
+ exchange.expects(:publish).with("msg\n", :key => "a_routing_key")
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(exchange)
+ AMQPLogging::Logger.new(StringIO.new, {:routing_key => "a_routing_key"}).debug("msg")
+ end
+
+ test "should take a proc argument to generate the routing key" do
+ key_generator = lambda {|msg| msg == "a message\n" }
+ exchange = mock()
+ exchange.expects(:publish).with("a message\n", :key => "true")
+ AMQPLogging::AMQPLogDevice.any_instance.stubs(:exchange).returns(exchange)
+ AMQPLogging::Logger.new(StringIO.new, {:routing_key => key_generator}).debug("a message")
+ end
+end
+
View
@@ -0,0 +1,15 @@
+require 'rubygems'
+require 'test/unit'
+require 'mocha'
+require 'active_support/testing/declarative'
+
+require File.expand_path(File.dirname(__FILE__) + '/../lib/amqp_logging')
+
+begin
+ require 'redgreen' unless ENV['TM_FILENAME']
+rescue LoadError
+end
+
+class Test::Unit::TestCase
+ extend ActiveSupport::Testing::Declarative
+end

0 comments on commit f6ed3b3

Please sign in to comment.