#
# Copyright (C) 2002-2004 Satoru Takabayashi <satoru@namazu.org> 
# Copyright (C) 2003-2005 Kouichirou Eto
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of 
# the GNU General Public License version 2.
#

require "thread"
$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/ml-utils"

module QuickML
  class Logger
    def initialize (log_filename, verbose_mode = nil)
      @mutex = Mutex.new
      @log_file = File.safe_open(log_filename, "a")
      @log_file.sync = true
      @verbose_mode = verbose_mode
    end

    def log (msg)
      puts_log(msg)
    end

    def vlog (msg)
      puts_log(msg) if @verbose_mode
    end

    def reopen
      @mutex.synchronize {
	log_filename = @log_file.path
      	@log_file.close
      	@log_file = File.safe_open(log_filename, "a")
      }
    end

    private

    def puts_log (msg)
      @mutex.synchronize {
	time = Time.now.strftime("%Y-%m-%dT%H:%M:%S")
	@log_file.puts "#{time}: #{msg}"
      }
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  $debug = true
end

if $debug
  class TestMLLogger < Test::Unit::TestCase
    def test_all
      logger = QuickML::Logger.new("testlog.txt")
      logger.log("t")
      str = open("testlog.txt"){|f| f.read }
      assert_match(/: t\n/, str)
    end
  end
end
