Merge pull request #16 from golift/dn2_wan2

Clean up logging.
This commit is contained in:
David Newhall II 2019-06-19 01:50:14 -07:00 committed by GitHub
commit e3e463553e
3 changed files with 30 additions and 34 deletions

View File

@ -13,7 +13,7 @@ func (u *Unifi) parseDevices(data []json.RawMessage, siteName string) *Devices {
} else if t, ok := o["type"].(string); ok { } else if t, ok := o["type"].(string); ok {
assetType = t assetType = t
} }
u.dLogf("Unmarshalling Device Type: %v, site %s ", assetType, siteName) u.DebugLog("Unmarshalling Device Type: %v, site %s ", assetType, siteName)
// Choose which type to unmarshal into based on the "type" json key. // Choose which type to unmarshal into based on the "type" json key.
switch assetType { // Unmarshal again into the correct type.. switch assetType { // Unmarshal again into the correct type..
case "uap": case "uap":
@ -32,7 +32,7 @@ func (u *Unifi) parseDevices(data []json.RawMessage, siteName string) *Devices {
devices.USWs = append(devices.USWs, usw) devices.USWs = append(devices.USWs, usw)
} }
default: default:
u.eLogf("unknown asset type - %v - skipping", assetType) u.ErrorLog("unknown asset type - %v - skipping", assetType)
} }
} }
return devices return devices
@ -41,12 +41,12 @@ func (u *Unifi) parseDevices(data []json.RawMessage, siteName string) *Devices {
// unmarshalDevice handles logging for the unmarshal operations in parseDevices(). // unmarshalDevice handles logging for the unmarshal operations in parseDevices().
func (u *Unifi) unmarshalDevice(dev string, data json.RawMessage, v interface{}) (err error) { func (u *Unifi) unmarshalDevice(dev string, data json.RawMessage, v interface{}) (err error) {
if err = json.Unmarshal(data, v); err != nil { if err = json.Unmarshal(data, v); err != nil {
u.eLogf("json.Unmarshal(%v): %v", dev, err) u.ErrorLog("json.Unmarshal(%v): %v", dev, err)
u.eLogf("Enable Debug Logging to output the failed payload.") u.ErrorLog("Enable Debug Logging to output the failed payload.")
json, err := data.MarshalJSON() json, err := data.MarshalJSON()
u.dLogf("Failed Payload: %s (marshal err: %v)", json, err) u.DebugLog("Failed Payload: %s (marshal err: %v)", json, err)
u.dLogf("The above payload can prove useful during torubleshooting when you open an Issue:") u.DebugLog("The above payload can prove useful during torubleshooting when you open an Issue:")
u.dLogf("==- https://github.com/golift/unifi/issues/new -==") u.DebugLog("==- https://github.com/golift/unifi/issues/new -==")
} }
return err return err
} }

View File

@ -32,18 +32,9 @@ const (
// that matches this interface to capture debug and error logs. // that matches this interface to capture debug and error logs.
type Logger func(msg string, fmt ...interface{}) type Logger func(msg string, fmt ...interface{})
// dLogf logs a debug message. // DiscardLogs is the default debug logger.
func (u *Unifi) dLogf(msg string, v ...interface{}) { func DiscardLogs(msg string, v ...interface{}) {
if u.DebugLog != nil { // do nothing.
u.DebugLog("[DEBUG] "+msg, v...)
}
}
// eLogf logs an error message.
func (u *Unifi) eLogf(msg string, v ...interface{}) {
if u.ErrorLog != nil {
u.ErrorLog("[ERROR] "+msg, v...)
}
} }
// Devices contains a list of all the unifi devices from a controller. // Devices contains a list of all the unifi devices from a controller.
@ -56,7 +47,8 @@ type Devices struct {
// Unifi is what you get in return for providing a password! Unifi represents // Unifi is what you get in return for providing a password! Unifi represents
// a controller that you can make authenticated requests to. Use this to make // a controller that you can make authenticated requests to. Use this to make
// additional requests for devices, clients or other custom data. // additional requests for devices, clients or other custom data. Do not set
// the loggers to nil. Set them to DiscardLogs if you want no logs.
type Unifi struct { type Unifi struct {
*http.Client *http.Client
baseURL string baseURL string

View File

@ -12,6 +12,7 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"strings" "strings"
@ -32,6 +33,8 @@ func NewUnifi(user, pass, url string, verifySSL bool) (*Unifi, error) {
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifySSL}}, Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifySSL}},
Jar: jar, Jar: jar,
}, },
ErrorLog: log.Printf,
DebugLog: DiscardLogs,
} }
return u, u.getController(user, pass) return u, u.getController(user, pass)
} }
@ -39,7 +42,7 @@ func NewUnifi(user, pass, url string, verifySSL bool) (*Unifi, error) {
// getController is a helper method to make testsing a bit easier. // getController is a helper method to make testsing a bit easier.
func (u *Unifi) getController(user, pass string) error { func (u *Unifi) getController(user, pass string) error {
// magic login. // magic login.
req, err := u.UniReq(LoginPath, `{"username": "`+user+`","password": "`+pass+`"}`) req, err := u.UniReq(LoginPath, fmt.Sprintf(`{"username":"%s","password":"%s"}`, user, pass))
if err != nil { if err != nil {
return errors.Wrap(err, "UniReq(LoginPath, json)") return errors.Wrap(err, "UniReq(LoginPath, json)")
} }
@ -52,8 +55,8 @@ func (u *Unifi) getController(user, pass string) error {
_ = resp.Body.Close() _ = resp.Body.Close()
}() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return errors.Errorf("authentication failed (user: %s): %s (status: %d/%s)", return errors.Errorf("authentication failed (user: %s): %s (status: %s)",
user, u.baseURL+LoginPath, resp.StatusCode, resp.Status) user, u.baseURL+LoginPath, resp.Status)
} }
return nil return nil
} }
@ -74,7 +77,7 @@ func (u *Unifi) GetClients(sites []Site) (Clients, error) {
var response struct { var response struct {
Data []Client `json:"data"` Data []Client `json:"data"`
} }
u.dLogf("Polling Controller, retreiving Unifi Clients, site %s (%s) ", site.Name, site.Desc) u.DebugLog("Polling Controller, retreiving Unifi Clients, site %s (%s) ", site.Name, site.Desc)
clientPath := fmt.Sprintf(ClientPath, site.Name) clientPath := fmt.Sprintf(ClientPath, site.Name)
if err := u.GetData(clientPath, &response); err != nil { if err := u.GetData(clientPath, &response); err != nil {
return nil, err return nil, err
@ -135,18 +138,18 @@ func (u *Unifi) GetSites() (Sites, error) {
response.Data[i].SiteName = response.Data[i].Desc + " (" + response.Data[i].Name + ")" response.Data[i].SiteName = response.Data[i].Desc + " (" + response.Data[i].Name + ")"
sites = append(sites, response.Data[i].Name) sites = append(sites, response.Data[i].Name)
} }
u.dLogf("Found %d site(s): %s", len(sites), strings.Join(sites, ",")) u.DebugLog("Found %d site(s): %s", len(sites), strings.Join(sites, ","))
return response.Data, nil return response.Data, nil
} }
// GetData makes a unifi request and unmarshal the response into a provided pointer. // GetData makes a unifi request and unmarshal the response into a provided pointer.
func (u *Unifi) GetData(methodPath string, v interface{}) error { func (u *Unifi) GetData(methodPath string, v interface{}) error {
if body, err := u.GetJSON(methodPath); err != nil { body, err := u.GetJSON(methodPath)
if err != nil {
return err return err
} else if err = json.Unmarshal(body, v); err != nil {
return errors.Wrapf(err, "json.Unmarshal(%s)", methodPath)
} }
return nil err = json.Unmarshal(body, v)
return errors.Wrapf(err, "json.Unmarshal(%s)", methodPath)
} }
// UniReq is a small helper function that adds an Accept header. // UniReq is a small helper function that adds an Accept header.
@ -154,10 +157,11 @@ func (u *Unifi) GetData(methodPath string, v interface{}) error {
// And if you're doing that... sumbut a pull request with your new struct. :) // And if you're doing that... sumbut a pull request with your new struct. :)
// This is a helper method that is exposed for convenience. // This is a helper method that is exposed for convenience.
func (u *Unifi) UniReq(apiPath string, params string) (req *http.Request, err error) { func (u *Unifi) UniReq(apiPath string, params string) (req *http.Request, err error) {
if params != "" { switch path := u.baseURL + apiPath; {
req, err = http.NewRequest("POST", u.baseURL+apiPath, bytes.NewBufferString(params)) case params == "":
} else { req, err = http.NewRequest("GET", path, nil)
req, err = http.NewRequest("GET", u.baseURL+apiPath, nil) default:
req, err = http.NewRequest("POST", path, bytes.NewBufferString(params))
} }
if err == nil { if err == nil {
req.Header.Add("Accept", "application/json") req.Header.Add("Accept", "application/json")
@ -183,7 +187,7 @@ func (u *Unifi) GetJSON(apiPath string) ([]byte, error) {
return body, errors.Wrapf(err, "ioutil.ReadAll(%s)", apiPath) return body, errors.Wrapf(err, "ioutil.ReadAll(%s)", apiPath)
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
err = errors.Errorf("invalid status code from server %v %v", resp.StatusCode, resp.Status) err = errors.Errorf("invalid status code from server %s", resp.Status)
} }
return body, err return body, err
} }