snippet/exceptionless/exceptionless.go

100 lines
1.7 KiB
Go
Raw Normal View History

package exceptionless
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
type Config struct {
URL string
Token string
}
var conf *Config
func Init(config *Config) error {
if config == nil {
return errors.New("nil of Config")
}
conf = config
conf.Token = "Bearer " + conf.Token
return nil
}
func post(uri string, body interface{}) (*[]byte, error) {
url := fmt.Sprintf(`%s/%s`, conf.URL, uri)
reqbody, _ := json.Marshal(body)
req, err := http.NewRequest("POST", url, strings.NewReader(string(reqbody)))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", conf.Token)
req.Header.Add("Content-Type", "application/json")
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 202 {
return nil, nil
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return &respBody, nil
}
func WriteMessages(msg string) {
message := &struct {
Message string
}{
Message: msg,
}
post("api/v2/events", message)
}
func WriteLogs(msg string) {
message := &struct {
Message string
Type string
Date string
}{
Type: "log",
Message: msg,
Date: time.Now().Format("2006-01-02 15:04:05"),
}
post("api/v2/events", message)
}
func WriteErrors(msg string) {
message := &struct {
SimpleError interface{}
Type string
Date string
}{
Type: "error",
SimpleError: &struct {
Message string
}{
Message: msg,
},
Date: time.Now().Format("2006-01-02 15:04:05"),
}
post("api/v2/events", message)
}