logger.go 1.77 KB
Newer Older
Lukas Matt's avatar
Lukas Matt committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package federation
//
// GangGo Diaspora Federation Library
// Copyright (C) 2017 Lukas Matt <lukas@zauberstuhl.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import (
  "fmt"
  "runtime"
  "regexp"
24 25
  "os"
  "log"
Lukas Matt's avatar
Lukas Matt committed
26 27
)

28 29 30 31 32 33 34
const (
  LOG_C_RED = "\033[31m"
  LOG_C_YELLOW = "\033[33m"
  LOG_C_RESET = "\033[0m"
)

var (
35
  logger Logger
36 37 38 39
  defaultPrefix string
)

func init() {
Lukas Matt's avatar
Lukas Matt committed
40 41 42 43 44 45 46 47 48 49
  pc := make([]uintptr, 10)  // at least 1 entry needed
  runtime.Callers(3, pc)
  f := runtime.FuncForPC(pc[0])
  file, line := f.FileLine(pc[0])
  regex, _ := regexp.Compile(`\/([^\/]+?\.go)`)
  result := regex.FindAllStringSubmatch(file, -1)
  if len(result) == 1 {
    file = result[0][1]
  }

50
  defaultPrefix = fmt.Sprintf("%s:%d %s ", file, line, f.Name())
51
  logger = Logger{log.New(os.Stdout, defaultPrefix, log.Lshortfile)}
52 53
}

54
type LogWriter interface {
55 56
  Println(v... interface{})
}
Lukas Matt's avatar
Lukas Matt committed
57

58 59
type Logger struct{
  LogWriter
60 61
}

62 63
func SetLogger(writer LogWriter) {
  logger = Logger{writer}
Lukas Matt's avatar
Lukas Matt committed
64 65
}

66 67
func (l Logger) Info(values... interface{}) {
  l.Println(values...)
Lukas Matt's avatar
Lukas Matt committed
68 69
}

70
func (l Logger) Error(values... interface{}) {
71
  l.Info(LOG_C_RED, values, LOG_C_RESET)
Lukas Matt's avatar
Lukas Matt committed
72 73
}

74
func (l Logger) Warn(values... interface{}) {
75
  l.Info(LOG_C_YELLOW, values, LOG_C_RESET)
Lukas Matt's avatar
Lukas Matt committed
76
}