You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fw-daemon/sgfw/log.go

69 lines
1.8 KiB

8 years ago
package sgfw
import (
7 years ago
"fmt"
8 years ago
"os"
"syscall"
"unsafe"
"github.com/op/go-logging"
)
8 years ago
// Log level conversion map
var LevelToID = map[int32]string{
8 years ago
int32(logging.ERROR): "error",
int32(logging.WARNING): "warning",
int32(logging.NOTICE): "notice",
int32(logging.INFO): "info",
int32(logging.DEBUG): "debug",
}
8 years ago
// Log level string conversion
var IDToLevel = func() map[string]int32 {
8 years ago
m := make(map[string]int32)
8 years ago
for k, v := range LevelToID {
8 years ago
m[v] = k
}
return m
}()
var log = logging.MustGetLogger("sgfw")
var logFormat = logging.MustStringFormatter(
"%{level:.4s} %{id:03x} %{message}",
)
var ttyFormat = logging.MustStringFormatter(
"%{color}%{time:15:04:05} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}",
)
const ioctlReadTermios = 0x5401
func isTerminal(fd int) bool {
var termios syscall.Termios
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
return err == 0
}
func setupLoggerBackend(lvl logging.Level) (logging.LeveledBackend, logging.LeveledBackend) {
8 years ago
format := logFormat
sleveler := logging.LeveledBackend(nil)
8 years ago
if isTerminal(int(os.Stderr.Fd())) {
format = ttyFormat
fmt.Fprintf(os.Stderr, "Program was launched from a terminal; forcing output to syslog.\n")
sbackend, err := logging.NewSyslogBackend("sgfw")
if err != nil {
log.Error("Could not open syslog backend for logging: %v", err)
} else {
sformatter := logging.NewBackendFormatter(sbackend, logFormat)
sleveler = logging.AddModuleLevel(sformatter)
sleveler.SetLevel(lvl, "sgfw")
}
8 years ago
}
backend := logging.NewLogBackend(os.Stderr, "", 0)
formatter := logging.NewBackendFormatter(backend, format)
leveler := logging.AddModuleLevel(formatter)
leveler.SetLevel(lvl, "sgfw")
return leveler, sleveler
8 years ago
}