日志抛出

``` package main import ( "flag" "fmt" "os" "os/exec" "strconv" "strings" "time" ) var ( i string conerrstr string conErrstr string conbool bool conBool bool timecon string ) //计算抛出日志的时间和记录错误的时间比对 func subtime(logtime, errtime string) time.Duration { a, _ := time.Parse("2006-01-02 15:04:05", logtime) b, _ := time.Parse("2006-01-02 15:04:05", errtime) // 取较大时间 var c time.Duration if a.After(b) { c = a.Sub(b) } else { c = b.Sub(a) } return c } func tracefile(str_content string) string { PWD := strings.TrimSpace(Subprocess("pwd")) + "/" + "npds-metrics.log" fd, _ := os.OpenFile(PWD, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) fd_time := time.Now().Format("2006-01-02 15:04:05") fd_content := strings.Join([]string{"====== 日志写入时间", fd_time, "=====\n", str_content, ""}, "") buf := []byte(fd_content) fd.Write(buf) fd.Close() return fd_time } func Subprocess(command string) string { cmd := exec.Command("bash", "-c", command) output, _ := cmd.Output() // output, err := cmd.Output() // if err != nil { // tracefile(fmt.Sprintf("Execute Shell:%s failed with error:%s\n", command, err.Error())) // } return string(output) } func getError(timecon string,pwds []string) { for _, dir := range pwds { tailcon , _ :=strconv.Atoi(timecon) cmd := fmt.Sprintf("tail -%d /home/NPDS/%s/logs/inspector.log", tailcon * 5, dir) result := Subprocess(cmd) conbool,conBool = false,false for _, i = range strings.Split(result, "\n") { errstr := fmt.Sprintln("文件夹: ", dir, "<= ERROR:", "=>", i) if len(i) > 101 { if i[51:101] == "每秒客户端消费的有效流量大小为:0.0M" { logtime := time.Now().Format("2006-01-02 15:04:05") errtime := i[8:27] c := subtime(logtime, errtime) contime, _ := strconv.Atoi(timecon) d := c - time.Duration(contime) if int(d) < contime*1000*1000*1000 { conbool = true conerrstr = errstr } } } if len(i) > 51 { if i[1:5] != "INFO" { logtime := time.Now().Format("2006-01-02 15:04:05") errtime := i[8:27] c := subtime(logtime, errtime) contime, _ := strconv.Atoi(timecon) d := c - time.Duration(contime) if i[50:63] == "handle error" && int(d) < contime*1000*1000*1000 { conBool = true conErrstr = errstr } if i[50:63] != "handle error" && int(d) < contime*1000*1000*1000 { tracefile(errstr) } // if int(d) < contime*1000*1000*1000 { // tracefile(errstr) // } } } } if conbool { tracefile(conerrstr) } if conBool{ tracefile(conErrstr) } } } func main() { flag.StringVar(&timecon, "t", "30", "读取时间参数,默认30条") //cmd flag.Parse() pwd := Subprocess("ls /home/NPDS|grep -E NPDS-Client[0-9]") pwds := strings.Split(pwd, "\n") pwds = pwds[:len(pwds)-1] fmt.Println("收集的文件夹:", pwds) fmt.Println("读取条数:", timecon) for{ getError(timecon,pwds) sleeptime,err := strconv.Atoi(timecon) if err != nil { fmt.Println("-t 的参数请输入数字!") } time.Sleep(time.Second * time.Duration(sleeptime)) } } ```