Class: Swak::Logger

Inherits:
Object show all
Defined in:
lib/swak/logger.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(progname = nil, fout = STDERR) ⇒ Logger

Returns a new instance of Logger.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/swak/logger.rb', line 7

def initialize(progname=nil, fout=STDERR)
  @num_indents = 0
  @do_datetime = true
  @indent_str = "  "
  @progname = progname
  @logger = ::Logger.new(fout)

  @logger.datetime_format = "%m-%d %H:%M:%S"
  @logger.formatter = proc { |severity, datetime, progname, msg|
    prog_str = progname && progname.length > 0 ? "[#{progname}]" : ""
    has_prog = prog_str.length > 0

    date_str = @do_datetime ? datetime.strftime(@logger.datetime_format) : ""
    date_str = "#{indent_str}#{date_str}" if date_str.length > 0  && has_prog
    has_date = date_str.length > 0

    has_prefix = has_prog || has_date

    indent_str = @indent_str * (@num_indents + (has_prefix ? 1 : 0))

    "#{prog_str}#{date_str}#{indent_str}#{msg}\n"
  }
end

Instance Attribute Details

#do_datetimeObject

Returns the value of attribute do_datetime.



5
6
7
# File 'lib/swak/logger.rb', line 5

def do_datetime
  @do_datetime
end

#indent_strObject

Returns the value of attribute indent_str.



5
6
7
# File 'lib/swak/logger.rb', line 5

def indent_str
  @indent_str
end

#loggerObject

Returns the value of attribute logger.



5
6
7
# File 'lib/swak/logger.rb', line 5

def logger
  @logger
end

#num_indentsObject

Returns the value of attribute num_indents.



5
6
7
# File 'lib/swak/logger.rb', line 5

def num_indents
  @num_indents
end

#prognameObject

Returns the value of attribute progname.



5
6
7
# File 'lib/swak/logger.rb', line 5

def progname
  @progname
end

Instance Method Details

#endsectObject



68
69
70
71
# File 'lib/swak/logger.rb', line 68

def endsect
  unindent
  nil
end

#indent(levels = 1) ⇒ Object



31
32
33
34
35
# File 'lib/swak/logger.rb', line 31

def indent(levels=1)
  @num_indents += levels
  @num_indents = [@num_indents, 0].max
  nil
end

#puts(*messages) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/swak/logger.rb', line 43

def puts(*messages)
  messages = [""] if messages.nil? || messages.size == 0

  for msg in messages
    @logger.info(@progname) {msg}
  end

  nil
end

#section(msg) ⇒ Object

Usage:

section("== My Section ==") { some_code }

or

section("== My Section ==")
endsect


58
59
60
61
62
63
64
65
66
# File 'lib/swak/logger.rb', line 58

def section(msg)
  puts(msg)
  indent
  if block_given?
    yield
    unindent
  end
  nil
end

#unindent(levels = 1) ⇒ Object



37
38
39
40
41
# File 'lib/swak/logger.rb', line 37

def unindent(levels=1)
  @num_indents -= levels
  @num_indents = [@num_indents, 0].max
  nil
end