juretta.com

Ruby remote logging

December 31, 2005
Tags: Java Logging Ruby
Logger:
# == Synopsis
#
# Simple remote debug class 
#
# == Author
# Stefan Saasen s@juretta.com
#
# == Copyright
# Copyright (c) 2005 juretta.com Stefan Saasen
# Licensed under the same terms as Ruby.
# == Version
# Version 0.1 ($Id: logger.rb 5 2005-01-01 12:51:04Z stefan $)

require 'socket'
require 'singleton'
require 'timeout' 

class SimpleLogger
  include Singleton
  
  def initialize
    @host, @port = "localhost", 3333 # !In use: http://www.iana.org/assignments/port-numbers
    @session = TCPSocket.new(@host, @port)
  end
  
  def method_missing(method, *args)
    if method.to_s =~ /(debug|notice|info|error|warn|fatal)/i
      return self.log(method.to_s, args[0])
    end
  end
  
  def log(level, msg)
    connect! unless @session
    Timeout::timeout(1) do
      @session.puts Time.new.strftime("%Y-%m-%d %H:%M:%S") + \
      " " + "[" + level.upcase + "]: " + msg + "\n" 
    end
    rescue Errno::EPIPE => e
     connect!
     retry
  end
  
  def shutdown
    @session.shutdown
    @session = nil
  end
  
  private
    def connect!
      @session = TCPSocket.new(@host, @port)
    end
end


logger = SimpleLogger.instance
#logger.port = 3030
#logger.host = "192.168.0.10"
logger.debug "debug called"
logger.info "info called"
logger.fatal "Fatal error"

logger.shutdown
Log listener:
# == Synopsis
#
# Log listener.
#
# == Usage
# 
#  ruby log_listener.rb [options]
#  Options: -h | --help -> show the help message
#
# == Version
# Version 0.1 ($Id: log_listener.rb 11 2006-01-02 15:17:41Z stefan $)
	
require 'socket'
require 'optparse'
require 'rdoc/usage'

port = 12123 # Default port

options = OptionParser.new
options.banner = "Usage: ruby log_listener.rb [options]"
options.on('-a', '--about', 'Show the about message') { 
  RDoc::usage 
}
options.on('-h', '--help', 'Show the help message') {
  # Show OPtions usage
  puts options.to_s
  exit
}
options.on('-i', '--interactive', 'Set options interactive') {
  print "Bitte geben Sie einen Port für den LogListener an (Default: #{PORT}): "
  port_input = gets.strip
  port =  (port_input =~ /^(\d+)$/) ? port_input : port
}
options.on('-p', '--port PORT', 'Define the port to listen to') { |p| port = p.to_i }

begin
  rest = options.parse(ARGV) #rescue RDoc::usage('usage')
rescue => ex
  STDERR.puts "E: #{ex.message}"
  STDERR.puts options.to_s
  exit 1
end

# Start the LogListener
puts "Starting listener (localhost:#{port})\nPress \"Enter\" to stop!"

server = TCPServer.new(port)
server_thread = Thread.start do
  while (session = server.accept)
    puts session.gets
    session.close
  end
end


STDIN.gets.strip
server_thread.exit
exit
powerbook:~ sts$ ruby log_listener -p 3333
Log Listener in java:
package com.example;

import java.io.*;
import java.net.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LogListener {

    public static void main(final String argv[]) {
        try {
            new LogListener().run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private final static int PORT = 3333;
    private final static int THREADS = 5;
    private static final Executor EXECUTORS = Executors.newFixedThreadPool(THREADS);

    private void run() throws IOException {
        ServerSocket server = new ServerSocket(PORT);
        System.out.println(String.format("Starting log listener on port %d", PORT));
        while (true) {
            final Socket connectionSocket = server.accept();
            Runnable task = new Runnable() {
                public void run() {
                    try {
                        BufferedReader client = new BufferedReader(
                          new InputStreamReader(connectionSocket.getInputStream()));
                        String line;
                        while(null != (line = client.readLine())) {
                            System.out.println(String.format("[%s]: %s", Thread.currentThread().getName(), line));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            EXECUTORS.execute(task);
        }
    }

}
powerbook:~ sts$ java -cp . LogListener

About

This is the defunct blog of Stefan Saasen.