#
# log.rb -- Log Class
#
# Author: IPR -- Internet Programming with Ruby -- writers
# Copyright (C) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
#
# $IPR: log.rb,v 1.13 2002/02/05 20:20:32 gotoyuzo Exp $

module WEBrick
  class Log

    # log-level constant
    FATAL, ERROR, WARN, INFO, DEBUG = 1, 2, 3, 4, 5

    attr_accessor :level, :time_format

    def initialize(log_file=nil, level=nil)
      if log_file.kind_of?(String)
        @log = open(log_file, "a+")
        @opened = true
      else
        @log = log_file || $stderr
        @opened = false
      end
      @log.sync = true if @log.respond_to?("sync=")
      @level = level || INFO
      @time_format = "[%Y-%m-%d %H:%M:%S] "
      info "Logging start (level=#{@level})."
    end

    def close
      info "Logging end."
      @log.close if @opened
      @log = nil
    end

    def log(level, data)
      if @log && level <= @level
        str = ""
        str << Time.now.strftime(@time_format) if @time_format
        str << data
        @log << str
      end
    end

    def fatal(msg) log(FATAL, "FATAL " << format(msg)); end
    def error(msg) log(ERROR, "ERROR " << format(msg)); end
    def warn(msg)  log(WARN,  "WARN  " << format(msg)); end
    def info(msg)  log(INFO,  "INFO  " << format(msg)); end
    def debug(msg) log(DEBUG, "DEBUG " << format(msg)); end

    def fatal?; @level >= FATAL; end
    def error?; @level >= ERROR; end
    def warn?;  @level >= WARN; end
    def info?;  @level >= INFO; end
    def debug?; @level >= DEBUG; end

    def backtrace(ex)
      warn("#{type}#backtrace is obsolete; use #{type}#error")
      error(ex)
    end

    def format(arg)
      str = if arg.is_a?(Exception)
        "#{arg.type}: #{arg.message}\n\t" <<
        arg.backtrace.join("\n\t")
      elsif arg.respond_to?(:to_str)
        arg.to_str
      else
        arg.inspect
      end
      str << "\n"
    end
    private :format

  end
end
