summaryrefslogtreecommitdiff
path: root/lib/byteback/log.rb
blob: 6753ca86ad96793bdd63c1f951b21326efd7739c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
require 'logger'
require 'syslog'

module Byteback

  #
  # Translates Ruby's Logger calls to similar calls to Syslog
  # (implemented in Ruby 2.0 as Syslog::Logger).
  #
  # We need to neuter % signs which are taken as format strings.
  #
  class SyslogProxy
    class << self
      def debug(m)
        log_nopc(Syslog::LOG_DEBUG, m)
      end

      def info(m)
        log_nopc(Syslog::LOG_INFO, m)
      end
      
      def warn(m)
        log_nopc(Syslog::LOG_WARNING, m)
      end
      
      def error(m)
        log_nopc(Syslog::LOG_ERR, m)
      end
      
      #
      # syslog(3) says:
      #
      # LOG_EMERG means "system is unusable"
      # LOG_ERR   means "error conditions"
      #
      # Errors might be fatal to Byteback, but they're unlikely to make the
      # whole server unusable.  So lets dial this down to ERR from EMERG.
      #
      def fatal(m)
        log_nopc(Syslog::LOG_ERR, m)
      end

      def log_nopc(level, m)
        Syslog.log(level, m.gsub('%', '%%'))
      end
    end
  end

  # Log proxy class that we can include in our scripts for some simple
  # logging defaults.
  #
  module Log
    @@me = File.expand_path($PROGRAM_NAME).split('/').last


    #
    #  If we're running interactively then we have simple logging.
    #
    if STDIN.tty?

      #
      #  We log to the console.
      #
      logger = Logger.new(STDERR)
      logger.level = Logger::DEBUG
      logger.formatter = proc { |severity, _datetime, _progname, msg|
        if severity == 'FATAL' || severity == 'ERROR'
          "*** #{msg}\n"
        else
          "#{msg}\n"
        end
      }
      @@logger = logger
    else

      #
      #  Otherwise we log via our Syslog-proxy.
      #
      Syslog.open(@@me)
      @@logger = SyslogProxy
    end

    
    def debug(*a)
      @@logger.__send__(:debug, *a)
    end
    
    def info(*a)
      @@logger.__send__(:info, *a)
    end
    
    def warn(*a)
      @@logger.__send__(:warn, *a)
    end
    
    def fatal(*a)
      @@logger.__send__(:fatal, *a)
      exit 1
    end
    
    def error(*a)
      @@logger.__send__(:error, *a)
    end
  end
end