From 8e9c3888945ff876bc1c499e0e2d45e4d188d1ba Mon Sep 17 00:00:00 2001 From: Matej Kramny Date: Sat, 21 Mar 2015 12:36:45 +0100 Subject: [PATCH] System logger --- cachet/config.go | 24 +++++++++++++++++++++++- cachet/incident.go | 24 +++++++++++++----------- cachet/metrics.go | 3 +-- cachet/monitor.go | 7 +++---- main.go | 12 ++++++------ 5 files changed, 46 insertions(+), 24 deletions(-) diff --git a/cachet/config.go b/cachet/config.go index b3ca870..c6e6968 100644 --- a/cachet/config.go +++ b/cachet/config.go @@ -5,7 +5,9 @@ import ( "flag" "fmt" "github.com/castawaylabs/cachet-monitor/system" + "io" "io/ioutil" + "log" "net/http" "net/url" "os" @@ -13,6 +15,8 @@ import ( // Static config var Config CachetConfig +// Central logger +var Logger *log.Logger // CachetConfig is the monitoring tool configuration type CachetConfig struct { @@ -20,13 +24,16 @@ type CachetConfig struct { APIToken string `json:"api_token"` Monitors []*Monitor `json:"monitors"` SystemName string `json:"system_name"` + LogPath string `json:"log_path"` } func init() { var configPath string var systemName string + var logPath string flag.StringVar(&configPath, "c", "/etc/cachet-monitor.config.json", "Config path") flag.StringVar(&systemName, "name", "", "System Name") + flag.StringVar(&logPath, "log", "", "Log path") flag.Parse() var data []byte @@ -42,7 +49,6 @@ func init() { } defer response.Body.Close() - data, _ = ioutil.ReadAll(response.Body) fmt.Println("Downloaded network configuration.") @@ -85,4 +91,20 @@ func init() { fmt.Printf("No monitors defined!\nSee sample configuration: https://github.com/CastawayLabs/cachet-monitor/blob/master/example.config.json\n") os.Exit(1) } + + if len(logPath) > 0 { + Config.LogPath = logPath + } + + var logWriter io.Writer + logWriter = os.Stdout + if len(Config.LogPath) > 0 { + logWriter, err = os.Create(Config.LogPath) + if err != nil { + fmt.Printf("Unable to open file '%v' for logging\n", Config.LogPath) + os.Exit(1) + } + } + + Logger = log.New(logWriter, "", log.Llongfile | log.Ldate | log.Ltime) } diff --git a/cachet/incident.go b/cachet/incident.go index 45410a6..244a6b1 100644 --- a/cachet/incident.go +++ b/cachet/incident.go @@ -2,7 +2,6 @@ package cachet import ( "encoding/json" - "fmt" "strconv" ) @@ -13,7 +12,7 @@ type Incident struct { Message string `json:"message"` Status int `json:"status"` // 4? HumanStatus string `json:"human_status"` - Component *Component `json:"component"` + Component *Component `json:"-"` ComponentID *int `json:"component_id"` CreatedAt int `json:"created_at"` UpdatedAt int `json:"updated_at"` @@ -33,13 +32,14 @@ type IncidentList struct { func GetIncidents() []Incident { _, body, err := makeRequest("GET", "/incidents", nil) if err != nil { - panic(err) + Logger.Printf("Cannot get incidents: %v\n", err) + return []Incident{} } var data IncidentList err = json.Unmarshal(body, &data) if err != nil { - fmt.Println("Cannot parse incidents.") + Logger.Printf("Cannot parse incidents: %v\n", err) } return data.Incidents @@ -49,7 +49,8 @@ func GetIncidents() []Incident { func (incident *Incident) Send() { jsonBytes, err := json.Marshal(incident) if err != nil { - panic(err) + Logger.Printf("Cannot encode incident: %v\n", err) + return } requestType := "POST" @@ -61,24 +62,25 @@ func (incident *Incident) Send() { resp, body, err := makeRequest(requestType, requestURL, jsonBytes) if err != nil { - panic(err) + Logger.Printf("Cannot create/update incident: %v\n", err) + return } - fmt.Println(strconv.Itoa(resp.StatusCode) + " " + string(body)) + Logger.Println(strconv.Itoa(resp.StatusCode) + " " + string(body)) var data IncidentData err = json.Unmarshal(body, &data) if err != nil { - fmt.Println("Cannot parse incident body.") + Logger.Println("Cannot parse incident body.") panic(err) } else { incident.ID = data.Incident.ID } - fmt.Println("ID:" + strconv.Itoa(incident.ID)) + Logger.Println("ID:" + strconv.Itoa(incident.ID)) if resp.StatusCode != 200 { - fmt.Println("Could not create/update incident!") + Logger.Println("Could not create/update incident!") } } @@ -90,7 +92,7 @@ func (incident *Incident) GetSimilarIncidentID() { for _, inc := range incidents { if incident.Name == inc.Name && incident.Message == inc.Message && incident.Status == inc.Status && incident.HumanStatus == inc.HumanStatus { incident.ID = inc.ID - fmt.Printf("Updated incident id to %v\n", inc.ID) + Logger.Printf("Updated incident id to %v\n", inc.ID) break } } diff --git a/cachet/metrics.go b/cachet/metrics.go index 79cf20c..ff21d58 100644 --- a/cachet/metrics.go +++ b/cachet/metrics.go @@ -2,7 +2,6 @@ package cachet import ( "encoding/json" - "fmt" "strconv" ) @@ -18,7 +17,7 @@ func SendMetric(metricID int, delay int64) { resp, _, err := makeRequest("POST", "/metrics/"+strconv.Itoa(metricID)+"/points", jsonBytes) if err != nil || resp.StatusCode != 200 { - fmt.Printf("Could not log data point!\n%v\n", err) + Logger.Printf("Could not log data point!\n%v\n", err) return } } diff --git a/cachet/monitor.go b/cachet/monitor.go index 6997de2..5b4b998 100644 --- a/cachet/monitor.go +++ b/cachet/monitor.go @@ -1,7 +1,6 @@ package cachet import ( - "fmt" "net/http" "time" ) @@ -66,7 +65,7 @@ func (monitor *Monitor) AnalyseData() { } t := (float32(numDown) / float32(len(monitor.History))) * 100 - fmt.Printf("%s %.2f%% Down at %v. Threshold: %.2f%%\n", monitor.URL, t, time.Now().UnixNano()/int64(time.Second), monitor.Threshold) + Logger.Printf("%s %.2f%% Down at %v. Threshold: %.2f%%\n", monitor.URL, t, time.Now().UnixNano()/int64(time.Second), monitor.Threshold) if len(monitor.History) != 10 { // not enough data @@ -75,7 +74,7 @@ func (monitor *Monitor) AnalyseData() { if t > monitor.Threshold && monitor.Incident == nil { // is down, create an incident - fmt.Println("Creating incident...") + Logger.Println("Creating incident...") monitor.Incident = &Incident{ Name: monitor.Name + " - " + Config.SystemName, @@ -96,7 +95,7 @@ func (monitor *Monitor) AnalyseData() { monitor.Incident.Send() } else if t < monitor.Threshold && monitor.Incident != nil { // was down, created an incident, its now ok, make it resolved. - fmt.Println("Updating incident to resolved...") + Logger.Println("Updating incident to resolved...") monitor.Incident.SetFixed() monitor.Incident.Send() diff --git a/main.go b/main.go index 2cce06f..e5fde68 100644 --- a/main.go +++ b/main.go @@ -1,24 +1,24 @@ package main import ( - "fmt" "github.com/castawaylabs/cachet-monitor/cachet" "time" ) func main() { config := cachet.Config + log := cachet.Logger - fmt.Printf("System: %s, API: %s\n", config.SystemName, config.APIUrl) - fmt.Printf("Starting %d monitors:\n", len(config.Monitors)) + log.Printf("System: %s, API: %s\n", config.SystemName, config.APIUrl) + log.Printf("Starting %d monitors:\n", len(config.Monitors)) for _, mon := range config.Monitors { - fmt.Printf(" %s: GET %s & Expect HTTP %d\n", mon.Name, mon.URL, mon.ExpectedStatusCode) + log.Printf(" %s: GET %s & Expect HTTP %d\n", mon.Name, mon.URL, mon.ExpectedStatusCode) if mon.MetricID > 0 { - fmt.Printf(" - Logs lag to metric id: %d\n", mon.MetricID) + log.Printf(" - Logs lag to metric id: %d\n", mon.MetricID) } } - fmt.Println() + log.Println() ticker := time.NewTicker(time.Second) for range ticker.C {