代码
package main
import (
"github.com/sirupsen/logrus"
"gopkg.in/urfave/cli.v1"
"io"
"net/http"
"os"
"os/signal"
"sync"
"time"
)
var log = logrus.StandardLogger()
var successCount int64
var failCount int64
var wait sync.WaitGroup
func init() {
logInit()
}
func main() {
wait.Add(1)
url, interval, duration := parsingParam()
log.Infof("服务运行PID: %d", os.Getpid())
log.Info("监控地址 ", url)
log.Infof("每隔%d秒检查一次", interval)
log.Infof("脚本将运行%d秒", duration)
go schedule(interval, apiCheck, url)
go gracefulShutdown(duration)
go timeOut(duration)
wait.Wait()
printStatic()
}
func gracefulShutdown(duration int64) {
defer wait.Done()
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
}
func timeOut(duration int64) {
defer wait.Done()
after := time.After(time.Duration(duration) * time.Second)
<-after
}
func parsingParam() (string, int64, int64) {
var url string
var interval int64
var duration int64
app := cli.NewApp()
app.Name = "api监控"
app.Usage = "持续监控api"
app.UsageText = "./apiCheck -u https://www.baidu.com -i 1 -d 60"
app.Version = "1.0.0"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "url,u",
Value: "https://www.baidu.com",
Usage: "监控地址",
Destination: &url,
},
cli.Int64Flag{
Name: "interval,i",
Value: 3,
Usage: "每隔x秒检查一次",
Destination: &interval,
}, cli.Int64Flag{
Name: "duration,d",
Value: 3600,
Usage: "脚本运行时间",
Destination: &duration,
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
return url, interval, duration
}
func schedule(second int64, f func(string), url string) {
ticker := time.NewTicker(time.Duration(second) * time.Second)
go func() {
for range ticker.C {
go f(url)
}
}()
}
func apiCheck(url string) {
resp, err := http.Get(url)
if err != nil {
log.Error(url, " error:", err)
failCount++
return
}
defer resp.Body.Close()
code := resp.StatusCode
if code == 200 {
log.Info(url, " code:", code)
successCount++
} else {
log.Error(url, " code:", code)
failCount++
}
}
func printStatic() {
log.Infof("检查任务完成")
log.Infof("请求次数:%d", successCount+failCount)
log.Infof("请求成功:%d", successCount)
log.Infof("请求失败:%d", failCount)
}
func logInit() {
log.Level = logrus.DebugLevel
log.Formatter = &logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05",
ForceColors: true,
FullTimestamp: true,
}
file, err := os.OpenFile("apiCheck.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0755)
if err != nil {
log.Warn("create log file fail " + err.Error())
log.Out = os.Stdout
} else {
mw := io.MultiWriter(file, os.Stdout)
log.Out = mw
}
}
效果

image.png
网友评论