pupirka
/
device.go
98 строк · 2.9 Кб
1package main2
3import (4"fmt"5"github.com/sirupsen/logrus"6"gopkg.in/natefinch/lumberjack.v2"7"os/exec"8"strings"9)
10
11func (device *Device) LogConfig() {12device.Logdevice = logrus.New()13
14switch ConfigV.GetString("log.format") {15case "text":16device.Logdevice.SetFormatter(&logrus.TextFormatter{})17case "json":18device.Logdevice.SetFormatter(&logrus.JSONFormatter{})19default:20device.Logdevice.SetFormatter(&logrus.TextFormatter{})21}22
23device.Logdevice.SetOutput(&lumberjack.Logger{24Filename: fmt.Sprintf("%s/%s/%s", ConfigV.GetString("path.log"), device.Name, "device.log"),25MaxSize: ConfigV.GetInt("log.maxsize"),26MaxAge: ConfigV.GetInt("log.maxday"),27MaxBackups: ConfigV.GetInt("log.maxbackups"),28LocalTime: true,29Compress: false,30})31
32device.Logdevice.SetLevel(LogConsole.GetLevel())33}
34
35func (device *Device) LogError(s ...interface{}) {36device.Logdevice.Errorln(s...)37device.Logdevice.Infoln(s...)38device.Logdevice.Debugln(s...)39device.Logdevice.Warnln(s...)40LogConsole.Errorln(s...)41LogGlobal.Errorln(s...)42}
43func (device *Device) LogInfo(s ...interface{}) {44device.Logdevice.Infoln(s...)45device.Logdevice.Debugln(s...)46}
47func (device *Device) LogWarn(s ...interface{}) {48device.Logdevice.Warnln(s...)49device.Logdevice.Debugln(s...)50LogGlobal.Warnln(s...)51}
52func (device *Device) LogDebug(s ...interface{}) {53device.Logdevice.Debug(s...)54LogGlobal.Debugln(s...)55LogConsole.Debugln(s...)56}
57
58func (device *Device) Hook() {59device.LogDebug(fmt.Sprintf("Run Hook '%s': Device %s", device.StatusJob, device.Name))60var command string61switch device.StatusJob {62case "skip":63command = device.DeviceHooks.Skip64case "error":65command = device.DeviceHooks.Error66case "backup":67command = device.DeviceHooks.Backup68default:69command = ""70}71if command == "" {72device.LogDebug(fmt.Sprintf("Hook '%s': No command for hook: Device %s", device.StatusJob, device.Name))73return74}75device.LogDebug(fmt.Sprintf("Hook '%s': Command for hook '%s': Device %s", device.StatusJob, command, device.Name))76rVariable := []string{"%name", "%parent", "%filename", "%address", "%portssh"}77rValue := []string{device.Name, device.Parent, device.BackupFileName, device.Address, fmt.Sprintf("%d", device.PortSSH)}78execCommand := strings.NewReplacer(zipStringsForReplacer(rVariable, rValue)...).Replace(command)79device.LogDebug(fmt.Sprintf("Hook '%s': Command Compile for hook '%s': Device %s", device.StatusJob, execCommand, device.Name))80execComandi := strings.Fields(execCommand)81cmd := exec.Command(execComandi[0], execComandi[1:]...)82device.LogDebug(fmt.Sprintf("Hook '%s': Hook Runiing: Device %s", device.StatusJob, device.Name))83err := cmd.Start()84if err != nil {85device.LogError("Error running command: ", err)86return87}88
89}
90
91func zipStringsForReplacer(a1, a2 []string) []string {92r := make([]string, 2*len(a1))93for i, e := range a1 {94r[i*2] = e95r[i*2+1] = a2[i]96}97return r98}
99