diff --git a/common/common.go b/common/common.go index 67594b74..84d7d249 100644 --- a/common/common.go +++ b/common/common.go @@ -16,7 +16,6 @@ import ( "hash" "io" "io/ioutil" - "log" "math" "net/http" "net/url" @@ -29,6 +28,8 @@ import ( "strconv" "strings" "time" + + log "github.com/thrasher-/gocryptotrader/logger" ) // Vars for common.go operations @@ -390,7 +391,7 @@ func SendHTTPRequest(method, path string, headers map[string]string, body io.Rea // on failure. func SendHTTPGetRequest(url string, jsonDecode, isVerbose bool, result interface{}) error { if isVerbose { - log.Println("Raw URL: ", url) + log.Debugf("Raw URL: %s", url) } initialiseHTTPClient() @@ -410,7 +411,7 @@ func SendHTTPGetRequest(url string, jsonDecode, isVerbose bool, result interface } if isVerbose { - log.Println("Raw Resp: ", string(contents[:])) + log.Debugf("Raw Resp: %s", string(contents[:])) } defer res.Body.Close() @@ -639,8 +640,8 @@ func CheckDir(dir string, create bool) error { return fmt.Errorf("directory %s does not exist. Err: %s", dir, err) } - log.Printf("Directory %s does not exist.. creating.", dir) - err = os.Mkdir(dir, 0777) + log.Warnf("Directory %s does not exist.. creating.", dir) + err = os.MkdirAll(dir, 0777) if err != nil { return fmt.Errorf("failed to create dir. Err: %s", err) } diff --git a/communications/base/base_interface.go b/communications/base/base_interface.go index 3a157419..9762074f 100644 --- a/communications/base/base_interface.go +++ b/communications/base/base_interface.go @@ -1,12 +1,12 @@ package base import ( - "log" "time" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // IComm is the main interface array across the communication packages @@ -33,7 +33,7 @@ func (c IComm) Setup() { if c[i].IsEnabled() && !c[i].IsConnected() { err := c[i].Connect() if err != nil { - log.Printf("Communications: %s failed to connect. Err: %s", c[i].GetName(), err) + log.Errorf("Communications: %s failed to connect. Err: %s", c[i].GetName(), err) } } } @@ -45,7 +45,7 @@ func (c IComm) PushEvent(event Event) { if c[i].IsEnabled() && c[i].IsConnected() { err := c[i].PushEvent(event) if err != nil { - log.Printf("Communications error - PushEvent() in package %s with %v", + log.Errorf("Communications error - PushEvent() in package %s with %v", c[i].GetName(), event) } } @@ -58,12 +58,12 @@ func (c IComm) GetEnabledCommunicationMediums() { var count int for i := range c { if c[i].IsEnabled() && c[i].IsConnected() { - log.Printf("Communications: Medium %s is enabled.", c[i].GetName()) + log.Debugf("Communications: Medium %s is enabled.", c[i].GetName()) count++ } } if count == 0 { - log.Println("Communications: No communication mediums are enabled.") + log.Warnf("Communications: No communication mediums are enabled.") } } diff --git a/communications/slack/slack.go b/communications/slack/slack.go index c96f3451..47c9a130 100644 --- a/communications/slack/slack.go +++ b/communications/slack/slack.go @@ -7,7 +7,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/http" "sync" "time" @@ -16,6 +15,7 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/communications/base" "github.com/thrasher-/gocryptotrader/config" + log "github.com/thrasher-/gocryptotrader/logger" ) // const declares main slack url and commands that will be supported on client @@ -154,13 +154,13 @@ func (s *Slack) NewConnection() error { } if s.Verbose { - log.Printf("%s [%s] connected to %s [%s] \nWebsocket URL: %s.\n", + log.Debugf("%s [%s] connected to %s [%s] \nWebsocket URL: %s.\n", s.Details.Self.Name, s.Details.Self.ID, s.Details.Team.Domain, s.Details.Team.ID, s.Details.URL) - log.Printf("Slack channels: %s", s.GetChannelsString()) + log.Debugf("Slack channels: %s", s.GetChannelsString()) } s.TargetChannelID, err = s.GetIDByName(s.TargetChannel) @@ -197,14 +197,14 @@ func (s *Slack) WebsocketReader() { for { _, resp, err := s.WebsocketConn.ReadMessage() if err != nil { - log.Fatal(err) + log.Error(err) } var data WebsocketResponse err = common.JSONDecode(resp, &data) if err != nil { - log.Println(err) + log.Error(err) continue } @@ -239,10 +239,10 @@ func (s *Slack) WebsocketReader() { case "pong": if s.Verbose { - log.Println("Pong received from server") + log.Debugf("Pong received from server") } default: - log.Println(string(resp)) + log.Debugf(string(resp)) } } } @@ -254,7 +254,7 @@ func (s *Slack) handlePresenceChange(resp []byte) error { return err } if s.Verbose { - log.Printf("Presence change. User %s [%s] changed status to %s\n", + log.Debugf("Presence change. User %s [%s] changed status to %s\n", s.GetUsernameByID(pres.User), pres.User, pres.Presence) } @@ -271,7 +271,7 @@ func (s *Slack) handleMessageResponse(resp []byte, data WebsocketResponse) error return err } if s.Verbose { - log.Printf("Msg received by %s [%s] with text: %s\n", + log.Debugf("Msg received by %s [%s] with text: %s\n", s.GetUsernameByID(msg.User), msg.User, msg.Text) } @@ -283,7 +283,7 @@ func (s *Slack) handleMessageResponse(resp []byte, data WebsocketResponse) error func (s *Slack) handleErrorResponse(data WebsocketResponse) error { if data.Error.Msg == "Socket URL has expired" { if s.Verbose { - log.Println("Slack websocket URL has expired.. Reconnecting") + log.Debugf("Slack websocket URL has expired.. Reconnecting") } if s.WebsocketConn == nil { @@ -291,7 +291,7 @@ func (s *Slack) handleErrorResponse(data WebsocketResponse) error { } if err := s.WebsocketConn.Close(); err != nil { - log.Println(err) + log.Error(err) } s.ReconnectURL = "" @@ -303,7 +303,7 @@ func (s *Slack) handleErrorResponse(data WebsocketResponse) error { func (s *Slack) handleHelloResponse(data WebsocketResponse) { if s.Verbose { - log.Println("Websocket connected successfully.") + log.Debugln("Websocket connected successfully.") } s.Connected = true go s.WebsocketKeepAlive() @@ -320,7 +320,7 @@ func (s *Slack) handleReconnectResponse(resp []byte) error { } s.ReconnectURL = recURL.URL if s.Verbose { - log.Printf("Reconnect URL set to %s\n", s.ReconnectURL) + log.Debugf("Reconnect URL set to %s\n", s.ReconnectURL) } return nil } @@ -332,7 +332,7 @@ func (s *Slack) WebsocketKeepAlive() { for { <-ticker.C if err := s.WebsocketSend("ping", ""); err != nil { - log.Println("slack WebsocketKeepAlive() error", err) + log.Debugf("slack WebsocketKeepAlive() error %s", err) } } } diff --git a/communications/telegram/telegram.go b/communications/telegram/telegram.go index b514edc9..c36e0cd1 100644 --- a/communications/telegram/telegram.go +++ b/communications/telegram/telegram.go @@ -7,11 +7,11 @@ import ( "bytes" "errors" "fmt" - "log" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/communications/base" "github.com/thrasher-/gocryptotrader/config" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -87,7 +87,7 @@ func (t *Telegram) PollerStart() { for { resp, err := t.GetUpdates() if err != nil { - log.Fatal(err) + log.Error(err) } for i := range resp.Result { @@ -95,7 +95,7 @@ func (t *Telegram) PollerStart() { if string(resp.Result[i].Message.Text[0]) == "/" { err = t.HandleMessages(resp.Result[i].Message.Text, resp.Result[i].Message.From.ID) if err != nil { - log.Fatal(err) + log.Error(err) } } t.Offset = resp.Result[i].UpdateID diff --git a/config/config.go b/config/config.go index 37b167bd..55a4592d 100644 --- a/config/config.go +++ b/config/config.go @@ -5,7 +5,6 @@ import ( "errors" "flag" "fmt" - "log" "os" "path" "runtime" @@ -18,6 +17,7 @@ import ( "github.com/thrasher-/gocryptotrader/currency/forexprovider" "github.com/thrasher-/gocryptotrader/currency/forexprovider/base" "github.com/thrasher-/gocryptotrader/currency/pair" + log "github.com/thrasher-/gocryptotrader/logger" "github.com/thrasher-/gocryptotrader/portfolio" ) @@ -99,6 +99,7 @@ type Config struct { Name string `json:"name"` EncryptConfig int `json:"encryptConfig"` GlobalHTTPTimeout time.Duration `json:"globalHTTPTimeout"` + Logging log.Logging `json:"logging"` Currency CurrencyConfig `json:"currencyConfig"` Communications CommunicationsConfig `json:"communications"` Portfolio portfolio.Base `json:"portfolioAddresses"` @@ -521,7 +522,7 @@ func (c *Config) CheckPairConsistency(exchName string) error { if len(pairs) == 0 { exchCfg.EnabledPairs = pair.RandomPairFromPairs(availPairs).Pair().String() - log.Printf("Exchange %s: No enabled pairs found in available pairs, randomly added %v\n", exchName, exchCfg.EnabledPairs) + log.Debugf("Exchange %s: No enabled pairs found in available pairs, randomly added %v\n", exchName, exchCfg.EnabledPairs) } else { exchCfg.EnabledPairs = common.JoinStrings(pair.PairsToStringArray(pairs), ",") } @@ -531,7 +532,7 @@ func (c *Config) CheckPairConsistency(exchName string) error { return err } - log.Printf("Exchange %s: Removing enabled pair(s) %v from enabled pairs as it isn't an available pair", exchName, pair.PairsToStringArray(pairsRemoved)) + log.Debugf("Exchange %s: Removing enabled pair(s) %v from enabled pairs as it isn't an available pair", exchName, pair.PairsToStringArray(pairsRemoved)) return nil } @@ -730,11 +731,11 @@ func (c *Config) CheckExchangeConfigValues() error { if exch.AuthenticatedAPISupport { // non-fatal error if exch.APIKey == "" || exch.APISecret == "" || exch.APIKey == "Key" || exch.APISecret == "Secret" { c.Exchanges[i].AuthenticatedAPISupport = false - log.Printf(WarningExchangeAuthAPIDefaultOrEmptyValues, exch.Name) + log.Warn(WarningExchangeAuthAPIDefaultOrEmptyValues, exch.Name) } else if exch.Name == "ITBIT" || exch.Name == "Bitstamp" || exch.Name == "COINUT" || exch.Name == "CoinbasePro" { if exch.ClientID == "" || exch.ClientID == "ClientID" { c.Exchanges[i].AuthenticatedAPISupport = false - log.Printf(WarningExchangeAuthAPIDefaultOrEmptyValues, exch.Name) + log.Warn(WarningExchangeAuthAPIDefaultOrEmptyValues, exch.Name) } } } @@ -742,18 +743,18 @@ func (c *Config) CheckExchangeConfigValues() error { lastUpdated := common.UnixTimestampToTime(exch.PairsLastUpdated) lastUpdated = lastUpdated.AddDate(0, 0, configPairsLastUpdatedWarningThreshold) if lastUpdated.Unix() <= time.Now().Unix() { - log.Printf(WarningPairsLastUpdatedThresholdExceeded, exch.Name, configPairsLastUpdatedWarningThreshold) + log.Warn(WarningPairsLastUpdatedThresholdExceeded, exch.Name, configPairsLastUpdatedWarningThreshold) } } if exch.HTTPTimeout <= 0 { - log.Printf("Exchange %s HTTP Timeout value not set, defaulting to %v.", exch.Name, configDefaultHTTPTimeout) + log.Warnf("Exchange %s HTTP Timeout value not set, defaulting to %v.", exch.Name, configDefaultHTTPTimeout) c.Exchanges[i].HTTPTimeout = configDefaultHTTPTimeout } err := c.CheckPairConsistency(exch.Name) if err != nil { - log.Printf("Exchange %s: CheckPairConsistency error: %s", exch.Name, err) + log.Errorf("Exchange %s: CheckPairConsistency error: %s", exch.Name, err) } if len(exch.BankAccounts) == 0 { @@ -853,13 +854,13 @@ func (c *Config) CheckCurrencyConfigValues() error { for i := range c.Currency.ForexProviders { if c.Currency.ForexProviders[i].Enabled == true { if c.Currency.ForexProviders[i].APIKey == "Key" { - log.Printf("WARNING -- %s forex provider API key not set. Please set this in your config.json file", c.Currency.ForexProviders[i].Name) + log.Warnf("%s forex provider API key not set. Please set this in your config.json file", c.Currency.ForexProviders[i].Name) c.Currency.ForexProviders[i].Enabled = false c.Currency.ForexProviders[i].PrimaryProvider = false continue } if c.Currency.ForexProviders[i].APIKeyLvl == -1 && c.Currency.ForexProviders[i].Name != "CurrencyConverter" { - log.Printf("WARNING -- %s APIKey Level not set, functions limited. Please set this in your config.json file", + log.Warnf("%s APIKey Level not set, functions limited. Please set this in your config.json file", c.Currency.ForexProviders[i].Name) } count++ @@ -872,7 +873,7 @@ func (c *Config) CheckCurrencyConfigValues() error { c.Currency.ForexProviders[x].Enabled = true c.Currency.ForexProviders[x].APIKey = "" c.Currency.ForexProviders[x].PrimaryProvider = true - log.Printf("WARNING -- No forex providers set, defaulting to free provider CurrencyConverterAPI.") + log.Warn("No forex providers set, defaulting to free provider CurrencyConverterAPI.") } } } @@ -959,6 +960,44 @@ func (c *Config) RetrieveConfigCurrencyPairs(enabledOnly bool) error { return nil } +// CheckLoggerConfig checks to see logger values are present and valid in config +// if not creates a default instance of the logger +func (c *Config) CheckLoggerConfig() (err error) { + m.Lock() + defer m.Unlock() + + // check if enabled is nil or level is a blank string + if c.Logging.Enabled == nil || c.Logging.Level == "" { + // Creates a new pointer to bool and sets it as true + t := func(t bool) *bool { return &t }(true) + + log.Warn("Missing or invalid config settings using safe defaults") + + // Set logger to safe defaults + + c.Logging = log.Logging{ + Enabled: t, + Level: "DEBUG|INFO|WARN|ERROR|FATAL", + ColourOutput: false, + File: "debug.txt", + Rotate: false, + } + log.Logger = &c.Logging + } else { + log.Logger = &c.Logging + } + + if len(c.Logging.File) > 0 { + logPath := path.Join(common.GetDefaultDataDir(runtime.GOOS), "logs") + err = common.CheckDir(logPath, true) + if err != nil { + return + } + log.LogPath = logPath + } + return +} + // GetFilePath returns the desired config file or the default config file name // based on if the application is being run under test or normal mode. func GetFilePath(file string) (string, error) { @@ -996,13 +1035,13 @@ func GetFilePath(file string) (string, error) { if err != nil { return "", err } - log.Printf("Renamed old config file %s to %s", oldDirs[x], newDirs[0]) + log.Debugf("Renamed old config file %s to %s", oldDirs[x], newDirs[0]) } else { err = os.Rename(oldDirs[x], newDirs[1]) if err != nil { return "", err } - log.Printf("Renamed old config file %s to %s", oldDirs[x], newDirs[1]) + log.Debugf("Renamed old config file %s to %s", oldDirs[x], newDirs[1]) } } } @@ -1086,7 +1125,7 @@ func (c *Config) ReadConfig(configPath string) error { } key, err := PromptForConfigKey(IsInitialSetup) if err != nil { - log.Printf("PromptForConfigKey err: %s", err) + log.Errorf("PromptForConfigKey err: %s", err) errCounter++ continue } @@ -1095,7 +1134,7 @@ func (c *Config) ReadConfig(configPath string) error { f = append(f, file...) data, err := DecryptConfigFile(f, key) if err != nil { - log.Printf("DecryptConfigFile err: %s", err) + log.Errorf("DecryptConfigFile err: %s", err) errCounter++ continue } @@ -1103,7 +1142,7 @@ func (c *Config) ReadConfig(configPath string) error { err = ConfirmConfigJSON(data, &c) if err != nil { if errCounter < configMaxAuthFailres { - log.Printf("Invalid password.") + log.Errorf("Invalid password.") } errCounter++ continue @@ -1164,7 +1203,7 @@ func (c *Config) CheckConfig() error { if c.Webserver.Enabled { err = c.CheckWebserverConfigValues() if err != nil { - log.Print(fmt.Errorf(ErrCheckingConfigValues, err)) + log.Errorf(ErrCheckingConfigValues, err) c.Webserver.Enabled = false } } @@ -1175,7 +1214,7 @@ func (c *Config) CheckConfig() error { } if c.GlobalHTTPTimeout <= 0 { - log.Printf("Global HTTP Timeout value not set, defaulting to %v.", configDefaultHTTPTimeout) + log.Warnf("Global HTTP Timeout value not set, defaulting to %v.", configDefaultHTTPTimeout) c.GlobalHTTPTimeout = configDefaultHTTPTimeout } diff --git a/config/config_encryption.go b/config/config_encryption.go index 5d43074c..9298abbe 100644 --- a/config/config_encryption.go +++ b/config/config_encryption.go @@ -8,9 +8,9 @@ import ( "errors" "fmt" "io" - "log" "github.com/thrasher-/gocryptotrader/common" + log "github.com/thrasher-/gocryptotrader/logger" "golang.org/x/crypto/scrypt" ) diff --git a/config/config_test.go b/config/config_test.go index d325d450..c3863364 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -5,6 +5,7 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" + log "github.com/thrasher-/gocryptotrader/logger" ) func TestGetCurrencyConfig(t *testing.T) { @@ -905,3 +906,21 @@ func TestUpdateConfig(t *testing.T) { t.Fatalf("Test failed. Cryptocurrencies should have been repopulated") } } + +func TestCheckLoggerConfig(t *testing.T) { + c := GetConfig() + err := c.LoadConfig(ConfigTestFile) + if err != nil { + t.Fatal(err) + } + c.Logging = log.Logging{} + err = c.CheckLoggerConfig() + if err != nil { + t.Errorf("Failed to create default logger reason: %v", err) + } + c.LoadConfig(ConfigTestFile) + err = c.CheckLoggerConfig() + if err != nil { + t.Errorf("Failed to create logger with user settings: reason: %v", err) + } +} diff --git a/config_example.json b/config_example.json index c058dff2..a380372a 100644 --- a/config_example.json +++ b/config_example.json @@ -2,6 +2,13 @@ "name": "Skynet", "encryptConfig": 0, "globalHTTPTimeout": 15000000000, + "logging": { + "enabled": true, + "file": "debug.txt", + "colour": false, + "level": "DEBUG|WARN|INFO|ERROR|FATAL", + "rotate": false + }, "currencyConfig": { "forexProviders": [ { diff --git a/currency/currency.go b/currency/currency.go index 98605ded..a60d3c27 100644 --- a/currency/currency.go +++ b/currency/currency.go @@ -2,11 +2,11 @@ package currency import ( "fmt" - "log" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/forexprovider" "github.com/thrasher-/gocryptotrader/currency/pair" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -38,7 +38,7 @@ func SetDefaults() { FXProviders = forexprovider.NewDefaultFXProvider() err := SeedCurrencyData(DefaultCurrencies) if err != nil { - log.Printf("Failed to seed currency data. Err: %s", err) + log.Errorf("Failed to seed currency data. Err: %s", err) return } } diff --git a/currency/forexprovider/base/base_interface.go b/currency/forexprovider/base/base_interface.go index 44fe2193..4eb7da51 100644 --- a/currency/forexprovider/base/base_interface.go +++ b/currency/forexprovider/base/base_interface.go @@ -2,7 +2,8 @@ package base import ( "errors" - "log" + + log "github.com/thrasher-/gocryptotrader/logger" ) // IFXProviders contains an array of foreign exchange interfaces @@ -24,12 +25,12 @@ func (fxp IFXProviders) GetCurrencyData(baseCurrency, symbols string) (map[strin if fxp[x].IsPrimaryProvider() && fxp[x].IsEnabled() { rates, err := fxp[x].GetRates(baseCurrency, symbols) if err != nil { - log.Println(err) + log.Error(err) for y := range fxp { if !fxp[y].IsPrimaryProvider() && fxp[x].IsEnabled() { rates, err = fxp[y].GetRates(baseCurrency, symbols) if err != nil { - log.Println(err) + log.Error(err) continue } return rates, nil diff --git a/currency/forexprovider/currencyconverterapi/currencyconverterapi.go b/currency/forexprovider/currencyconverterapi/currencyconverterapi.go index d82eb6b6..309a6e04 100644 --- a/currency/forexprovider/currencyconverterapi/currencyconverterapi.go +++ b/currency/forexprovider/currencyconverterapi/currencyconverterapi.go @@ -3,11 +3,11 @@ package currencyconverter import ( "errors" "fmt" - "log" "net/url" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/forexprovider/base" + log "github.com/thrasher-/gocryptotrader/logger" ) // const declarations consist of endpoints @@ -61,7 +61,7 @@ func (c *CurrencyConverter) GetRates(baseCurrency, symbols string) (map[string]f batch := completedStrings[i : i+2] result, err := c.ConvertMany(batch) if err != nil { - log.Printf("Failed to get batch err: %s", err) + log.Errorf("Failed to get batch err: %s", err) continue } for k, v := range result { diff --git a/currency/forexprovider/forexprovider.go b/currency/forexprovider/forexprovider.go index 425444ef..8c94d71c 100644 --- a/currency/forexprovider/forexprovider.go +++ b/currency/forexprovider/forexprovider.go @@ -3,13 +3,12 @@ package forexprovider import ( - "log" - "github.com/thrasher-/gocryptotrader/currency/forexprovider/base" currencyconverter "github.com/thrasher-/gocryptotrader/currency/forexprovider/currencyconverterapi" "github.com/thrasher-/gocryptotrader/currency/forexprovider/currencylayer" fixer "github.com/thrasher-/gocryptotrader/currency/forexprovider/fixer.io" "github.com/thrasher-/gocryptotrader/currency/forexprovider/openexchangerates" + log "github.com/thrasher-/gocryptotrader/logger" ) // ForexProviders is an array of foreign exchange interfaces @@ -61,7 +60,7 @@ func StartFXService(fxProviders []base.Settings) *ForexProviders { } } if len(fxp.IFXProviders) == 0 { - log.Fatal("No foreign exchange providers enabled") + log.Error("No foreign exchange providers enabled") } return fxp } diff --git a/events/events.go b/events/events.go index 41251f71..9d3cc2ba 100644 --- a/events/events.go +++ b/events/events.go @@ -3,7 +3,6 @@ package events import ( "errors" "fmt" - "log" "strconv" "github.com/thrasher-/gocryptotrader/common" @@ -12,6 +11,7 @@ import ( "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/pair" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -121,7 +121,7 @@ func (e *Event) ExecuteAction() bool { } } } else { - log.Printf("Event triggered: %s", e.String()) + log.Debugf("Event triggered: %s", e.String()) } return true } @@ -239,7 +239,7 @@ func CheckEvents() { if !event.Executed { success := event.CheckCondition() if success { - log.Printf( + log.Debugf( "Event %d triggered on %s successfully.\n", event.ID, event.Exchange, ) diff --git a/exchange.go b/exchange.go index 407a9dc9..1b3fa467 100644 --- a/exchange.go +++ b/exchange.go @@ -2,7 +2,6 @@ package main import ( "errors" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -36,6 +35,7 @@ import ( "github.com/thrasher-/gocryptotrader/exchanges/wex" "github.com/thrasher-/gocryptotrader/exchanges/yobit" "github.com/thrasher-/gocryptotrader/exchanges/zb" + log "github.com/thrasher-/gocryptotrader/logger" ) // vars related to exchange functions @@ -86,7 +86,7 @@ func ReloadExchange(name string) error { e := GetExchangeByName(nameLower) e.Setup(exchCfg) - log.Printf("%s exchange reloaded successfully.\n", name) + log.Debugf("%s exchange reloaded successfully.\n", name) return nil } @@ -231,13 +231,13 @@ func SetupExchanges() { if CheckExchangeExists(exch.Name) { e := GetExchangeByName(exch.Name) if e == nil { - log.Println(ErrExchangeNotFound) + log.Errorf("%s", ErrExchangeNotFound) continue } err := ReloadExchange(exch.Name) if err != nil { - log.Printf("ReloadExchange %s failed: %s", exch.Name, err) + log.Errorf("ReloadExchange %s failed: %s", exch.Name, err) continue } @@ -249,16 +249,16 @@ func SetupExchanges() { } if !exch.Enabled { - log.Printf("%s: Exchange support: Disabled", exch.Name) + log.Debugf("%s: Exchange support: Disabled", exch.Name) continue } else { err := LoadExchange(exch.Name, true, &wg) if err != nil { - log.Printf("LoadExchange %s failed: %s", exch.Name, err) + log.Errorf("LoadExchange %s failed: %s", exch.Name, err) continue } } - log.Printf( + log.Debugf( "%s: Exchange support: Enabled (Authenticated API support: %s - Verbose mode: %s).\n", exch.Name, common.IsEnabled(exch.AuthenticatedAPISupport), diff --git a/exchanges/alphapoint/alphapoint.go b/exchanges/alphapoint/alphapoint.go index 5b21d04a..98b220c8 100644 --- a/exchanges/alphapoint/alphapoint.go +++ b/exchanges/alphapoint/alphapoint.go @@ -4,13 +4,12 @@ import ( "bytes" "errors" "fmt" - "log" "strconv" "time" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" ) @@ -191,7 +190,7 @@ func (a *Alphapoint) CreateAccount(firstName, lastName, email, phone, password s err := a.SendAuthenticatedHTTPRequest("POST", alphapointCreateAccount, request, &response) if err != nil { - log.Println(err) + return fmt.Errorf("Alphapoint Error - CreateAccount HTTPRequest - reason: %s", err) } if !response.IsAccepted { return errors.New(response.RejectReason) diff --git a/exchanges/alphapoint/alphapoint_websocket.go b/exchanges/alphapoint/alphapoint_websocket.go index 6d42ffef..261014c4 100644 --- a/exchanges/alphapoint/alphapoint_websocket.go +++ b/exchanges/alphapoint/alphapoint_websocket.go @@ -1,11 +1,11 @@ package alphapoint import ( - "log" "net/http" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -20,25 +20,25 @@ func (a *Alphapoint) WebsocketClient() { a.WebsocketConn, _, err = Dialer.Dial(a.WebsocketURL, http.Header{}) if err != nil { - log.Printf("%s Unable to connect to Websocket. Error: %s\n", a.Name, err) + log.Errorf("%s Unable to connect to Websocket. Error: %s\n", a.Name, err) continue } if a.Verbose { - log.Printf("%s Connected to Websocket.\n", a.Name) + log.Debugf("%s Connected to Websocket.\n", a.Name) } err = a.WebsocketConn.WriteMessage(websocket.TextMessage, []byte(`{"messageType": "logon"}`)) if err != nil { - log.Println(err) + log.Error(err) return } for a.Enabled { msgType, resp, err := a.WebsocketConn.ReadMessage() if err != nil { - log.Println(err) + log.Error(err) break } @@ -51,7 +51,7 @@ func (a *Alphapoint) WebsocketClient() { msgType := MsgType{} err := common.JSONDecode(resp, &msgType) if err != nil { - log.Println(err) + log.Error(err) continue } @@ -60,13 +60,13 @@ func (a *Alphapoint) WebsocketClient() { ticker := WebsocketTicker{} err = common.JSONDecode(resp, &ticker) if err != nil { - log.Println(err) + log.Error(err) continue } } } } a.WebsocketConn.Close() - log.Printf("%s Websocket client disconnected.", a.Name) + log.Debugf("%s Websocket client disconnected.", a.Name) } } diff --git a/exchanges/anx/anx.go b/exchanges/anx/anx.go index 8f8c60ff..68d1f88d 100644 --- a/exchanges/anx/anx.go +++ b/exchanges/anx/anx.go @@ -4,17 +4,16 @@ import ( "bytes" "errors" "fmt" - "log" "strconv" "time" - "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + "github.com/thrasher-/gocryptotrader/currency/symbol" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -274,7 +273,7 @@ func (a *ANX) GetOrderList(isActiveOrdersOnly bool) ([]OrderResponse, error) { } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return nil, errors.New(response.ResultCode) } @@ -300,7 +299,7 @@ func (a *ANX) OrderInfo(orderID string) (OrderResponse, error) { } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return OrderResponse{}, errors.New(response.ResultCode) } return response.Order, nil @@ -331,7 +330,7 @@ func (a *ANX) Send(currency, address, otp, amount string) (string, error) { } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return "", errors.New(response.ResultCode) } return response.TransactionID, nil @@ -357,7 +356,7 @@ func (a *ANX) CreateNewSubAccount(currency, name string) (string, error) { } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return "", errors.New(response.ResultCode) } return response.SubAccount, nil @@ -392,7 +391,7 @@ func (a *ANX) GetDepositAddressByCurrency(currency, name string, new bool) (stri } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return "", errors.New(response.ResultCode) } @@ -432,7 +431,7 @@ func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interf } if a.Verbose { - log.Printf("Request JSON: %s\n", PayloadJSON) + log.Debugf("Request JSON: %s\n", PayloadJSON) } hmac := common.GetHMAC(common.HashSHA512, []byte(path+string("\x00")+string(PayloadJSON)), []byte(a.APISecret)) @@ -497,7 +496,7 @@ func (a *ANX) GetAccountInformation() (AccountInformation, error) { } if response.ResultCode != "OK" { - log.Printf("Response code is not OK: %s\n", response.ResultCode) + log.Errorf("Response code is not OK: %s\n", response.ResultCode) return response, errors.New(response.ResultCode) } return response, nil @@ -520,7 +519,7 @@ func (a *ANX) CheckAPIWithdrawPermission() (bool, error) { } if !apiAllowsWithdraw { - log.Printf("API key is missing withdrawal permissions") + log.Warn("API key is missing withdrawal permissions") } return apiAllowsWithdraw, nil diff --git a/exchanges/anx/anx_wrapper.go b/exchanges/anx/anx_wrapper.go index 1484e705..8dce5a2a 100644 --- a/exchanges/anx/anx_wrapper.go +++ b/exchanges/anx/anx_wrapper.go @@ -2,15 +2,15 @@ package anx import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the ANX go routine @@ -25,13 +25,13 @@ func (a *ANX) Start(wg *sync.WaitGroup) { // Run implements the ANX wrapper func (a *ANX) Run() { if a.Verbose { - log.Printf("%s polling delay: %ds.\n", a.GetName(), a.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", a.GetName(), len(a.EnabledPairs), a.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", a.GetName(), a.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", a.GetName(), len(a.EnabledPairs), a.EnabledPairs) } exchangeProducts, err := a.GetTradablePairs() if err != nil { - log.Printf("%s Failed to get available symbols.\n", a.GetName()) + log.Debugf("%s Failed to get available symbols.\n", a.GetName()) } else { forceUpgrade := false if !common.StringDataContains(a.EnabledPairs, "_") || !common.StringDataContains(a.AvailablePairs, "_") { @@ -40,16 +40,16 @@ func (a *ANX) Run() { if forceUpgrade { enabledPairs := []string{"BTC_USD,BTC_HKD,BTC_EUR,BTC_CAD,BTC_AUD,BTC_SGD,BTC_JPY,BTC_GBP,BTC_NZD,LTC_BTC,DOG_EBTC,STR_BTC,XRP_BTC"} - log.Println("WARNING: Enabled pairs for ANX reset due to config upgrade, please enable the ones you would like again.") + log.Warn("Enabled pairs for ANX reset due to config upgrade, please enable the ones you would like again.") err = a.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to get config.\n", a.GetName()) + log.Errorf("%s Failed to get config.\n", a.GetName()) } } err = a.UpdateCurrencies(exchangeProducts, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to get config.\n", a.GetName()) + log.Errorf("%s Failed to get config.\n", a.GetName()) } } } diff --git a/exchanges/binance/binance.go b/exchanges/binance/binance.go index e9408af5..f7295084 100644 --- a/exchanges/binance/binance.go +++ b/exchanges/binance/binance.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -15,6 +14,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Binance is the overarching type across the Bithumb package @@ -609,7 +609,7 @@ func (b *Binance) SendAuthHTTPRequest(method, path string, params url.Values, re headers["X-MBX-APIKEY"] = b.APIKey if b.Verbose { - log.Printf("sent path: \n%s\n", path) + log.Debugf("sent path: \n%s\n", path) } path = common.EncodeURLValues(path, params) @@ -741,7 +741,6 @@ func (b *Binance) WithdrawCrypto(asset, address, addressTag, name, amount string return resp.ID, nil } - //GetDepositAddressForCurrency retrieves the wallet address for a given currency func (b *Binance) GetDepositAddressForCurrency(currency string) error { path := fmt.Sprintf("%s%s", b.APIUrl, depositAddress) diff --git a/exchanges/binance/binance_wrapper.go b/exchanges/binance/binance_wrapper.go index 716f2d2b..6cc59721 100644 --- a/exchanges/binance/binance_wrapper.go +++ b/exchanges/binance/binance_wrapper.go @@ -3,7 +3,6 @@ package binance import ( "errors" "fmt" - "log" "strconv" "sync" @@ -12,6 +11,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKEX go routine @@ -26,7 +26,7 @@ func (b *Binance) Start(wg *sync.WaitGroup) { // Run implements the OKEX wrapper func (b *Binance) Run() { if b.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n%s polling delay: %ds.\n%s %d currencies enabled: %s.\n", + log.Debugf("%s Websocket: %s. (url: %s).\n%s polling delay: %ds.\n%s %d currencies enabled: %s.\n", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled()), b.Websocket.GetWebsocketURL(), @@ -39,7 +39,7 @@ func (b *Binance) Run() { symbols, err := b.GetExchangeValidCurrencyPairs() if err != nil { - log.Printf("%s Failed to get exchange info.\n", b.GetName()) + log.Errorf("%s Failed to get exchange info.\n", b.GetName()) } else { forceUpgrade := false if !common.StringDataContains(b.EnabledPairs, "-") || @@ -49,16 +49,16 @@ func (b *Binance) Run() { if forceUpgrade { enabledPairs := []string{"BTC-USDT"} - log.Println("WARNING: Available pairs for Binance reset due to config upgrade, please enable the ones you would like again") + log.Warn("Available pairs for Binance reset due to config upgrade, please enable the ones you would like again") err = b.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to get config.\n", b.GetName()) + log.Errorf("%s Failed to get config.\n", b.GetName()) } } err = b.UpdateCurrencies(symbols, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to get config.\n", b.GetName()) + log.Errorf("%s Failed to get config.\n", b.GetName()) } } } diff --git a/exchanges/bitfinex/bitfinex.go b/exchanges/bitfinex/bitfinex.go index 16014669..d3205f71 100644 --- a/exchanges/bitfinex/bitfinex.go +++ b/exchanges/bitfinex/bitfinex.go @@ -3,7 +3,6 @@ package bitfinex import ( "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -15,6 +14,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -906,7 +906,7 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ } if b.Verbose { - log.Printf("Request JSON: %s\n", PayloadJSON) + log.Debugf("Request JSON: %s\n", PayloadJSON) } PayloadBase64 := common.Base64Encode(PayloadJSON) diff --git a/exchanges/bitfinex/bitfinex_websocket.go b/exchanges/bitfinex/bitfinex_websocket.go index e8e74bc7..e7cb509a 100644 --- a/exchanges/bitfinex/bitfinex_websocket.go +++ b/exchanges/bitfinex/bitfinex_websocket.go @@ -3,7 +3,6 @@ package bitfinex import ( "errors" "fmt" - "log" "net/http" "net/url" "reflect" @@ -13,8 +12,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -116,7 +116,7 @@ func (b *Bitfinex) WsAddSubscriptionChannel(chanID int, channel, pair string) { b.WebsocketSubdChannels[chanID] = chanInfo if b.Verbose { - log.Printf("%s Subscribed to Channel: %s Pair: %s ChannelID: %d\n", + log.Debugf("%s Subscribed to Channel: %s Pair: %s ChannelID: %d\n", b.GetName(), channel, pair, @@ -160,7 +160,7 @@ func (b *Bitfinex) WsConnect() error { if hs.Event == "info" { if b.Verbose { - log.Printf("%s Connected to Websocket.\n", b.GetName()) + log.Debugf("%s Connected to Websocket.\n", b.GetName()) } } diff --git a/exchanges/bitfinex/bitfinex_wrapper.go b/exchanges/bitfinex/bitfinex_wrapper.go index e0012d91..d1301415 100644 --- a/exchanges/bitfinex/bitfinex_wrapper.go +++ b/exchanges/bitfinex/bitfinex_wrapper.go @@ -3,16 +3,16 @@ package bitfinex import ( "errors" "fmt" - "log" "net/url" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Bitfinex go routine @@ -27,18 +27,18 @@ func (b *Bitfinex) Start(wg *sync.WaitGroup) { // Run implements the Bitfinex wrapper func (b *Bitfinex) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } exchangeProducts, err := b.GetSymbols() if err != nil { - log.Printf("%s Failed to get available symbols.\n", b.GetName()) + log.Errorf("%s Failed to get available symbols.\n", b.GetName()) } else { err = b.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to update available symbols.\n", b.GetName()) + log.Errorf("%s Failed to update available symbols.\n", b.GetName()) } } } diff --git a/exchanges/bitflyer/bitflyer.go b/exchanges/bitflyer/bitflyer.go index 9d1fb1db..9876a798 100644 --- a/exchanges/bitflyer/bitflyer.go +++ b/exchanges/bitflyer/bitflyer.go @@ -3,7 +3,6 @@ package bitflyer import ( "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -14,6 +13,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/bitflyer/bitflyer_wrapper.go b/exchanges/bitflyer/bitflyer_wrapper.go index 7d525cb4..1ccd4a93 100644 --- a/exchanges/bitflyer/bitflyer_wrapper.go +++ b/exchanges/bitflyer/bitflyer_wrapper.go @@ -2,7 +2,6 @@ package bitflyer import ( "errors" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -10,6 +9,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Bitflyer go routine @@ -24,9 +24,9 @@ func (b *Bitflyer) Start(wg *sync.WaitGroup) { // Run implements the Bitflyer wrapper func (b *Bitflyer) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } /* diff --git a/exchanges/bithumb/bithumb.go b/exchanges/bithumb/bithumb.go index 7f99e362..0c3c85e1 100644 --- a/exchanges/bithumb/bithumb.go +++ b/exchanges/bithumb/bithumb.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/url" "reflect" "strconv" @@ -17,6 +16,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/bithumb/bithumb_wrapper.go b/exchanges/bithumb/bithumb_wrapper.go index 670bfcf7..ae83566f 100644 --- a/exchanges/bithumb/bithumb_wrapper.go +++ b/exchanges/bithumb/bithumb_wrapper.go @@ -2,7 +2,6 @@ package bithumb import ( "fmt" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -10,6 +9,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKEX go routine @@ -24,18 +24,18 @@ func (b *Bithumb) Start(wg *sync.WaitGroup) { // Run implements the OKEX wrapper func (b *Bithumb) Run() { if b.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled()), b.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled()), b.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } exchangeProducts, err := b.GetTradingPairs() if err != nil { - log.Printf("%s Failed to get available symbols.\n", b.GetName()) + log.Errorf("%s Failed to get available symbols.\n", b.GetName()) } else { err = b.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to update available symbols.\n", b.GetName()) + log.Errorf("%s Failed to update available symbols.\n", b.GetName()) } } } diff --git a/exchanges/bitmex/bitmex.go b/exchanges/bitmex/bitmex.go index c87ebcba..0a276f57 100644 --- a/exchanges/bitmex/bitmex.go +++ b/exchanges/bitmex/bitmex.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - "log" "strconv" "time" @@ -14,6 +13,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Bitmex is the overarching type across this package diff --git a/exchanges/bitmex/bitmex_websocket.go b/exchanges/bitmex/bitmex_websocket.go index e11f79e1..fb6e871a 100644 --- a/exchanges/bitmex/bitmex_websocket.go +++ b/exchanges/bitmex/bitmex_websocket.go @@ -3,18 +3,17 @@ package bitmex import ( "errors" "fmt" - "log" "net/http" "net/url" "strconv" "time" - "github.com/thrasher-/gocryptotrader/exchanges/orderbook" - "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" + "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -98,7 +97,7 @@ func (b *Bitmex) WsConnector() error { } if b.Verbose { - log.Printf("Successfully connected to Bitmex %s at time: %s Limit: %d", + log.Debugf("Successfully connected to Bitmex %s at time: %s Limit: %d", welcomeResp.Info, welcomeResp.Timestamp, welcomeResp.Limit.Remaining) @@ -187,14 +186,14 @@ func (b *Bitmex) wsHandleIncomingData() { quickCapture := make(map[string]interface{}) err := common.JSONDecode(resp.Raw, &quickCapture) if err != nil { - log.Fatal(err) + log.Error(err) } var respError WebsocketErrorResponse if _, ok := quickCapture["status"]; ok { err = common.JSONDecode(resp.Raw, &respError) if err != nil { - log.Fatal(err) + log.Error(err) } b.Websocket.DataHandler <- errors.New(respError.Error) continue @@ -204,16 +203,16 @@ func (b *Bitmex) wsHandleIncomingData() { var decodedResp WebsocketSubscribeResp err := common.JSONDecode(resp.Raw, &decodedResp) if err != nil { - log.Fatal(err) + log.Error(err) } if decodedResp.Success { if b.Verbose { if len(quickCapture) == 3 { - log.Printf("Bitmex Websocket: Successfully subscribed to %s", + log.Debugf("Bitmex Websocket: Successfully subscribed to %s", decodedResp.Subscribe) } else { - log.Println("Bitmex Websocket: Successfully authenticated websocket connection") + log.Debugf("Bitmex Websocket: Successfully authenticated websocket connection") } } continue @@ -226,7 +225,7 @@ func (b *Bitmex) wsHandleIncomingData() { var decodedResp WebsocketMainResponse err := common.JSONDecode(resp.Raw, &decodedResp) if err != nil { - log.Fatal(err) + log.Error(err) } switch decodedResp.Table { @@ -234,20 +233,20 @@ func (b *Bitmex) wsHandleIncomingData() { var orderbooks OrderBookData err = common.JSONDecode(resp.Raw, &orderbooks) if err != nil { - log.Fatal(err) + log.Error(err) } p := pair.NewCurrencyPairFromString(orderbooks.Data[0].Symbol) err = b.processOrderbook(orderbooks.Data, orderbooks.Action, p, "CONTRACT") if err != nil { - log.Fatal(err) + log.Error(err) } case bitmexWSTrade: var trades TradeData err = common.JSONDecode(resp.Raw, &trades) if err != nil { - log.Fatal(err) + log.Error(err) } if trades.Action == bitmexActionInitialData { @@ -257,7 +256,7 @@ func (b *Bitmex) wsHandleIncomingData() { for _, trade := range trades.Data { timestamp, err := time.Parse(time.RFC3339, trade.Timestamp) if err != nil { - log.Fatal(err) + log.Error(err) } b.Websocket.DataHandler <- exchange.TradeData{ @@ -276,7 +275,7 @@ func (b *Bitmex) wsHandleIncomingData() { err = common.JSONDecode(resp.Raw, &announcement) if err != nil { - log.Fatal(err) + log.Error(err) } if announcement.Action == bitmexActionInitialData { @@ -286,7 +285,7 @@ func (b *Bitmex) wsHandleIncomingData() { b.Websocket.DataHandler <- announcement.Data default: - log.Fatal("Bitmex websocket error: Table unknown -", decodedResp.Table) + log.Errorf("Bitmex websocket error: Table unknown - %s", decodedResp.Table) } } } diff --git a/exchanges/bitmex/bitmex_wrapper.go b/exchanges/bitmex/bitmex_wrapper.go index f26f3c2b..05fe54f1 100644 --- a/exchanges/bitmex/bitmex_wrapper.go +++ b/exchanges/bitmex/bitmex_wrapper.go @@ -2,7 +2,6 @@ package bitmex import ( "errors" - "log" "math" "sync" "time" @@ -12,6 +11,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Bitmex go routine @@ -26,14 +26,14 @@ func (b *Bitmex) Start(wg *sync.WaitGroup) { // Run implements the Bitmex wrapper func (b *Bitmex) Run() { if b.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled()), b.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled()), b.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } marketInfo, err := b.GetActiveInstruments(GenericRequestParams{}) if err != nil { - log.Printf("%s Failed to get available symbols.\n", b.GetName()) + log.Errorf("%s Failed to get available symbols.\n", b.GetName()) } else { var exchangeProducts []string @@ -43,7 +43,7 @@ func (b *Bitmex) Run() { err = b.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", b.GetName()) + log.Errorf("%s Failed to update available currencies.\n", b.GetName()) } } } diff --git a/exchanges/bitstamp/bitstamp.go b/exchanges/bitstamp/bitstamp.go index 460977ad..e76256a6 100644 --- a/exchanges/bitstamp/bitstamp.go +++ b/exchanges/bitstamp/bitstamp.go @@ -3,7 +3,6 @@ package bitstamp import ( "errors" "fmt" - "log" "net/url" "reflect" "strconv" @@ -13,9 +12,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -254,12 +254,12 @@ func (b *Bitstamp) GetOrderbook(currency string) (Orderbook, error) { for _, x := range resp.Bids { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Bids = append(orderbook.Bids, OrderbookBase{price, amount}) @@ -268,12 +268,12 @@ func (b *Bitstamp) GetOrderbook(currency string) (Orderbook, error) { for _, x := range resp.Asks { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Asks = append(orderbook.Asks, OrderbookBase{price, amount}) @@ -605,7 +605,7 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, v2 bool, values url } if b.Verbose { - log.Println("Sending POST request to " + path) + log.Debugf("Sending POST request to " + path) } headers := make(map[string]string) diff --git a/exchanges/bitstamp/bitstamp_websocket.go b/exchanges/bitstamp/bitstamp_websocket.go index 4a473a34..cb3ca8b7 100644 --- a/exchanges/bitstamp/bitstamp_websocket.go +++ b/exchanges/bitstamp/bitstamp_websocket.go @@ -3,16 +3,16 @@ package bitstamp import ( "errors" "fmt" - "log" "strconv" "strings" "time" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" - "github.com/toorop/go-pusher" + log "github.com/thrasher-/gocryptotrader/logger" + pusher "github.com/toorop/go-pusher" ) // WebsocketConn defins a pusher websocket connection @@ -78,7 +78,7 @@ func (b *Bitstamp) WsConnect() error { var err error if b.Websocket.GetProxyAddress() != "" { - log.Println("bistamp_websocket.go warning - set proxy address error: proxy not supported") + log.Warn("bitstamp_websocket.go warning - set proxy address error: proxy not supported") } b.WebsocketConn.Client, err = pusher.NewClient(BitstampPusherKey) @@ -147,7 +147,7 @@ func (b *Bitstamp) WsConnect() error { strings.ToLower(p.Pair().String()))) if err != nil { - log.Println(err) + log.Error(err) return fmt.Errorf("%s Websocket Trade subscription error: %s", b.GetName(), err) @@ -157,7 +157,7 @@ func (b *Bitstamp) WsConnect() error { strings.ToLower(p.Pair().String()))) if err != nil { - log.Println(err) + log.Error(err) return fmt.Errorf("%s Websocket Trade subscription error: %s", b.GetName(), err) diff --git a/exchanges/bitstamp/bitstamp_wrapper.go b/exchanges/bitstamp/bitstamp_wrapper.go index b59d0432..cbcf9780 100644 --- a/exchanges/bitstamp/bitstamp_wrapper.go +++ b/exchanges/bitstamp/bitstamp_wrapper.go @@ -3,7 +3,6 @@ package bitstamp import ( "errors" "fmt" - "log" "strconv" "strings" "sync" @@ -13,6 +12,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Bitstamp go routine @@ -27,14 +27,14 @@ func (b *Bitstamp) Start(wg *sync.WaitGroup) { // Run implements the Bitstamp wrapper func (b *Bitstamp) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } pairs, err := b.GetTradingPairs() if err != nil { - log.Printf("%s failed to get trading pairs. Err: %s", b.Name, err) + log.Errorf("%s failed to get trading pairs. Err: %s", b.Name, err) } else { var currencies []string for x := range pairs { @@ -46,7 +46,7 @@ func (b *Bitstamp) Run() { } err = b.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", b.Name) + log.Errorf("%s Failed to update available currencies.\n", b.Name) } } } diff --git a/exchanges/bittrex/bittrex.go b/exchanges/bittrex/bittrex.go index 0b5eafa8..c4d6ab67 100644 --- a/exchanges/bittrex/bittrex.go +++ b/exchanges/bittrex/bittrex.go @@ -3,16 +3,16 @@ package bittrex import ( "errors" "fmt" - "log" "net/url" "strconv" "time" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/bittrex/bittrex_wrapper.go b/exchanges/bittrex/bittrex_wrapper.go index 12534372..55a78377 100644 --- a/exchanges/bittrex/bittrex_wrapper.go +++ b/exchanges/bittrex/bittrex_wrapper.go @@ -3,7 +3,6 @@ package bittrex import ( "errors" "fmt" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -11,6 +10,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Bittrex go routine @@ -25,13 +25,13 @@ func (b *Bittrex) Start(wg *sync.WaitGroup) { // Run implements the Bittrex wrapper func (b *Bittrex) Run() { if b.Verbose { - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } exchangeProducts, err := b.GetMarkets() if err != nil { - log.Printf("%s Failed to get available symbols.\n", b.GetName()) + log.Errorf("%s Failed to get available symbols.\n", b.GetName()) } else { forceUpgrade := false if !common.StringDataContains(b.EnabledPairs, "-") || !common.StringDataContains(b.AvailablePairs, "-") { @@ -47,16 +47,16 @@ func (b *Bittrex) Run() { if forceUpgrade { enabledPairs := []string{"USDT-BTC"} - log.Println("WARNING: Available pairs for Bittrex reset due to config upgrade, please enable the ones you would like again") + log.Warn("Available pairs for Bittrex reset due to config upgrade, please enable the ones you would like again") err = b.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to get config.\n", b.GetName()) + log.Errorf("%s Failed to get config.", b.GetName()) } } err = b.UpdateCurrencies(currencies, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to get config.\n", b.GetName()) + log.Errorf("%s Failed to get config.", b.GetName()) } } } diff --git a/exchanges/btcc/btcc.go b/exchanges/btcc/btcc.go index 4367162c..f650b66c 100644 --- a/exchanges/btcc/btcc.go +++ b/exchanges/btcc/btcc.go @@ -1,15 +1,15 @@ package btcc import ( - "log" "time" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/btcc/btcc_websocket.go b/exchanges/btcc/btcc_websocket.go index 7ed468f8..8080ebd7 100644 --- a/exchanges/btcc/btcc_websocket.go +++ b/exchanges/btcc/btcc_websocket.go @@ -3,7 +3,6 @@ package btcc import ( "errors" "fmt" - "log" "net/http" "net/url" "strconv" @@ -15,6 +14,7 @@ import ( "github.com/thrasher-/gocryptotrader/currency/pair" exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -132,48 +132,37 @@ func (b *BTCC) WsHandleData() { case msgTypeHeartBeat: case msgTypeGetActiveContracts: - log.Println("Active Contracts") - log.Fatal(string(resp.Raw)) + log.Debugf("Active Contracts: %s", resp.Raw) case msgTypeQuote: - log.Println("Quotes") - log.Fatal(string(resp.Raw)) + log.Debugf("Quotes: %s", resp.Raw) case msgTypeLogin: - log.Println("Login") - log.Fatal(string(resp.Raw)) + log.Debugf("Login: %s", resp.Raw) case msgTypeAccountInfo: - log.Println("Account info") - log.Fatal(string(resp.Raw)) + log.Debugf("Account info: %s", resp.Raw) case msgTypeExecReport: - log.Println("Exec Report") - log.Fatal(string(resp.Raw)) + log.Debugf("Exec Report: %s", resp.Raw) case msgTypePlaceOrder: - log.Println("Place order") - log.Fatal(string(resp.Raw)) + log.Debugf("Place order: %s", resp.Raw) case msgTypeCancelAllOrders: - log.Println("Cancel All orders") - log.Fatal(string(resp.Raw)) + log.Debugf("Cancel All orders: %s", resp.Raw) case msgTypeCancelOrder: - log.Println("Cancel order") - log.Fatal(string(resp.Raw)) + log.Debugf("Cancel order: %s", resp.Raw) case msgTypeCancelReplaceOrder: - log.Println("Replace order") - log.Fatal(string(resp.Raw)) + log.Debugf("Replace order: %s", resp.Raw) case msgTypeGetAccountInfo: - log.Println("Account info") - log.Fatal(string(resp.Raw)) + log.Debugf("Account info: %s", resp.Raw) case msgTypeRetrieveOrder: - log.Println("Retrieve order") - log.Fatal(string(resp.Raw)) + log.Debugf("Retrieve order: %s", resp.Raw) case msgTypeGetTrades: var trades WsTrades diff --git a/exchanges/btcc/btcc_wrapper.go b/exchanges/btcc/btcc_wrapper.go index 14c7fad4..a603ecdb 100644 --- a/exchanges/btcc/btcc_wrapper.go +++ b/exchanges/btcc/btcc_wrapper.go @@ -2,7 +2,6 @@ package btcc import ( "errors" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" @@ -11,6 +10,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the BTCC go routine @@ -25,18 +25,18 @@ func (b *BTCC) Start(wg *sync.WaitGroup) { // Run implements the BTCC wrapper func (b *BTCC) Run() { if b.Verbose { - log.Printf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s Websocket: %s.", b.GetName(), common.IsEnabled(b.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } if common.StringDataContains(b.EnabledPairs, "CNY") || common.StringDataContains(b.AvailablePairs, "CNY") || common.StringDataContains(b.BaseCurrencies, "CNY") { - log.Println("WARNING: BTCC only supports BTCUSD now, upgrading available, enabled and base currencies to BTCUSD/USD") + log.Warn("BTCC only supports BTCUSD now, upgrading available, enabled and base currencies to BTCUSD/USD") pairs := []string{"BTCUSD"} cfg := config.GetConfig() exchCfg, err := cfg.GetExchangeConfig(b.Name) if err != nil { - log.Printf("%s failed to get exchange config. %s\n", b.Name, err) + log.Errorf("%s failed to get exchange config. %s\n", b.Name, err) return } @@ -47,17 +47,17 @@ func (b *BTCC) Run() { err = b.UpdateCurrencies(pairs, false, true) if err != nil { - log.Printf("%s failed to update available currencies. %s\n", b.Name, err) + log.Errorf("%s failed to update available currencies. %s\n", b.Name, err) } err = b.UpdateCurrencies(pairs, true, true) if err != nil { - log.Printf("%s failed to update enabled currencies. %s\n", b.Name, err) + log.Errorf("%s failed to update enabled currencies. %s\n", b.Name, err) } err = cfg.UpdateExchangeConfig(exchCfg) if err != nil { - log.Printf("%s failed to update config. %s\n", b.Name, err) + log.Errorf("%s failed to update config. %s\n", b.Name, err) return } } diff --git a/exchanges/btcmarkets/btcmarkets.go b/exchanges/btcmarkets/btcmarkets.go index ac16793f..2bbb9e0a 100644 --- a/exchanges/btcmarkets/btcmarkets.go +++ b/exchanges/btcmarkets/btcmarkets.go @@ -4,16 +4,16 @@ import ( "bytes" "errors" "fmt" - "log" "net/url" "time" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -442,7 +442,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa hmac := common.GetHMAC(common.HashSHA512, []byte(request), []byte(b.APISecret)) if b.Verbose { - log.Printf("Sending %s request to URL %s with params %s\n", reqType, b.APIUrl+path, request) + log.Debugf("Sending %s request to URL %s with params %s\n", reqType, b.APIUrl+path, request) } headers := make(map[string]string) diff --git a/exchanges/btcmarkets/btcmarkets_wrapper.go b/exchanges/btcmarkets/btcmarkets_wrapper.go index 6cb47d9b..f4613846 100644 --- a/exchanges/btcmarkets/btcmarkets_wrapper.go +++ b/exchanges/btcmarkets/btcmarkets_wrapper.go @@ -3,16 +3,15 @@ package btcmarkets import ( "errors" "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" - "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the BTC Markets go routine @@ -27,13 +26,13 @@ func (b *BTCMarkets) Start(wg *sync.WaitGroup) { // Run implements the BTC Markets wrapper func (b *BTCMarkets) Run() { if b.Verbose { - log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", b.GetName(), len(b.EnabledPairs), b.EnabledPairs) } markets, err := b.GetMarkets() if err != nil { - log.Printf("%s failed to get active market. Err: %s", b.Name, err) + log.Errorf("%s failed to get active market. Err: %s", b.Name, err) } else { forceUpgrade := false if !common.StringDataContains(b.EnabledPairs, "-") || !common.StringDataContains(b.AvailablePairs, "-") { @@ -47,16 +46,16 @@ func (b *BTCMarkets) Run() { if forceUpgrade { enabledPairs := []string{"BTC-AUD"} - log.Println("WARNING: Available pairs for BTC Makrets reset due to config upgrade, please enable the pairs you would like again.") + log.Warn("Available pairs for BTC Makrets reset due to config upgrade, please enable the pairs you would like again.") err = b.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s failed to update currencies. Err: %s", b.Name, err) + log.Errorf("%s failed to update currencies. Err: %s", b.Name, err) } } err = b.UpdateCurrencies(currencies, false, forceUpgrade) if err != nil { - log.Printf("%s failed to update currencies. Err: %s", b.Name, err) + log.Errorf("%s failed to update currencies. Err: %s", b.Name, err) } } } diff --git a/exchanges/coinbasepro/coinbasepro.go b/exchanges/coinbasepro/coinbasepro.go index 2ebfc507..ffceb0fc 100644 --- a/exchanges/coinbasepro/coinbasepro.go +++ b/exchanges/coinbasepro/coinbasepro.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -14,9 +13,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -807,7 +807,7 @@ func (c *CoinbasePro) SendAuthenticatedHTTPRequest(method, path string, params m } if c.Verbose { - log.Printf("Request JSON: %s\n", payload) + log.Debugf("Request JSON: %s\n", payload) } } diff --git a/exchanges/coinbasepro/coinbasepro_websocket.go b/exchanges/coinbasepro/coinbasepro_websocket.go index 474596e0..ae93b79b 100644 --- a/exchanges/coinbasepro/coinbasepro_websocket.go +++ b/exchanges/coinbasepro/coinbasepro_websocket.go @@ -3,7 +3,6 @@ package coinbasepro import ( "errors" "fmt" - "log" "net/http" "net/url" "strconv" @@ -12,8 +11,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/coinbasepro/coinbasepro_wrapper.go b/exchanges/coinbasepro/coinbasepro_wrapper.go index a09a5cad..8349cbc1 100644 --- a/exchanges/coinbasepro/coinbasepro_wrapper.go +++ b/exchanges/coinbasepro/coinbasepro_wrapper.go @@ -2,14 +2,14 @@ package coinbasepro import ( "errors" - "log" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the coinbasepro go routine @@ -24,14 +24,14 @@ func (c *CoinbasePro) Start(wg *sync.WaitGroup) { // Run implements the coinbasepro wrapper func (c *CoinbasePro) Run() { if c.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", c.GetName(), common.IsEnabled(c.Websocket.IsEnabled()), coinbaseproWebsocketURL) - log.Printf("%s polling delay: %ds.\n", c.GetName(), c.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", c.GetName(), len(c.EnabledPairs), c.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", c.GetName(), common.IsEnabled(c.Websocket.IsEnabled()), coinbaseproWebsocketURL) + log.Debugf("%s polling delay: %ds.\n", c.GetName(), c.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", c.GetName(), len(c.EnabledPairs), c.EnabledPairs) } exchangeProducts, err := c.GetProducts() if err != nil { - log.Printf("%s Failed to get available products.\n", c.GetName()) + log.Errorf("%s Failed to get available products.\n", c.GetName()) } else { currencies := []string{} for _, x := range exchangeProducts { @@ -41,7 +41,7 @@ func (c *CoinbasePro) Run() { } err = c.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", c.GetName()) + log.Errorf("%s Failed to update available currencies.\n", c.GetName()) } } } diff --git a/exchanges/coinut/coinut.go b/exchanges/coinut/coinut.go index 4128fa8e..01a6956f 100644 --- a/exchanges/coinut/coinut.go +++ b/exchanges/coinut/coinut.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "time" "github.com/gorilla/websocket" @@ -12,9 +11,10 @@ import ( "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -352,7 +352,7 @@ func (c *COINUT) SendHTTPRequest(apiRequest string, params map[string]interface{ } if c.Verbose { - log.Printf("Request JSON: %s\n", payload) + log.Debugf("Request JSON: %s", payload) } headers := make(map[string]string) diff --git a/exchanges/coinut/coinut_websocket.go b/exchanges/coinut/coinut_websocket.go index afc33136..91cc721a 100644 --- a/exchanges/coinut/coinut_websocket.go +++ b/exchanges/coinut/coinut_websocket.go @@ -3,7 +3,6 @@ package coinut import ( "errors" "fmt" - "log" "net/http" "net/url" "time" @@ -11,8 +10,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const coinutWebsocketURL = "wss://wsapi.coinut.com" diff --git a/exchanges/coinut/coinut_wrapper.go b/exchanges/coinut/coinut_wrapper.go index 67548468..bdea8979 100644 --- a/exchanges/coinut/coinut_wrapper.go +++ b/exchanges/coinut/coinut_wrapper.go @@ -3,17 +3,16 @@ package coinut import ( "errors" "fmt" - "log" "strconv" "sync" - "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + "github.com/thrasher-/gocryptotrader/currency/symbol" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the COINUT go routine @@ -28,14 +27,14 @@ func (c *COINUT) Start(wg *sync.WaitGroup) { // Run implements the COINUT wrapper func (c *COINUT) Run() { if c.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", c.GetName(), common.IsEnabled(c.Websocket.IsEnabled()), coinutWebsocketURL) - log.Printf("%s polling delay: %ds.\n", c.GetName(), c.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", c.GetName(), len(c.EnabledPairs), c.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", c.GetName(), common.IsEnabled(c.Websocket.IsEnabled()), coinutWebsocketURL) + log.Debugf("%s polling delay: %ds.\n", c.GetName(), c.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", c.GetName(), len(c.EnabledPairs), c.EnabledPairs) } exchangeProducts, err := c.GetInstruments() if err != nil { - log.Printf("%s Failed to get available products.\n", c.GetName()) + log.Debugf("%s Failed to get available products.\n", c.GetName()) return } @@ -48,7 +47,7 @@ func (c *COINUT) Run() { err = c.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", c.GetName()) + log.Errorf("%s Failed to update available currencies.\n", c.GetName()) } } diff --git a/exchanges/exchange.go b/exchanges/exchange.go index 4fe99ba6..f1ec116b 100644 --- a/exchanges/exchange.go +++ b/exchanges/exchange.go @@ -3,7 +3,6 @@ package exchange import ( "errors" "fmt" - "log" "net/http" "net/url" "strings" @@ -17,6 +16,7 @@ import ( "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -654,7 +654,7 @@ func (e *Base) SetAPIKeys(APIKey, APISecret, ClientID string, b64Decode bool) { result, err := common.Base64Decode(APISecret) if err != nil { e.AuthenticatedAPISupport = false - log.Printf(warningBase64DecryptSecretKeyFailed, e.Name) + log.Warn(warningBase64DecryptSecretKeyFailed, e.Name) } e.APISecret = string(result) } else { @@ -728,13 +728,13 @@ func (e *Base) UpdateCurrencies(exchangeProducts []string, enabled, force bool) } if force { - log.Printf("%s forced update of %s pairs.", e.Name, updateType) + log.Debugf("%s forced update of %s pairs.", e.Name, updateType) } else { if len(newPairs) > 0 { - log.Printf("%s Updating pairs - New: %s.\n", e.Name, newPairs) + log.Debugf("%s Updating pairs - New: %s.\n", e.Name, newPairs) } if len(removedPairs) > 0 { - log.Printf("%s Updating pairs - Removed: %s.\n", e.Name, removedPairs) + log.Debugf("%s Updating pairs - Removed: %s.\n", e.Name, removedPairs) } } diff --git a/exchanges/exchange_websocket.go b/exchanges/exchange_websocket.go index cd642829..73f76ab5 100644 --- a/exchanges/exchange_websocket.go +++ b/exchanges/exchange_websocket.go @@ -167,8 +167,7 @@ func (w *Websocket) Connect() error { defer w.m.Unlock() if !w.IsEnabled() { - return fmt.Errorf("exchange_websocket.go %s error - websocket disabled", - w.GetName()) + return errors.New(WebsocketNotEnabled) } if w.connected { diff --git a/exchanges/exmo/exmo.go b/exchanges/exmo/exmo.go index e29cb30f..d90079c4 100644 --- a/exchanges/exmo/exmo.go +++ b/exchanges/exmo/exmo.go @@ -3,7 +3,6 @@ package exmo import ( "errors" "fmt" - "log" "net/url" "reflect" "strconv" @@ -16,6 +15,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -274,7 +274,7 @@ func (e *EXMO) GetRequiredAmount(pair string, amount float64) (RequiredAmount, e func (e *EXMO) GetCryptoDepositAddress() (map[string]string, error) { result := make(map[string]string) err := e.SendAuthenticatedHTTPRequest("POST", exmoDepositAddress, url.Values{}, &result) - log.Println(reflect.TypeOf(result).String()) + log.Debug(reflect.TypeOf(result).String()) return result, err } @@ -376,7 +376,7 @@ func (e *EXMO) SendAuthenticatedHTTPRequest(method, endpoint string, vals url.Va hash := common.GetHMAC(common.HashSHA512, []byte(payload), []byte(e.APISecret)) if e.Verbose { - log.Printf("Sending %s request to %s with params %s\n", method, endpoint, payload) + log.Debugf("Sending %s request to %s with params %s\n", method, endpoint, payload) } headers := make(map[string]string) diff --git a/exchanges/exmo/exmo_wrapper.go b/exchanges/exmo/exmo_wrapper.go index 364cce71..436d4342 100644 --- a/exchanges/exmo/exmo_wrapper.go +++ b/exchanges/exmo/exmo_wrapper.go @@ -3,7 +3,6 @@ package exmo import ( "errors" "fmt" - "log" "strconv" "sync" @@ -12,6 +11,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the EXMO go routine @@ -26,13 +26,13 @@ func (e *EXMO) Start(wg *sync.WaitGroup) { // Run implements the EXMO wrapper func (e *EXMO) Run() { if e.Verbose { - log.Printf("%s polling delay: %ds.\n", e.GetName(), e.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", e.GetName(), len(e.EnabledPairs), e.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", e.GetName(), e.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", e.GetName(), len(e.EnabledPairs), e.EnabledPairs) } exchangeProducts, err := e.GetPairSettings() if err != nil { - log.Printf("%s Failed to get available products.\n", e.GetName()) + log.Errorf("%s Failed to get available products.\n", e.GetName()) } else { var currencies []string for x := range exchangeProducts { @@ -40,7 +40,7 @@ func (e *EXMO) Run() { } err = e.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", e.GetName()) + log.Errorf("%s Failed to update available currencies.\n", e.GetName()) } } } diff --git a/exchanges/gateio/gateio.go b/exchanges/gateio/gateio.go index d17af1d0..1fa0bcbf 100644 --- a/exchanges/gateio/gateio.go +++ b/exchanges/gateio/gateio.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "strconv" "strings" "time" @@ -14,6 +13,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/gateio/gateio_wrapper.go b/exchanges/gateio/gateio_wrapper.go index 912ac275..c94aa439 100644 --- a/exchanges/gateio/gateio_wrapper.go +++ b/exchanges/gateio/gateio_wrapper.go @@ -2,15 +2,15 @@ package gateio import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the GateIO go routine @@ -25,18 +25,18 @@ func (g *Gateio) Start(wg *sync.WaitGroup) { // Run implements the GateIO wrapper func (g *Gateio) Run() { if g.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", g.GetName(), common.IsEnabled(g.Websocket.IsEnabled()), g.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", g.GetName(), g.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", g.GetName(), len(g.EnabledPairs), g.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", g.GetName(), common.IsEnabled(g.Websocket.IsEnabled()), g.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", g.GetName(), g.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", g.GetName(), len(g.EnabledPairs), g.EnabledPairs) } symbols, err := g.GetSymbols() if err != nil { - log.Printf("%s Unable to fetch symbols.\n", g.GetName()) + log.Errorf("%s Unable to fetch symbols.\n", g.GetName()) } else { err = g.UpdateCurrencies(symbols, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", g.GetName()) + log.Errorf("%s Failed to update available currencies.\n", g.GetName()) } } } diff --git a/exchanges/gemini/gemini.go b/exchanges/gemini/gemini.go index 2aaee6a5..f23c4b29 100644 --- a/exchanges/gemini/gemini.go +++ b/exchanges/gemini/gemini.go @@ -3,7 +3,6 @@ package gemini import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -11,9 +10,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -494,7 +494,7 @@ func (g *Gemini) SendAuthenticatedHTTPRequest(method, path string, params map[st } if g.Verbose { - log.Printf("Request JSON: %s\n", PayloadJSON) + log.Debugf("Request JSON: %s", PayloadJSON) } PayloadBase64 := common.Base64Encode(PayloadJSON) diff --git a/exchanges/gemini/gemini_wrapper.go b/exchanges/gemini/gemini_wrapper.go index bfe7273d..5fe4663d 100644 --- a/exchanges/gemini/gemini_wrapper.go +++ b/exchanges/gemini/gemini_wrapper.go @@ -3,16 +3,16 @@ package gemini import ( "errors" "fmt" - "log" "net/url" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Gemini go routine @@ -27,17 +27,17 @@ func (g *Gemini) Start(wg *sync.WaitGroup) { // Run implements the Gemini wrapper func (g *Gemini) Run() { if g.Verbose { - log.Printf("%s polling delay: %ds.\n", g.GetName(), g.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", g.GetName(), len(g.EnabledPairs), g.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", g.GetName(), g.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", g.GetName(), len(g.EnabledPairs), g.EnabledPairs) } exchangeProducts, err := g.GetSymbols() if err != nil { - log.Printf("%s Failed to get available symbols.\n", g.GetName()) + log.Errorf("%s Failed to get available symbols.\n", g.GetName()) } else { err = g.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", g.GetName()) + log.Errorf("%s Failed to update available currencies.\n", g.GetName()) } } } diff --git a/exchanges/hitbtc/hitbtc.go b/exchanges/hitbtc/hitbtc.go index 490f55f3..92ab0767 100644 --- a/exchanges/hitbtc/hitbtc.go +++ b/exchanges/hitbtc/hitbtc.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -13,9 +12,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/hitbtc/hitbtc_websocket.go b/exchanges/hitbtc/hitbtc_websocket.go index b1161edf..33c1309d 100644 --- a/exchanges/hitbtc/hitbtc_websocket.go +++ b/exchanges/hitbtc/hitbtc_websocket.go @@ -3,7 +3,6 @@ package hitbtc import ( "errors" "fmt" - "log" "net/http" "net/url" "time" @@ -11,8 +10,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -149,7 +149,7 @@ func (h *HitBTC) WsHandleData() { var init capture err := common.JSONDecode(resp.Raw, &init) if err != nil { - log.Fatal(err) + log.Error(err) } if init.Error.Message != "" || init.Error.Code != 0 { @@ -168,12 +168,12 @@ func (h *HitBTC) WsHandleData() { var ticker WsTicker err := common.JSONDecode(resp.Raw, &ticker) if err != nil { - log.Fatal(err) + log.Error(err) } ts, err := time.Parse(time.RFC3339, ticker.Params.Timestamp) if err != nil { - log.Fatal(err) + log.Error(err) } h.Websocket.DataHandler <- exchange.TickerData{ @@ -191,19 +191,19 @@ func (h *HitBTC) WsHandleData() { var obSnapshot WsOrderbook err := common.JSONDecode(resp.Raw, &obSnapshot) if err != nil { - log.Fatal(err) + log.Error(err) } err = h.WsProcessOrderbookSnapshot(obSnapshot) if err != nil { - log.Fatal(err) + log.Error(err) } case "updateOrderbook": var obUpdate WsOrderbook err := common.JSONDecode(resp.Raw, &obUpdate) if err != nil { - log.Fatal(err) + log.Error(err) } h.WsProcessOrderbookUpdate(obUpdate) @@ -212,14 +212,14 @@ func (h *HitBTC) WsHandleData() { var tradeSnapshot WsTrade err := common.JSONDecode(resp.Raw, &tradeSnapshot) if err != nil { - log.Fatal(err) + log.Error(err) } case "updateTrades": var tradeUpdates WsTrade err := common.JSONDecode(resp.Raw, &tradeUpdates) if err != nil { - log.Fatal(err) + log.Error(err) } } } diff --git a/exchanges/hitbtc/hitbtc_wrapper.go b/exchanges/hitbtc/hitbtc_wrapper.go index 5162969f..32e29964 100644 --- a/exchanges/hitbtc/hitbtc_wrapper.go +++ b/exchanges/hitbtc/hitbtc_wrapper.go @@ -2,15 +2,16 @@ package hitbtc import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the HitBTC go routine @@ -25,14 +26,14 @@ func (h *HitBTC) Start(wg *sync.WaitGroup) { // Run implements the HitBTC wrapper func (h *HitBTC) Run() { if h.Verbose { - log.Printf("%s Websocket: %s (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), hitbtcWebsocketAddress) - log.Printf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) + log.Debugf("%s Websocket: %s (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), hitbtcWebsocketAddress) + log.Debugf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) } exchangeProducts, err := h.GetSymbolsDetailed() if err != nil { - log.Printf("%s Failed to get available symbols.\n", h.GetName()) + log.Errorf("%s Failed to get available symbols.\n", h.GetName()) } else { forceUpgrade := false if !common.StringDataContains(h.EnabledPairs, "-") || !common.StringDataContains(h.AvailablePairs, "-") { @@ -45,16 +46,16 @@ func (h *HitBTC) Run() { if forceUpgrade { enabledPairs := []string{"BTC-USD"} - log.Println("WARNING: Available pairs for HitBTC reset due to config upgrade, please enable the ones you would like again.") + log.Warn("Available pairs for HitBTC reset due to config upgrade, please enable the ones you would like again.") err = h.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to update enabled currencies.\n", h.GetName()) + log.Errorf("%s Failed to update enabled currencies.\n", h.GetName()) } } err = h.UpdateCurrencies(currencies, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to update available currencies.\n", h.GetName()) + log.Errorf("%s Failed to update available currencies.\n", h.GetName()) } } } diff --git a/exchanges/huobi/huobi.go b/exchanges/huobi/huobi.go index b478ede8..13d60f44 100644 --- a/exchanges/huobi/huobi.go +++ b/exchanges/huobi/huobi.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io/ioutil" - "log" "net/http" "net/url" "strconv" @@ -24,6 +23,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/huobi/huobi_websocket.go b/exchanges/huobi/huobi_websocket.go index 5dee620c..11d6c6c7 100644 --- a/exchanges/huobi/huobi_websocket.go +++ b/exchanges/huobi/huobi_websocket.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io/ioutil" - "log" "math/big" "net/http" "net/url" @@ -15,8 +14,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -81,7 +81,7 @@ func (h *HUOBI) WsReadData() { default: _, resp, err := h.WebsocketConn.ReadMessage() if err != nil { - log.Fatal(err) + log.Error(err) } h.Websocket.TrafficAlert <- struct{}{} @@ -89,12 +89,12 @@ func (h *HUOBI) WsReadData() { b := bytes.NewReader(resp) gReader, err := gzip.NewReader(b) if err != nil { - log.Fatal(err) + log.Error(err) } unzipped, err := ioutil.ReadAll(gReader) if err != nil { - log.Fatal(err) + log.Error(err) } gReader.Close() @@ -115,7 +115,7 @@ func (h *HUOBI) WsHandleData() { var init WsResponse err := common.JSONDecode(resp.Raw, &init) if err != nil { - log.Fatal(err) + log.Error(err) } if init.Status == "error" { @@ -132,7 +132,7 @@ func (h *HUOBI) WsHandleData() { if init.Ping != 0 { err = h.WebsocketConn.WriteJSON(`{"pong":1337}`) if err != nil { - log.Fatal(err) + log.Error(err) } continue } @@ -142,7 +142,7 @@ func (h *HUOBI) WsHandleData() { var depth WsDepth err := common.JSONDecode(resp.Raw, &depth) if err != nil { - log.Fatal(err) + log.Error(err) } data := common.SplitStrings(depth.Channel, ".") @@ -153,7 +153,7 @@ func (h *HUOBI) WsHandleData() { var kline WsKline err := common.JSONDecode(resp.Raw, &kline) if err != nil { - log.Fatal(err) + log.Error(err) } data := common.SplitStrings(kline.Channel, ".") @@ -174,7 +174,7 @@ func (h *HUOBI) WsHandleData() { var trade WsTrade err := common.JSONDecode(resp.Raw, &trade) if err != nil { - log.Fatal(err) + log.Error(err) } data := common.SplitStrings(trade.Channel, ".") diff --git a/exchanges/huobi/huobi_wrapper.go b/exchanges/huobi/huobi_wrapper.go index 768e050c..36940d79 100644 --- a/exchanges/huobi/huobi_wrapper.go +++ b/exchanges/huobi/huobi_wrapper.go @@ -3,16 +3,16 @@ package huobi import ( "errors" "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the HUOBI go routine @@ -27,14 +27,14 @@ func (h *HUOBI) Start(wg *sync.WaitGroup) { // Run implements the HUOBI wrapper func (h *HUOBI) Run() { if h.Verbose { - log.Printf("%s Websocket: %s (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), huobiSocketIOAddress) - log.Printf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) + log.Debugf("%s Websocket: %s (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), huobiSocketIOAddress) + log.Debugf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) } exchangeProducts, err := h.GetSymbols() if err != nil { - log.Printf("%s Failed to get available symbols.\n", h.GetName()) + log.Errorf("%s Failed to get available symbols.\n", h.GetName()) } else { forceUpgrade := false if common.StringDataContains(h.EnabledPairs, "CNY") || common.StringDataContains(h.AvailablePairs, "CNY") { @@ -45,7 +45,7 @@ func (h *HUOBI) Run() { cfg := config.GetConfig() exchCfg, errCNY := cfg.GetExchangeConfig(h.Name) if err != nil { - log.Printf("%s failed to get exchange config. %s\n", h.Name, errCNY) + log.Errorf("%s failed to get exchange config. %s\n", h.Name, errCNY) return } exchCfg.BaseCurrencies = "USD" @@ -53,7 +53,7 @@ func (h *HUOBI) Run() { errCNY = cfg.UpdateExchangeConfig(exchCfg) if errCNY != nil { - log.Printf("%s failed to update config. %s\n", h.Name, errCNY) + log.Errorf("%s failed to update config. %s\n", h.Name, errCNY) return } } @@ -66,16 +66,16 @@ func (h *HUOBI) Run() { if forceUpgrade { enabledPairs := []string{"btc-usdt"} - log.Println("WARNING: Available and enabled pairs for Huobi reset due to config upgrade, please enable the ones you would like again") + log.Warn("Available and enabled pairs for Huobi reset due to config upgrade, please enable the ones you would like again") err = h.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to update enabled currencies.\n", h.GetName()) + log.Errorf("%s Failed to update enabled currencies.\n", h.GetName()) } } err = h.UpdateCurrencies(currencies, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to update available currencies.\n", h.GetName()) + log.Errorf("%s Failed to update available currencies.\n", h.GetName()) } } } diff --git a/exchanges/huobihadax/huobihadax.go b/exchanges/huobihadax/huobihadax.go index c4a75794..b887cbec 100644 --- a/exchanges/huobihadax/huobihadax.go +++ b/exchanges/huobihadax/huobihadax.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -13,9 +12,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/huobihadax/huobihadax_wrapper.go b/exchanges/huobihadax/huobihadax_wrapper.go index 4d00b134..c38dbda3 100644 --- a/exchanges/huobihadax/huobihadax_wrapper.go +++ b/exchanges/huobihadax/huobihadax_wrapper.go @@ -3,15 +3,15 @@ package huobihadax import ( "errors" "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKEX go routine @@ -26,14 +26,14 @@ func (h *HUOBIHADAX) Start(wg *sync.WaitGroup) { // Run implements the OKEX wrapper func (h *HUOBIHADAX) Run() { if h.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), h.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", h.GetName(), common.IsEnabled(h.Websocket.IsEnabled()), h.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", h.GetName(), h.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", h.GetName(), len(h.EnabledPairs), h.EnabledPairs) } exchangeProducts, err := h.GetSymbols() if err != nil { - log.Printf("%s Failed to get available symbols.\n", h.GetName()) + log.Debugf("%s Failed to get available symbols.\n", h.GetName()) } else { var currencies []string for x := range exchangeProducts { @@ -43,7 +43,7 @@ func (h *HUOBIHADAX) Run() { err = h.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", h.GetName()) + log.Debugf("%s Failed to update available currencies.\n", h.GetName()) } } } diff --git a/exchanges/itbit/itbit.go b/exchanges/itbit/itbit.go index 916bc3a9..0ba68498 100644 --- a/exchanges/itbit/itbit.go +++ b/exchanges/itbit/itbit.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -13,9 +12,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -379,7 +379,7 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params } if i.Verbose { - log.Printf("Request JSON: %s\n", PayloadJSON) + log.Debugf("Request JSON: %s\n", PayloadJSON) } } diff --git a/exchanges/itbit/itbit_wrapper.go b/exchanges/itbit/itbit_wrapper.go index 56b8961a..64117ced 100644 --- a/exchanges/itbit/itbit_wrapper.go +++ b/exchanges/itbit/itbit_wrapper.go @@ -2,16 +2,16 @@ package itbit import ( "fmt" - "log" "net/url" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the ItBit go routine @@ -26,8 +26,8 @@ func (i *ItBit) Start(wg *sync.WaitGroup) { // Run implements the ItBit wrapper func (i *ItBit) Run() { if i.Verbose { - log.Printf("%s polling delay: %ds.\n", i.GetName(), i.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", i.GetName(), len(i.EnabledPairs), i.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", i.GetName(), i.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", i.GetName(), len(i.EnabledPairs), i.EnabledPairs) } } @@ -82,11 +82,11 @@ func (i *ItBit) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderboo data := orderbookNew.Bids[x] price, err := strconv.ParseFloat(data[0], 64) if err != nil { - log.Println(err) + log.Error(err) } amount, err := strconv.ParseFloat(data[1], 64) if err != nil { - log.Println(err) + log.Error(err) } orderBook.Bids = append(orderBook.Bids, orderbook.Item{Amount: amount, Price: price}) } @@ -95,11 +95,11 @@ func (i *ItBit) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderboo data := orderbookNew.Asks[x] price, err := strconv.ParseFloat(data[0], 64) if err != nil { - log.Println(err) + log.Error(err) } amount, err := strconv.ParseFloat(data[1], 64) if err != nil { - log.Println(err) + log.Error(err) } orderBook.Asks = append(orderBook.Asks, orderbook.Item{Amount: amount, Price: price}) } diff --git a/exchanges/kraken/kraken.go b/exchanges/kraken/kraken.go index e6897c40..5e2841ba 100644 --- a/exchanges/kraken/kraken.go +++ b/exchanges/kraken/kraken.go @@ -2,7 +2,6 @@ package kraken import ( "fmt" - "log" "net/url" "strconv" "strings" @@ -10,9 +9,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -892,7 +892,7 @@ func GetError(errors []string) error { for _, e := range errors { switch e[0] { case 'W': - log.Printf("Kraken API warning: %v\n", e[1:]) + log.Warnf("Kraken API warning: %v\n", e[1:]) default: return fmt.Errorf("Kraken API error: %v", e[1:]) } @@ -931,7 +931,7 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, params url.Values, signature := common.Base64Encode(common.GetHMAC(common.HashSHA512, append([]byte(path), shasum...), secret)) if k.Verbose { - log.Printf("Sending POST request to %s, path: %s, params: %s", k.APIUrl, path, encoded) + log.Debugf("Sending POST request to %s, path: %s, params: %s", k.APIUrl, path, encoded) } headers := make(map[string]string) diff --git a/exchanges/kraken/kraken_wrapper.go b/exchanges/kraken/kraken_wrapper.go index 7fbded3f..f9885bb6 100644 --- a/exchanges/kraken/kraken_wrapper.go +++ b/exchanges/kraken/kraken_wrapper.go @@ -1,15 +1,15 @@ package kraken import ( - "log" "strings" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Kraken go routine @@ -24,13 +24,13 @@ func (k *Kraken) Start(wg *sync.WaitGroup) { // Run implements the Kraken wrapper func (k *Kraken) Run() { if k.Verbose { - log.Printf("%s polling delay: %ds.\n", k.GetName(), k.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", k.GetName(), len(k.EnabledPairs), k.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", k.GetName(), k.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", k.GetName(), len(k.EnabledPairs), k.EnabledPairs) } assetPairs, err := k.GetAssetPairs() if err != nil { - log.Printf("%s Failed to get available symbols.\n", k.GetName()) + log.Errorf("%s Failed to get available symbols.\n", k.GetName()) } else { forceUpgrade := false if !common.StringDataContains(k.EnabledPairs, "-") || !common.StringDataContains(k.AvailablePairs, "-") { @@ -55,16 +55,16 @@ func (k *Kraken) Run() { if forceUpgrade { enabledPairs := []string{"XBT-USD"} - log.Println("WARNING: Available pairs for Kraken reset due to config upgrade, please enable the ones you would like again") + log.Warn("Available pairs for Kraken reset due to config upgrade, please enable the ones you would like again") err = k.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to get config.\n", k.GetName()) + log.Errorf("%s Failed to get config.\n", k.GetName()) } } err = k.UpdateCurrencies(exchangeProducts, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to get config.\n", k.GetName()) + log.Errorf("%s Failed to get config.\n", k.GetName()) } } } diff --git a/exchanges/lakebtc/lakebtc.go b/exchanges/lakebtc/lakebtc.go index ce8c5243..59a79b0c 100644 --- a/exchanges/lakebtc/lakebtc.go +++ b/exchanges/lakebtc/lakebtc.go @@ -3,7 +3,6 @@ package lakebtc import ( "errors" "fmt" - "log" "strconv" "strings" "time" @@ -11,9 +10,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -175,12 +175,12 @@ func (l *LakeBTC) GetOrderBook(currency string) (Orderbook, error) { for _, x := range resp.Bids { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Bids = append(orderbook.Bids, OrderbookStructure{price, amount}) @@ -189,12 +189,12 @@ func (l *LakeBTC) GetOrderBook(currency string) (Orderbook, error) { for _, x := range resp.Asks { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Asks = append(orderbook.Asks, OrderbookStructure{price, amount}) @@ -353,7 +353,7 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string, result int hmac := common.GetHMAC(common.HashSHA1, []byte(req), []byte(l.APISecret)) if l.Verbose { - log.Printf("Sending POST request to %s calling method %s with params %s\n", l.APIUrl, method, req) + log.Debugf("Sending POST request to %s calling method %s with params %s\n", l.APIUrl, method, req) } postData := make(map[string]interface{}) diff --git a/exchanges/lakebtc/lakebtc_wrapper.go b/exchanges/lakebtc/lakebtc_wrapper.go index 24601a9f..e12944f0 100644 --- a/exchanges/lakebtc/lakebtc_wrapper.go +++ b/exchanges/lakebtc/lakebtc_wrapper.go @@ -3,16 +3,16 @@ package lakebtc import ( "errors" "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the LakeBTC go routine @@ -27,17 +27,17 @@ func (l *LakeBTC) Start(wg *sync.WaitGroup) { // Run implements the LakeBTC wrapper func (l *LakeBTC) Run() { if l.Verbose { - log.Printf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) } exchangeProducts, err := l.GetTradablePairs() if err != nil { - log.Printf("%s Failed to get available products.\n", l.GetName()) + log.Errorf("%s Failed to get available products.\n", l.GetName()) } else { err = l.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", l.GetName()) + log.Errorf("%s Failed to update available currencies.\n", l.GetName()) } } } diff --git a/exchanges/liqui/liqui.go b/exchanges/liqui/liqui.go index c6e82816..cf727d5d 100644 --- a/exchanges/liqui/liqui.go +++ b/exchanges/liqui/liqui.go @@ -3,7 +3,6 @@ package liqui import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -11,9 +10,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -299,7 +299,7 @@ func (l *Liqui) SendAuthenticatedHTTPRequest(method string, values url.Values, r hmac := common.GetHMAC(common.HashSHA512, []byte(encoded), []byte(l.APISecret)) if l.Verbose { - log.Printf("Sending POST request to %s calling method %s with params %s\n", + log.Debugf("Sending POST request to %s calling method %s with params %s\n", l.APIUrlSecondary, method, encoded) } diff --git a/exchanges/liqui/liqui_wrapper.go b/exchanges/liqui/liqui_wrapper.go index ad6729b0..4cf97b4f 100644 --- a/exchanges/liqui/liqui_wrapper.go +++ b/exchanges/liqui/liqui_wrapper.go @@ -2,15 +2,15 @@ package liqui import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Liqui go routine @@ -25,19 +25,19 @@ func (l *Liqui) Start(wg *sync.WaitGroup) { // Run implements the Liqui wrapper func (l *Liqui) Run() { if l.Verbose { - log.Printf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) } var err error l.Info, err = l.GetInfo() if err != nil { - log.Printf("%s Unable to fetch info.\n", l.GetName()) + log.Errorf("%s Unable to fetch info.\n", l.GetName()) } else { exchangeProducts := l.GetAvailablePairs(true) err = l.UpdateCurrencies(exchangeProducts, false, false) if err != nil { - log.Printf("%s Failed to get config.\n", l.GetName()) + log.Errorf("%s Failed to get config.\n", l.GetName()) } } } diff --git a/exchanges/localbitcoins/localbitcoins.go b/exchanges/localbitcoins/localbitcoins.go index 86a01006..6a7808e1 100644 --- a/exchanges/localbitcoins/localbitcoins.go +++ b/exchanges/localbitcoins/localbitcoins.go @@ -3,7 +3,6 @@ package localbitcoins import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -11,8 +10,9 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -677,12 +677,12 @@ func (l *LocalBitcoins) GetOrderbook(currency string) (Orderbook, error) { for _, x := range resp.Bids { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Bids = append(orderbook.Bids, Price{price, amount}) @@ -691,12 +691,12 @@ func (l *LocalBitcoins) GetOrderbook(currency string) (Orderbook, error) { for _, x := range resp.Asks { price, err := strconv.ParseFloat(x[0], 64) if err != nil { - log.Println(err) + log.Error(err) continue } amount, err := strconv.ParseFloat(x[1], 64) if err != nil { - log.Println(err) + log.Error(err) continue } orderbook.Asks = append(orderbook.Asks, Price{price, amount}) @@ -734,7 +734,7 @@ func (l *LocalBitcoins) SendAuthenticatedHTTPRequest(method, path string, params headers["Content-Type"] = "application/x-www-form-urlencoded" if l.Verbose { - log.Printf("Sending POST request to `%s`, path: `%s`, params: `%s`.", l.APIUrl, path, encoded) + log.Debugf("Sending POST request to `%s`, path: `%s`, params: `%s`.", l.APIUrl, path, encoded) } if method == "GET" && len(encoded) > 0 { diff --git a/exchanges/localbitcoins/localbitcoins_wrapper.go b/exchanges/localbitcoins/localbitcoins_wrapper.go index 2f9032b9..3a6054a7 100644 --- a/exchanges/localbitcoins/localbitcoins_wrapper.go +++ b/exchanges/localbitcoins/localbitcoins_wrapper.go @@ -3,16 +3,16 @@ package localbitcoins import ( "errors" "fmt" - "log" "math" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the LocalBitcoins go routine @@ -27,13 +27,13 @@ func (l *LocalBitcoins) Start(wg *sync.WaitGroup) { // Run implements the LocalBitcoins wrapper func (l *LocalBitcoins) Run() { if l.Verbose { - log.Printf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) + log.Debugf("%s polling delay: %ds.\n", l.GetName(), l.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", l.GetName(), len(l.EnabledPairs), l.EnabledPairs) } currencies, err := l.GetTradableCurrencies() if err != nil { - log.Printf("%s failed to obtain available tradable currencies. Err: %s", l.Name, err) + log.Errorf("%s failed to obtain available tradable currencies. Err: %s", l.Name, err) return } @@ -44,7 +44,7 @@ func (l *LocalBitcoins) Run() { err = l.UpdateCurrencies(pairs, false, false) if err != nil { - log.Printf("%s failed to update available currencies. Err %s", l.Name, err) + log.Errorf("%s failed to update available currencies. Err %s", l.Name, err) } } diff --git a/exchanges/okcoin/okcoin.go b/exchanges/okcoin/okcoin.go index 8cf0fe72..83efd09d 100644 --- a/exchanges/okcoin/okcoin.go +++ b/exchanges/okcoin/okcoin.go @@ -3,7 +3,6 @@ package okcoin import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -14,9 +13,10 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -811,7 +811,7 @@ func (o *OKCoin) GetFuturesUserInfo() { err := o.SendAuthenticatedHTTPRequest(okcoinFuturesUserInfo, url.Values{}, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -823,7 +823,7 @@ func (o *OKCoin) GetFuturesPosition(symbol, contractType string) { err := o.SendAuthenticatedHTTPRequest(okcoinFuturesPosition, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -841,7 +841,7 @@ func (o *OKCoin) FuturesTrade(amount, price float64, matchPrice, leverage int64, err := o.SendAuthenticatedHTTPRequest(okcoinFuturesTrade, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -856,7 +856,7 @@ func (o *OKCoin) FuturesBatchTrade(orderData, symbol, contractType string, lever err := o.SendAuthenticatedHTTPRequest(okcoinFuturesTradeBatch, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -870,7 +870,7 @@ func (o *OKCoin) CancelFuturesOrder(orderID int64, symbol, contractType string) err := o.SendAuthenticatedHTTPRequest(okcoinFuturesCancel, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -887,7 +887,7 @@ func (o *OKCoin) GetFuturesOrderInfo(orderID, status, currentPage, pageLength in err := o.SendAuthenticatedHTTPRequest(okcoinFuturesOrderInfo, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -901,7 +901,7 @@ func (o *OKCoin) GetFutureOrdersInfo(orderID int64, contractType, symbol string) err := o.SendAuthenticatedHTTPRequest(okcoinFuturesOrdersInfo, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -912,7 +912,7 @@ func (o *OKCoin) GetFuturesUserInfo4Fix() { err := o.SendAuthenticatedHTTPRequest(okcoinFuturesUserInfo4Fix, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -926,7 +926,7 @@ func (o *OKCoin) GetFuturesUserPosition4Fix(symbol, contractType string) { err := o.SendAuthenticatedHTTPRequest(okcoinFuturesUserInfo4Fix, v, nil) if err != nil { - log.Println(err) + log.Error(err) } } @@ -949,7 +949,7 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values, resul path := o.APIUrl + method if o.Verbose { - log.Printf("Sending POST request to %s with params %s\n", path, encoded) + log.Debugf("Sending POST request to %s with params %s\n", path, encoded) } headers := make(map[string]string) diff --git a/exchanges/okcoin/okcoin_websocket.go b/exchanges/okcoin/okcoin_websocket.go index 536db691..c408919f 100644 --- a/exchanges/okcoin/okcoin_websocket.go +++ b/exchanges/okcoin/okcoin_websocket.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/http" "net/url" "strconv" @@ -13,7 +12,8 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -132,11 +132,11 @@ func (o *OKCoin) WsHandleData() { var init []WsResponse err := common.JSONDecode(resp.Raw, &init) if err != nil { - log.Fatal(err) + log.Error(err) } if init[0].ErrorCode != "" { - log.Fatal(o.WebsocketErrors[init[0].ErrorCode]) + log.Error(o.WebsocketErrors[init[0].ErrorCode]) } if init[0].Success { @@ -166,7 +166,7 @@ func (o *OKCoin) WsHandleData() { err = common.JSONDecode(init[0].Data, &ticker) if err != nil { - log.Fatal(err) + log.Error(err) } @@ -187,7 +187,7 @@ func (o *OKCoin) WsHandleData() { err = common.JSONDecode(init[0].Data, &orderbook) if err != nil { - log.Fatal(err) + log.Error(err) } o.Websocket.DataHandler <- exchange.WebsocketOrderbookUpdate{ @@ -201,7 +201,7 @@ func (o *OKCoin) WsHandleData() { err = common.JSONDecode(init[0].Data, &klineData) if err != nil { - log.Fatal(err) + log.Error(err) } var klines []WsKlines @@ -237,7 +237,7 @@ func (o *OKCoin) WsHandleData() { var dealsData [][]interface{} err = common.JSONDecode(init[0].Data, &dealsData) if err != nil { - log.Fatal(err) + log.Error(err) } var deals []WsDeals diff --git a/exchanges/okcoin/okcoin_wrapper.go b/exchanges/okcoin/okcoin_wrapper.go index 20a27c30..33171e0b 100644 --- a/exchanges/okcoin/okcoin_wrapper.go +++ b/exchanges/okcoin/okcoin_wrapper.go @@ -3,15 +3,15 @@ package okcoin import ( "errors" "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKCoin go routine @@ -26,9 +26,9 @@ func (o *OKCoin) Start(wg *sync.WaitGroup) { // Run implements the OKCoin wrapper func (o *OKCoin) Run() { if o.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", o.GetName(), common.IsEnabled(o.Websocket.IsEnabled()), o.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", o.GetName(), o.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", o.GetName(), len(o.EnabledPairs), o.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", o.GetName(), common.IsEnabled(o.Websocket.IsEnabled()), o.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", o.GetName(), o.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", o.GetName(), len(o.EnabledPairs), o.EnabledPairs) } if o.APIUrl == okcoinAPIURL { @@ -40,7 +40,7 @@ func (o *OKCoin) Run() { prods, err := o.GetSpotInstruments() if err != nil { - log.Printf("OKEX failed to obtain available spot instruments. Err: %d", err) + log.Errorf("OKEX failed to obtain available spot instruments. Err: %d", err) } else { var pairs []string for x := range prods { @@ -49,17 +49,17 @@ func (o *OKCoin) Run() { err = o.UpdateCurrencies(pairs, false, forceUpgrade) if err != nil { - log.Printf("OKEX failed to update available currencies. Err: %s", err) + log.Errorf("OKEX failed to update available currencies. Err: %s", err) } } if forceUpgrade { enabledPairs := []string{"btc_usd"} - log.Println("WARNING: Available pairs for OKCoin International reset due to config upgrade, please enable the pairs you would like again.") + log.Warn("Available pairs for OKCoin International reset due to config upgrade, please enable the pairs you would like again.") err := o.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s failed to update currencies. Err: %s", o.Name, err) + log.Errorf("%s failed to update currencies. Err: %s", o.Name, err) } } } diff --git a/exchanges/okex/okex.go b/exchanges/okex/okex.go index 06b2e01d..03d002da 100644 --- a/exchanges/okex/okex.go +++ b/exchanges/okex/okex.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/url" "reflect" "strconv" @@ -18,6 +17,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -944,7 +944,7 @@ func (o *OKEX) SendAuthenticatedHTTPRequest(method string, values url.Values, re path := o.APIUrl + apiVersion + method if o.Verbose { - log.Printf("Sending POST request to %s with params %s\n", path, encoded) + log.Debugf("Sending POST request to %s with params %s\n", path, encoded) } headers := make(map[string]string) diff --git a/exchanges/okex/okex_websocket.go b/exchanges/okex/okex_websocket.go index 62e00198..df44ef47 100644 --- a/exchanges/okex/okex_websocket.go +++ b/exchanges/okex/okex_websocket.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io/ioutil" - "log" "net/http" "net/url" "strconv" @@ -16,7 +15,8 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -203,7 +203,8 @@ func (o *OKEX) WsHandleData() { if strings.Contains(string(resp.Raw), "pong") { continue } else { - log.Fatal("okex.go error -", err) + log.Error(err) + return } } @@ -212,7 +213,7 @@ func (o *OKEX) WsHandleData() { if common.StringContains(string(resp.Raw), "error_msg") { err = common.JSONDecode(resp.Raw, &errResponse) if err != nil { - log.Fatal(err) + log.Error(err) } o.Websocket.DataHandler <- fmt.Errorf("okex.go error - %s resp: %s ", errResponse.ErrorMsg, @@ -233,7 +234,8 @@ func (o *OKEX) WsHandleData() { err = common.JSONDecode(multiStreamData.Data, &ticker) if err != nil { - log.Fatal("OKEX Ticker Decode Error:", err) + log.Errorf("OKEX Ticker Decode Error: %s", err) + return } o.Websocket.DataHandler <- exchange.TickerData{ @@ -247,7 +249,8 @@ func (o *OKEX) WsHandleData() { err = common.JSONDecode(multiStreamData.Data, &deals) if err != nil { - log.Fatal("OKEX Deals Decode Error:", err) + log.Errorf("OKEX Deals Decode Error: %s", err) + return } for _, trade := range deals { @@ -271,7 +274,8 @@ func (o *OKEX) WsHandleData() { err := common.JSONDecode(multiStreamData.Data, &klines) if err != nil { - log.Fatal("OKEX Klines Decode Error:", err) + log.Errorf("OKEX Klines Decode Error: %s", err) + return } for _, kline := range klines { @@ -300,7 +304,8 @@ func (o *OKEX) WsHandleData() { err := common.JSONDecode(multiStreamData.Data, &depth) if err != nil { - log.Fatal("OKEX Depth Decode Error:", err) + log.Errorf("OKEX Depth Decode Error: %s", err) + return } o.Websocket.DataHandler <- exchange.WebsocketOrderbookUpdate{ diff --git a/exchanges/okex/okex_wrapper.go b/exchanges/okex/okex_wrapper.go index 76ce66e6..e203cf26 100644 --- a/exchanges/okex/okex_wrapper.go +++ b/exchanges/okex/okex_wrapper.go @@ -3,7 +3,6 @@ package okex import ( "errors" "fmt" - "log" "strconv" "sync" @@ -12,6 +11,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKEX go routine @@ -26,14 +26,14 @@ func (o *OKEX) Start(wg *sync.WaitGroup) { // Run implements the OKEX wrapper func (o *OKEX) Run() { if o.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", o.GetName(), common.IsEnabled(o.Websocket.IsEnabled()), o.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", o.GetName(), o.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", o.GetName(), len(o.EnabledPairs), o.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", o.GetName(), common.IsEnabled(o.Websocket.IsEnabled()), o.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", o.GetName(), o.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", o.GetName(), len(o.EnabledPairs), o.EnabledPairs) } prods, err := o.GetSpotInstruments() if err != nil { - log.Printf("OKEX failed to obtain available spot instruments. Err: %d", err) + log.Errorf("OKEX failed to obtain available spot instruments. Err: %d", err) return } @@ -44,7 +44,8 @@ func (o *OKEX) Run() { err = o.UpdateCurrencies(pairs, false, false) if err != nil { - log.Printf("OKEX failed to update available currencies. Err: %s", err) + log.Errorf("OKEX failed to update available currencies. Err: %s", err) + return } } diff --git a/exchanges/poloniex/poloniex.go b/exchanges/poloniex/poloniex.go index 786b7bbb..32e43e9a 100644 --- a/exchanges/poloniex/poloniex.go +++ b/exchanges/poloniex/poloniex.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "net/url" "strconv" "time" @@ -12,9 +11,10 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -168,7 +168,6 @@ func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (OrderbookAll, e return oba, err } if len(resp.Error) != 0 { - log.Println(resp.Error) return oba, fmt.Errorf("Poloniex GetOrderbook() error: %s", resp.Error) } ob := Orderbook{} diff --git a/exchanges/poloniex/poloniex_websocket.go b/exchanges/poloniex/poloniex_websocket.go index e83af566..66011bbc 100644 --- a/exchanges/poloniex/poloniex_websocket.go +++ b/exchanges/poloniex/poloniex_websocket.go @@ -3,7 +3,6 @@ package poloniex import ( "errors" "fmt" - "log" "net/http" "net/url" "strconv" @@ -12,8 +11,9 @@ import ( "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -132,7 +132,7 @@ func (p *Poloniex) WsHandleData() { var check []interface{} err := common.JSONDecode(resp.Raw, &check) if err != nil { - log.Fatal("poloniex_websocket.go - ", err) + log.Errorf("poloniex websocket decode error - %s", err) } switch len(check) { @@ -176,7 +176,7 @@ func (p *Poloniex) WsHandleData() { err := p.WsProcessOrderbookUpdate(datalevel2, CurrencyPairID[int64(check[0].(float64))]) if err != nil { - log.Fatal(err) + log.Error(err) } p.Websocket.DataHandler <- exchange.WebsocketOrderbookUpdate{ @@ -189,12 +189,12 @@ func (p *Poloniex) WsHandleData() { datalevel3 := datalevel2[1].(map[string]interface{}) currencyPair, ok := datalevel3["currencyPair"].(string) if !ok { - log.Fatal("poloniex.go error - could not find currency pair in map") + log.Error("poloniex.go error - could not find currency pair in map") } orderbookData, ok := datalevel3["orderBook"].([]interface{}) if !ok { - log.Fatal("poloniex.go error - could not find orderbook data in map") + log.Error("poloniex.go error - could not find orderbook data in map") } err := p.WsProcessOrderbookSnapshot(orderbookData, currencyPair) diff --git a/exchanges/poloniex/poloniex_wrapper.go b/exchanges/poloniex/poloniex_wrapper.go index 727a31f8..c3e9680a 100644 --- a/exchanges/poloniex/poloniex_wrapper.go +++ b/exchanges/poloniex/poloniex_wrapper.go @@ -2,15 +2,15 @@ package poloniex import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the Poloniex go routine @@ -25,24 +25,24 @@ func (p *Poloniex) Start(wg *sync.WaitGroup) { // Run implements the Poloniex wrapper func (p *Poloniex) Run() { if p.Verbose { - log.Printf("%s Websocket: %s (url: %s).\n", p.GetName(), common.IsEnabled(p.Websocket.IsEnabled()), poloniexWebsocketAddress) - log.Printf("%s polling delay: %ds.\n", p.GetName(), p.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", p.GetName(), len(p.EnabledPairs), p.EnabledPairs) + log.Debugf("%s Websocket: %s (url: %s).\n", p.GetName(), common.IsEnabled(p.Websocket.IsEnabled()), poloniexWebsocketAddress) + log.Debugf("%s polling delay: %ds.\n", p.GetName(), p.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", p.GetName(), len(p.EnabledPairs), p.EnabledPairs) } exchangeCurrencies, err := p.GetExchangeCurrencies() if err != nil { - log.Printf("%s Failed to get available symbols.\n", p.GetName()) + log.Errorf("%s Failed to get available symbols.\n", p.GetName()) } else { forceUpdate := false if common.StringDataCompare(p.AvailablePairs, "BTC_USDT") { - log.Printf("%s contains invalid pair, forcing upgrade of available currencies.\n", + log.Warnf("%s contains invalid pair, forcing upgrade of available currencies.\n", p.GetName()) forceUpdate = true } err = p.UpdateCurrencies(exchangeCurrencies, false, forceUpdate) if err != nil { - log.Printf("%s Failed to update available currencies %s.\n", p.GetName(), err) + log.Errorf("%s Failed to update available currencies %s.\n", p.GetName(), err) } } } diff --git a/exchanges/request/request.go b/exchanges/request/request.go index ed1f5613..3fdac63d 100644 --- a/exchanges/request/request.go +++ b/exchanges/request/request.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "io/ioutil" - "log" "net" "net/http" "net/url" @@ -13,6 +12,7 @@ import ( "time" "github.com/thrasher-/gocryptotrader/common" + log "github.com/thrasher-/gocryptotrader/logger" ) var supportedMethods = []string{"GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS", "CONNECT"} @@ -257,11 +257,11 @@ func (r *Requester) checkRequest(method, path string, body io.Reader, headers ma // DoRequest performs a HTTP/HTTPS request with the supplied params func (r *Requester) DoRequest(req *http.Request, method, path string, headers map[string]string, body io.Reader, result interface{}, authRequest, verbose bool) error { if verbose { - log.Printf("%s exchange request path: %s requires rate limiter: %v", r.Name, path, r.RequiresRateLimiter()) + log.Debugf("%s exchange request path: %s requires rate limiter: %v", r.Name, path, r.RequiresRateLimiter()) for k, d := range headers { - log.Printf("%s exchange request header [%s]: %s", r.Name, k, d) + log.Debugf("%s exchange request header [%s]: %s", r.Name, k, d) } - log.Println(body) + log.Debug(body) } var timeoutError error @@ -270,7 +270,7 @@ func (r *Requester) DoRequest(req *http.Request, method, path string, headers ma if err != nil { if timeoutErr, ok := err.(net.Error); ok && timeoutErr.Timeout() { if verbose { - log.Printf("%s request has timed-out retrying request, count %d", + log.Errorf("%s request has timed-out retrying request, count %d", r.Name, i) } @@ -308,8 +308,8 @@ func (r *Requester) DoRequest(req *http.Request, method, path string, headers ma resp.Body.Close() if verbose { - log.Printf("HTTP status: %s, Code: %v", resp.Status, resp.StatusCode) - log.Printf("%s exchange raw response: %s", r.Name, string(contents)) + log.Debugf("HTTP status: %s, Code: %v", resp.Status, resp.StatusCode) + log.Debugf("%s exchange raw response: %s", r.Name, string(contents)) } if result != nil { @@ -337,7 +337,7 @@ func (r *Requester) worker() { limit := r.GetRateLimit(x.AuthRequest) diff := limit.GetDuration() - time.Since(r.Cycle) if x.Verbose { - log.Printf("%s request. Rate limited! Sleeping for %v", r.Name, diff) + log.Debugf("%s request. Rate limited! Sleeping for %v", r.Name, diff) } time.Sleep(diff) @@ -346,7 +346,7 @@ func (r *Requester) worker() { r.IncrementRequests(x.AuthRequest) if x.Verbose { - log.Printf("%s request. No longer rate limited! Doing request", r.Name) + log.Debugf("%s request. No longer rate limited! Doing request", r.Name) } err := r.DoRequest(x.Request, x.Method, x.Path, x.Headers, x.Body, x.Result, x.AuthRequest, x.Verbose) @@ -412,17 +412,17 @@ func (r *Requester) SendPayload(method, path string, headers map[string]string, } if verbose { - log.Printf("%s request. Attaching new job.", r.Name) + log.Debugf("%s request. Attaching new job.", r.Name) } r.Jobs <- newJob if verbose { - log.Printf("%s request. Waiting for job to complete.", r.Name) + log.Debugf("%s request. Waiting for job to complete.", r.Name) } resp := <-newJob.JobResult if verbose { - log.Printf("%s request. Job complete.", r.Name) + log.Debugf("%s request. Job complete.", r.Name) } return resp.Error } diff --git a/exchanges/wex/wex.go b/exchanges/wex/wex.go index adb7a3f7..26c323a5 100644 --- a/exchanges/wex/wex.go +++ b/exchanges/wex/wex.go @@ -3,7 +3,6 @@ package wex import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -15,6 +14,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -377,7 +377,7 @@ func (w *WEX) SendAuthenticatedHTTPRequest(method string, values url.Values, res hmac := common.GetHMAC(common.HashSHA512, []byte(encoded), []byte(w.APISecret)) if w.Verbose { - log.Printf("Sending POST request to %s calling method %s with params %s\n", + log.Debugf("Sending POST request to %s calling method %s with params %s\n", w.APIUrlSecondary, method, encoded) diff --git a/exchanges/wex/wex_wrapper.go b/exchanges/wex/wex_wrapper.go index 3df63ef9..e5da7acf 100644 --- a/exchanges/wex/wex_wrapper.go +++ b/exchanges/wex/wex_wrapper.go @@ -2,7 +2,6 @@ package wex import ( "fmt" - "log" "strconv" "sync" @@ -11,6 +10,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the WEX go routine @@ -25,14 +25,14 @@ func (w *WEX) Start(wg *sync.WaitGroup) { // Run implements the WEX wrapper func (w *WEX) Run() { if w.Verbose { - log.Printf("%s Websocket: %s.", w.GetName(), common.IsEnabled(w.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", w.GetName(), w.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", w.GetName(), len(w.EnabledPairs), w.EnabledPairs) + log.Debugf("%s Websocket: %s.", w.GetName(), common.IsEnabled(w.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", w.GetName(), w.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", w.GetName(), len(w.EnabledPairs), w.EnabledPairs) } exchangeProducts, err := w.GetTradablePairs() if err != nil { - log.Printf("%s Failed to get available symbols.\n", w.GetName()) + log.Errorf("%s Failed to get available symbols.\n", w.GetName()) } else { forceUpgrade := false if !common.StringDataContains(w.EnabledPairs, "_") || !common.StringDataContains(w.AvailablePairs, "_") { @@ -41,16 +41,16 @@ func (w *WEX) Run() { if forceUpgrade { enabledPairs := []string{"BTC_USD", "LTC_USD", "LTC_BTC", "ETH_USD"} - log.Println("WARNING: Enabled pairs for WEX reset due to config upgrade, please enable the ones you would like again.") + log.Warn("Enabled pairs for WEX reset due to config upgrade, please enable the ones you would like again.") err = w.UpdateCurrencies(enabledPairs, true, true) if err != nil { - log.Printf("%s Failed to get config.\n", w.GetName()) + log.Errorf("%s Failed to get config.\n", w.GetName()) } } err = w.UpdateCurrencies(exchangeProducts, false, forceUpgrade) if err != nil { - log.Printf("%s Failed to get config.\n", w.GetName()) + log.Errorf("%s Failed to get config.\n", w.GetName()) } } } diff --git a/exchanges/yobit/yobit.go b/exchanges/yobit/yobit.go index 3ae3ae2d..a70ab4eb 100644 --- a/exchanges/yobit/yobit.go +++ b/exchanges/yobit/yobit.go @@ -3,7 +3,6 @@ package yobit import ( "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -12,9 +11,10 @@ import ( "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency/symbol" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -345,7 +345,7 @@ func (y *Yobit) SendAuthenticatedHTTPRequest(path string, params url.Values, res hmac := common.GetHMAC(common.HashSHA512, []byte(encoded), []byte(y.APISecret)) if y.Verbose { - log.Printf("Sending POST request to %s calling path %s with params %s\n", apiPrivateURL, path, encoded) + log.Debugf("Sending POST request to %s calling path %s with params %s\n", apiPrivateURL, path, encoded) } headers := make(map[string]string) diff --git a/exchanges/yobit/yobit_wrapper.go b/exchanges/yobit/yobit_wrapper.go index b23f8710..fc023275 100644 --- a/exchanges/yobit/yobit_wrapper.go +++ b/exchanges/yobit/yobit_wrapper.go @@ -3,7 +3,6 @@ package yobit import ( "errors" "fmt" - "log" "strconv" "sync" @@ -12,6 +11,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the WEX go routine @@ -26,9 +26,9 @@ func (y *Yobit) Start(wg *sync.WaitGroup) { // Run implements the Yobit wrapper func (y *Yobit) Run() { if y.Verbose { - log.Printf("%s Websocket: %s.", y.GetName(), common.IsEnabled(y.Websocket.IsEnabled())) - log.Printf("%s polling delay: %ds.\n", y.GetName(), y.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", y.GetName(), len(y.EnabledPairs), y.EnabledPairs) + log.Debugf("%s Websocket: %s.", y.GetName(), common.IsEnabled(y.Websocket.IsEnabled())) + log.Debugf("%s polling delay: %ds.\n", y.GetName(), y.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", y.GetName(), len(y.EnabledPairs), y.EnabledPairs) } } diff --git a/exchanges/zb/zb.go b/exchanges/zb/zb.go index db84d80d..a7ca43e1 100644 --- a/exchanges/zb/zb.go +++ b/exchanges/zb/zb.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/url" "strconv" "strings" @@ -15,6 +14,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/request" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( diff --git a/exchanges/zb/zb_wrapper.go b/exchanges/zb/zb_wrapper.go index af3a36a5..ff9548fb 100644 --- a/exchanges/zb/zb_wrapper.go +++ b/exchanges/zb/zb_wrapper.go @@ -2,15 +2,15 @@ package zb import ( "fmt" - "log" "strconv" "sync" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency/pair" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the OKEX go routine @@ -25,14 +25,14 @@ func (z *ZB) Start(wg *sync.WaitGroup) { // Run implements the OKEX wrapper func (z *ZB) Run() { if z.Verbose { - log.Printf("%s Websocket: %s. (url: %s).\n", z.GetName(), common.IsEnabled(z.Websocket.IsEnabled()), z.WebsocketURL) - log.Printf("%s polling delay: %ds.\n", z.GetName(), z.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", z.GetName(), len(z.EnabledPairs), z.EnabledPairs) + log.Debugf("%s Websocket: %s. (url: %s).\n", z.GetName(), common.IsEnabled(z.Websocket.IsEnabled()), z.WebsocketURL) + log.Debugf("%s polling delay: %ds.\n", z.GetName(), z.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", z.GetName(), len(z.EnabledPairs), z.EnabledPairs) } markets, err := z.GetMarkets() if err != nil { - log.Printf("%s Unable to fetch symbols.\n", z.GetName()) + log.Errorf("%s Unable to fetch symbols.\n", z.GetName()) } else { var currencies []string for x := range markets { @@ -41,7 +41,7 @@ func (z *ZB) Run() { err = z.UpdateCurrencies(currencies, false, false) if err != nil { - log.Printf("%s Failed to update available currencies.\n", z.GetName()) + log.Errorf("%s Failed to update available currencies.\n", z.GetName()) } } } diff --git a/helpers.go b/helpers.go index d577396d..0b6b8776 100644 --- a/helpers.go +++ b/helpers.go @@ -3,11 +3,7 @@ package main import ( "errors" "fmt" - "io" - "log" - "os" - "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/currency/pair" "github.com/thrasher-/gocryptotrader/currency/translation" @@ -15,39 +11,10 @@ import ( "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/stats" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" "github.com/thrasher-/gocryptotrader/portfolio" ) -const ( - logFile = "debug.log" -) - -var ( - logFileHandle *os.File -) - -// InitLogFile initialises the log file -func InitLogFile(lFile string) error { - if logFileHandle != nil { - return nil - } - - var err error - logFileHandle, err = os.OpenFile(lFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - return err - } - - wrt := io.MultiWriter(os.Stdout, logFileHandle) - log.SetOutput(wrt) - return nil -} - -// GetLogFile returns the debug.log file -func GetLogFile(dir string) string { - return dir + common.GetOSPathSlash() + logFile -} - // GetAllAvailablePairs returns a list of all available pairs on either enabled // or disabled exchanges func GetAllAvailablePairs(enabledExchangesOnly bool) []pair.CurrencyPair { @@ -369,7 +336,7 @@ func SeedExchangeAccountInfo(data []exchange.AccountInfo) { if total <= 0 { continue } - log.Printf("Portfolio: Adding new exchange address: %s, %s, %f, %s\n", + log.Debugf("Portfolio: Adding new exchange address: %s, %s, %f, %s\n", exchangeName, currencyName, total, portfolio.PortfolioAddressExchange) port.Addresses = append( port.Addresses, @@ -378,7 +345,7 @@ func SeedExchangeAccountInfo(data []exchange.AccountInfo) { ) } else { if total <= 0 { - log.Printf("Portfolio: Removing %s %s entry.\n", exchangeName, + log.Debugf("Portfolio: Removing %s %s entry.\n", exchangeName, currencyName) port.RemoveExchangeAddress(exchangeName, currencyName) } else { @@ -387,7 +354,7 @@ func SeedExchangeAccountInfo(data []exchange.AccountInfo) { continue } if balance != total { - log.Printf("Portfolio: Updating %s %s entry with balance %f.\n", + log.Debugf("Portfolio: Updating %s %s entry with balance %f.\n", exchangeName, currencyName, total) port.UpdateExchangeAddressBalance(exchangeName, currencyName, total) } diff --git a/helpers_test.go b/helpers_test.go index c9b85437..5f1261d4 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -344,16 +344,16 @@ func TestGetExchangeHighestPriceByCurrencyPair(t *testing.T) { stats.Add("Bitstamp", p, ticker.Spot, 1337, 10000) exchange, err := GetExchangeHighestPriceByCurrencyPair(p, ticker.Spot) if err != nil { - log.Fatal(err) + t.Error(err) } if exchange != "Bitstamp" { - log.Fatal("Unexpected result") + t.Error("Unexpected result") } _, err = GetExchangeHighestPriceByCurrencyPair(pair.NewCurrencyPair("BTC", "AUD"), ticker.Spot) if err == nil { - log.Fatal("Unexpected reuslt") + t.Error("Unexpected result") } } @@ -365,15 +365,15 @@ func TestGetExchangeLowestPriceByCurrencyPair(t *testing.T) { stats.Add("Bitstamp", p, ticker.Spot, 1337, 10000) exchange, err := GetExchangeLowestPriceByCurrencyPair(p, ticker.Spot) if err != nil { - log.Fatal(err) + t.Error(err) } if exchange != "Bitfinex" { - log.Fatal("Unexpected result") + t.Error("Unexpected result") } _, err = GetExchangeLowestPriceByCurrencyPair(pair.NewCurrencyPair("BTC", "AUD"), ticker.Spot) if err == nil { - log.Fatal("Unexpected reuslt") + t.Error("Unexpected reuslt") } } diff --git a/logger/logger.go b/logger/logger.go new file mode 100644 index 00000000..42d753ca --- /dev/null +++ b/logger/logger.go @@ -0,0 +1,120 @@ +package logger + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "os" + "path" + "runtime" + "time" +) + +func init() { + setDefaultOutputs() +} + +// SetupLogger configure logger instance with user provided settings +func SetupLogger() (err error) { + if *Logger.Enabled { + err = setupOutputs() + if err != nil { + return + } + logLevel() + if Logger.ColourOutput { + colourOutput() + } + } else { + clearAllLoggers() + } + return +} + +// setDefaultOutputs() this setups defaults used by the logger +// This allows it to be used without any user configuration +func setDefaultOutputs() { + debugLogger = log.New(os.Stdout, + "[DEBUG]: ", + log.Ldate|log.Ltime) + + infoLogger = log.New(os.Stdout, + "[INFO]: ", + log.Ldate|log.Ltime) + + warnLogger = log.New(os.Stdout, + "[WARN]: ", + log.Ldate|log.Ltime) + + errorLogger = log.New(os.Stdout, + "[ERROR]: ", + log.Ldate|log.Ltime) + + fatalLogger = log.New(os.Stdout, + "[FATAL]: ", + log.Ldate|log.Ltime) +} + +// colorOutput() sets the prefix of each log type to matching colour +// TODO: add windows support +func colourOutput() { + if runtime.GOOS != "windows" { + debugLogger.SetPrefix("\033[34m[DEBUG]\033[0m: ") + infoLogger.SetPrefix("\033[32m[INFO]\033[0m: ") + warnLogger.SetPrefix("\033[33m[WARN]\033[0m: ") + errorLogger.SetPrefix("\033[31m[ERROR]\033[0m: ") + fatalLogger.SetPrefix("\033[31m[FATAL]\033[0m: ") + } +} + +// clearAllLoggers() sets all logger flags to 0 and outputs to Discard +func clearAllLoggers() { + debugLogger.SetFlags(0) + infoLogger.SetFlags(0) + warnLogger.SetFlags(0) + errorLogger.SetFlags(0) + fatalLogger.SetFlags(0) + + debugLogger.SetOutput(ioutil.Discard) + infoLogger.SetOutput(ioutil.Discard) + warnLogger.SetOutput(ioutil.Discard) + errorLogger.SetOutput(ioutil.Discard) + fatalLogger.SetOutput(ioutil.Discard) +} + +// setupOutputs() sets up the io.writer to use for logging +// TODO: Fix up rotating at the moment its a quick job +func setupOutputs() (err error) { + if len(Logger.File) > 0 { + logFile := path.Join(LogPath, Logger.File) + if Logger.Rotate { + if _, err = os.Stat(logFile); !os.IsNotExist(err) { + currentTime := time.Now() + newName := currentTime.Format("2006-01-02 15-04-05") + newFile := newName + " " + Logger.File + err = os.Rename(logFile, path.Join(LogPath, newFile)) + if err != nil { + err = fmt.Errorf("Failed to rename old log file %s", err) + return + } + } + } + logFileHandle, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + return + } + logOutput = io.MultiWriter(os.Stdout, logFileHandle) + } else { + logOutput = os.Stdout + } + return +} + +// CloseLogFile close the handler for any open log files +func CloseLogFile() (err error) { + if logFileHandle != nil { + err = logFileHandle.Close() + } + return +} diff --git a/logger/logger_levels.go b/logger/logger_levels.go new file mode 100644 index 00000000..ce7f2c8c --- /dev/null +++ b/logger/logger_levels.go @@ -0,0 +1,33 @@ +package logger + +import ( + "log" + "strings" +) + +func logLevel() { + clearAllLoggers() + enabledLevels := strings.Split(Logger.Level, "|") + + for x := range enabledLevels { + switch level := enabledLevels[x]; level { + case "DEBUG": + debugLogger.SetOutput(logOutput) + debugLogger.SetFlags(log.Ldate | log.Ltime) + case "INFO": + infoLogger.SetOutput(logOutput) + infoLogger.SetFlags(log.Ldate | log.Ltime) + case "WARN": + warnLogger.SetOutput(logOutput) + warnLogger.SetFlags(log.Ldate | log.Ltime) + case "ERROR": + errorLogger.SetOutput(logOutput) + errorLogger.SetFlags(log.Ldate | log.Ltime) + case "FATAL": + fatalLogger.SetOutput(logOutput) + fatalLogger.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) + default: + continue + } + } +} diff --git a/logger/logger_test.go b/logger/logger_test.go new file mode 100644 index 00000000..79ba0812 --- /dev/null +++ b/logger/logger_test.go @@ -0,0 +1,75 @@ +package logger + +import ( + "os" + "path" + "testing" +) + +var ( + trueptr = func(b bool) *bool { return &b }(true) + falseptr = func(b bool) *bool { return &b }(false) +) + +func TestCloseLogFile(t *testing.T) { + Logger = &Logging{ + Enabled: trueptr, + Level: "DEBUG", + ColourOutput: false, + File: "", + Rotate: false, + } + SetupLogger() + err := CloseLogFile() + if err != nil { + t.Fatalf("CloseLogFile failed with %v", err) + } + os.Remove(path.Join(LogPath, Logger.File)) +} + +func TestSetupOutputsValidPath(t *testing.T) { + Logger.Enabled = trueptr + Logger.File = "debug.txt" + LogPath = "../testdata/" + err := setupOutputs() + if err != nil { + t.Fatalf("SetupOutputs failed expected nil got %v", err) + } + os.Remove(path.Join(LogPath, Logger.File)) +} + +func TestSetupOutputsInValidPath(t *testing.T) { + Logger.Enabled = trueptr + Logger.File = "debug.txt" + LogPath = "../testdataa/" + err := setupOutputs() + if err != nil { + if !os.IsNotExist(err) { + t.Fatalf("SetupOutputs failed expected %v got %v", os.ErrNotExist, err) + } + } + os.Remove(path.Join(LogPath, Logger.File)) +} + +func BenchmarkDebugf(b *testing.B) { + Logger = &Logging{ + Enabled: trueptr, + Level: "DEBUG", + ColourOutput: false, + File: "", + Rotate: false, + } + SetupLogger() + b.ResetTimer() + for n := 0; n < b.N; n++ { + Debugf("This is a debug benchmark %d", n) + } +} + +func BenchmarkDebugfLoggerDisabled(b *testing.B) { + clearAllLoggers() + b.ResetTimer() + for n := 0; n < b.N; n++ { + Debugf("this is a debug benchmark") + } +} diff --git a/logger/logger_types.go b/logger/logger_types.go new file mode 100644 index 00000000..b2671694 --- /dev/null +++ b/logger/logger_types.go @@ -0,0 +1,34 @@ +package logger + +import ( + "io" + "log" + "os" +) + +// Logging struct that holds all user configurable options for the logger +type Logging struct { + Enabled *bool `json:"enabled,omitempty"` + File string `json:"file"` + ColourOutput bool `json:"colour"` + Level string `json:"level"` + Rotate bool `json:"rotate"` +} + +var ( + debugLogger *log.Logger + infoLogger *log.Logger + warnLogger *log.Logger + errorLogger *log.Logger + fatalLogger *log.Logger + + logFileHandle *os.File + + logOutput io.Writer + + // LogPath location to store logs in + LogPath string + + // Logger create a pointer to Logging struct for holding data + Logger = &Logging{} +) diff --git a/logger/loggers.go b/logger/loggers.go new file mode 100644 index 00000000..7e6c1f4f --- /dev/null +++ b/logger/loggers.go @@ -0,0 +1,80 @@ +package logger + +import ( + "fmt" + "log" + "os" +) + +// Info handler takes any input returns unformatted output to infoLogger writer +func Info(v ...interface{}) { + infoLogger.Print(v...) +} + +// Infof handler takes any input infoLogger returns formatted output to infoLogger writer +func Infof(data string, v ...interface{}) { + infoLogger.Printf(data, v...) +} + +// Infoln handler takes any input infoLogger returns formatted output to infoLogger writer +func Infoln(v ...interface{}) { + infoLogger.Println(v...) +} + +// Print aliased to Standard log.Print +var Print = log.Print + +// Printf aliased to Standard log.Printf +var Printf = log.Printf + +// Println aliased to Standard log.Println +var Println = log.Println + +// Debug handler takes any input returns unformatted output to infoLogger writer +func Debug(v ...interface{}) { + debugLogger.Print(v...) +} + +// Debugf handler takes any input infoLogger returns formatted output to infoLogger writer +func Debugf(data string, v ...interface{}) { + debugLogger.Printf(data, v...) +} + +// Debugln handler takes any input infoLogger returns formatted output to infoLogger writer +func Debugln(v ...interface{}) { + debugLogger.Println(v...) +} + +// Warn handler takes any input returns unformatted output to warnLogger writer +func Warn(v ...interface{}) { + warnLogger.Print(v...) +} + +// Warnf handler takes any input returns unformatted output to warnLogger writer +func Warnf(data string, v ...interface{}) { + warnLogger.Printf(data, v...) +} + +// Error handler takes any input returns unformatted output to errorLogger writer +func Error(v ...interface{}) { + errorLogger.Print(v...) +} + +// Errorf handler takes any input returns unformatted output to errorLogger writer +func Errorf(data string, v ...interface{}) { + errorLogger.Printf(data, v...) +} + +// Fatal handler takes any input returns unformatted output to fatalLogger writer +func Fatal(v ...interface{}) { + // Send to Output instead of Fatal to allow us to increase the output depth by 1 to make sure the correct file is displayed + fatalLogger.Output(2, fmt.Sprint(v...)) + os.Exit(1) +} + +// Fatalf handler takes any input returns unformatted output to fatalLogger writer +func Fatalf(data string, v ...interface{}) { + // Send to Output instead of Fatal to allow us to increase the output depth by 1 to make sure the correct file is displayed + fatalLogger.Output(2, fmt.Sprintf(data, v...)) + os.Exit(1) +} diff --git a/main.go b/main.go index 89afc79a..9e362165 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,6 @@ package main import ( "flag" "fmt" - "log" "net/http" "os" "os/signal" @@ -16,7 +15,8 @@ import ( "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency" "github.com/thrasher-/gocryptotrader/currency/forexprovider" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" + log "github.com/thrasher-/gocryptotrader/logger" "github.com/thrasher-/gocryptotrader/portfolio" ) @@ -31,7 +31,6 @@ type Bot struct { dryRun bool configFile string dataDir string - logFile string } const banner = ` @@ -76,7 +75,7 @@ func main() { fmt.Println(BuildVersion(false)) bot.config = &config.Cfg - log.Printf("Loading config file %s..\n", bot.configFile) + log.Debugf("Loading config file %s..\n", bot.configFile) err = bot.config.LoadConfig(bot.configFile) if err != nil { log.Fatalf("Failed to load config. Err: %s", err) @@ -86,46 +85,48 @@ func main() { if err != nil { log.Fatalf("Failed to open/create data directory: %s. Err: %s", bot.dataDir, err) } - log.Printf("Using data directory: %s.\n", bot.dataDir) + log.Debugf("Using data directory: %s.\n", bot.dataDir) - bot.logFile = GetLogFile(bot.dataDir) - err = InitLogFile(bot.logFile) + err = bot.config.CheckLoggerConfig() if err != nil { - log.Printf("Failed to create log file writer. Err: %s", err) - } else { - log.Printf("Using log file: %s.\n", bot.logFile) + log.Errorf("Failed to configure logger reason: %s", err) + } + + err = log.SetupLogger() + if err != nil { + log.Errorf("Failed to setup logger reason: %s", err) } AdjustGoMaxProcs() - log.Printf("Bot '%s' started.\n", bot.config.Name) - log.Printf("Bot dry run mode: %v.\n", common.IsEnabled(bot.dryRun)) + log.Debugf("Bot '%s' started.\n", bot.config.Name) + log.Debugf("Bot dry run mode: %v.\n", common.IsEnabled(bot.dryRun)) - log.Printf("Available Exchanges: %d. Enabled Exchanges: %d.\n", + log.Debugf("Available Exchanges: %d. Enabled Exchanges: %d.\n", len(bot.config.Exchanges), bot.config.CountEnabledExchanges()) common.HTTPClient = common.NewHTTPClientWithTimeout(bot.config.GlobalHTTPTimeout) - log.Printf("Global HTTP request timeout: %v.\n", common.HTTPClient.Timeout) + log.Debugf("Global HTTP request timeout: %v.\n", common.HTTPClient.Timeout) SetupExchanges() if len(bot.exchanges) == 0 { log.Fatalf("No exchanges were able to be loaded. Exiting") } - log.Println("Starting communication mediums..") + log.Debugf("Starting communication mediums..") bot.comms = communications.NewComm(bot.config.GetCommunicationsConfig()) bot.comms.GetEnabledCommunicationMediums() - log.Printf("Fiat display currency: %s.", bot.config.Currency.FiatDisplayCurrency) + log.Debugf("Fiat display currency: %s.", bot.config.Currency.FiatDisplayCurrency) currency.BaseCurrency = bot.config.Currency.FiatDisplayCurrency currency.FXProviders = forexprovider.StartFXService(bot.config.GetCurrencyConfig().ForexProviders) - log.Printf("Primary forex conversion provider: %s.\n", bot.config.GetPrimaryForexProvider()) + log.Debugf("Primary forex conversion provider: %s.\n", bot.config.GetPrimaryForexProvider()) err = bot.config.RetrieveConfigCurrencyPairs(true) if err != nil { log.Fatalf("Failed to retrieve config currency pairs. Error: %s", err) } - log.Println("Successfully retrieved config currencies.") - log.Println("Fetching currency data from forex provider..") + log.Debugf("Successfully retrieved config currencies.") + log.Debugf("Fetching currency data from forex provider..") err = currency.SeedCurrencyData(common.JoinStrings(currency.FiatCurrencies, ",")) if err != nil { log.Fatalf("Unable to fetch forex data. Error: %s", err) @@ -137,7 +138,7 @@ func main() { if bot.config.Webserver.Enabled { listenAddr := bot.config.Webserver.ListenAddress - log.Printf( + log.Debugf( "HTTP Webserver support enabled. Listen URL: http://%s:%d/\n", common.ExtractHost(listenAddr), common.ExtractPort(listenAddr), ) @@ -150,11 +151,11 @@ func main() { } }() - log.Println("HTTP Webserver started successfully.") - log.Println("Starting websocket handler.") + log.Debugln("HTTP Webserver started successfully.") + log.Debugln("Starting websocket handler.") StartWebsocketHandler() } else { - log.Println("HTTP RESTful Webserver support disabled.") + log.Debugln("HTTP RESTful Webserver support disabled.") } go portfolio.StartPortfolioWatcher() @@ -169,24 +170,24 @@ func main() { // AdjustGoMaxProcs adjusts the maximum processes that the CPU can handle. func AdjustGoMaxProcs() { - log.Println("Adjusting bot runtime performance..") + log.Debugln("Adjusting bot runtime performance..") maxProcsEnv := os.Getenv("GOMAXPROCS") maxProcs := runtime.NumCPU() - log.Println("Number of CPU's detected:", maxProcs) + log.Debugln("Number of CPU's detected:", maxProcs) if maxProcsEnv != "" { - log.Println("GOMAXPROCS env =", maxProcsEnv) + log.Debugln("GOMAXPROCS env =", maxProcsEnv) env, err := strconv.Atoi(maxProcsEnv) if err != nil { - log.Println("Unable to convert GOMAXPROCS to int, using", maxProcs) + log.Debugf("Unable to convert GOMAXPROCS to int, using %d", maxProcs) } else { maxProcs = env } } if i := runtime.GOMAXPROCS(maxProcs); i != maxProcs { - log.Fatal("Go Max Procs were not set correctly.") + log.Error("Go Max Procs were not set correctly.") } - log.Println("Set GOMAXPROCS to:", maxProcs) + log.Debugln("Set GOMAXPROCS to:", maxProcs) } // HandleInterrupt monitors and captures the SIGTERM in a new goroutine then @@ -196,14 +197,14 @@ func HandleInterrupt() { signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { sig := <-c - log.Printf("Captured %v, shutdown requested.", sig) + log.Debugf("Captured %v, shutdown requested.", sig) bot.shutdown <- true }() } // Shutdown correctly shuts down bot saving configuration files func Shutdown() { - log.Println("Bot shutting down..") + log.Debugln("Bot shutting down..") if len(portfolio.Portfolio.Addresses) != 0 { bot.config.Portfolio = portfolio.Portfolio @@ -213,16 +214,14 @@ func Shutdown() { err := bot.config.SaveConfig(bot.configFile) if err != nil { - log.Println("Unable to save config.") + log.Warn("Unable to save config.") } else { - log.Println("Config file saved successfully.") + log.Debugln("Config file saved successfully.") } } - log.Println("Exiting.") + log.Debugln("Exiting.") - if logFileHandle != nil { - logFileHandle.Close() - } + log.CloseLogFile() os.Exit(0) } diff --git a/portfolio/portfolio.go b/portfolio/portfolio.go index c050d9c9..093d830d 100644 --- a/portfolio/portfolio.go +++ b/portfolio/portfolio.go @@ -3,10 +3,10 @@ package portfolio import ( "errors" "fmt" - "log" "time" "github.com/thrasher-/gocryptotrader/common" + log "github.com/thrasher-/gocryptotrader/logger" ) const ( @@ -390,7 +390,7 @@ func (p *Base) SeedPortfolio(port Base) { // StartPortfolioWatcher observes the portfolio object func StartPortfolioWatcher() { addrCount := len(Portfolio.Addresses) - log.Printf( + log.Debugf( "PortfolioWatcher started: Have %d entries in portfolio.\n", addrCount, ) for { @@ -398,7 +398,7 @@ func StartPortfolioWatcher() { for key, value := range data { success := Portfolio.UpdatePortfolio(value, key) if success { - log.Printf( + log.Debugf( "PortfolioWatcher: Successfully updated address balance for %s address(es) %s\n", key, value, ) diff --git a/restful_router.go b/restful_router.go index f6666bac..65dc937c 100644 --- a/restful_router.go +++ b/restful_router.go @@ -2,12 +2,12 @@ package main import ( "fmt" - "log" "net/http" "time" "github.com/gorilla/mux" - "github.com/thrasher-/gocryptotrader/exchanges" + exchange "github.com/thrasher-/gocryptotrader/exchanges" + log "github.com/thrasher-/gocryptotrader/logger" ) // RESTLogger logs the requests internally @@ -17,7 +17,7 @@ func RESTLogger(inner http.Handler, name string) http.Handler { inner.ServeHTTP(w, r) - log.Printf( + log.Debugf( "%s\t%s\t%s\t%s", r.Method, r.RequestURI, diff --git a/restful_server.go b/restful_server.go index 2539c133..47535346 100644 --- a/restful_server.go +++ b/restful_server.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "log" "net/http" "github.com/gorilla/mux" @@ -10,6 +9,7 @@ import ( exchange "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // AllEnabledExchangeOrderbooks holds the enabled exchange orderbooks @@ -50,7 +50,7 @@ func RESTfulJSONResponse(w http.ResponseWriter, r *http.Request, response interf // RESTfulError prints the REST method and error func RESTfulError(method string, err error) { - log.Printf("RESTful %s: server failed to send JSON response. Error %s", + log.Errorf("RESTful %s: server failed to send JSON response. Error %s", method, err) } @@ -101,7 +101,7 @@ func RESTGetOrderbook(w http.ResponseWriter, r *http.Request) { response, err := GetSpecificOrderbook(currency, exchange, assetType) if err != nil { - log.Printf("Failed to fetch orderbook for %s currency: %s\n", exchange, + log.Errorf("Failed to fetch orderbook for %s currency: %s\n", exchange, currency) return } @@ -124,7 +124,7 @@ func GetAllActiveOrderbooks() []EnabledExchangeOrderbooks { currencies := individualBot.GetEnabledCurrencies() assetTypes, err := exchange.GetExchangeAssetTypes(exchangeName) if err != nil { - log.Printf("failed to get %s exchange asset types. Error: %s", + log.Errorf("failed to get %s exchange asset types. Error: %s", exchangeName, err) continue } @@ -143,7 +143,7 @@ func GetAllActiveOrderbooks() []EnabledExchangeOrderbooks { } if err != nil { - log.Printf("failed to get %s %s orderbook. Error: %s", + log.Errorf("failed to get %s %s orderbook. Error: %s", currency.Pair().String(), exchangeName, err) @@ -193,7 +193,7 @@ func RESTGetTicker(w http.ResponseWriter, r *http.Request) { } response, err := GetSpecificTicker(currency, exchange, assetType) if err != nil { - log.Printf("Failed to fetch ticker for %s currency: %s\n", exchange, + log.Errorf("Failed to fetch ticker for %s currency: %s\n", exchange, currency) return } @@ -217,7 +217,7 @@ func GetAllActiveTickers() []EnabledExchangeCurrencies { currency := x assetTypes, err := exchange.GetExchangeAssetTypes(exchangeName) if err != nil { - log.Printf("failed to get %s exchange asset types. Error: %s", + log.Errorf("failed to get %s exchange asset types. Error: %s", exchangeName, err) continue } @@ -233,7 +233,7 @@ func GetAllActiveTickers() []EnabledExchangeCurrencies { } if err != nil { - log.Printf("failed to get %s %s ticker. Error: %s", + log.Errorf("failed to get %s %s ticker. Error: %s", currency.Pair().String(), exchangeName, err) @@ -267,12 +267,12 @@ func GetAllEnabledExchangeAccountInfo() AllEnabledExchangeAccounts { for _, individualBot := range bot.exchanges { if individualBot != nil && individualBot.IsEnabled() { if !individualBot.GetAuthenticatedAPISupport() { - log.Printf("GetAllEnabledExchangeAccountInfo: Skippping %s due to disabled authenticated API support.", individualBot.GetName()) + log.Warnf("GetAllEnabledExchangeAccountInfo: Skippping %s due to disabled authenticated API support.", individualBot.GetName()) continue } individualExchange, err := individualBot.GetAccountInfo() if err != nil { - log.Printf("Error encountered retrieving exchange account info for %s. Error %s", + log.Errorf("Error encountered retrieving exchange account info for %s. Error %s", individualBot.GetName(), err) continue } diff --git a/routines.go b/routines.go index 7ac553e9..bd97a55b 100644 --- a/routines.go +++ b/routines.go @@ -3,7 +3,6 @@ package main import ( "errors" "fmt" - "log" "sync" "time" @@ -15,12 +14,13 @@ import ( "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/stats" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) func printCurrencyFormat(price float64) string { displaySymbol, err := symbol.GetSymbolByCurrencyName(bot.config.Currency.FiatDisplayCurrency) if err != nil { - log.Printf("Failed to get display symbol: %s", err) + log.Errorf("Failed to get display symbol: %s", err) } return fmt.Sprintf("%s%.8f", displaySymbol, price) @@ -30,17 +30,17 @@ func printConvertCurrencyFormat(origCurrency string, origPrice float64) string { displayCurrency := bot.config.Currency.FiatDisplayCurrency conv, err := currency.ConvertCurrency(origPrice, origCurrency, displayCurrency) if err != nil { - log.Printf("Failed to convert currency: %s", err) + log.Errorf("Failed to convert currency: %s", err) } displaySymbol, err := symbol.GetSymbolByCurrencyName(displayCurrency) if err != nil { - log.Printf("Failed to get display symbol: %s", err) + log.Errorf("Failed to get display symbol: %s", err) } origSymbol, err := symbol.GetSymbolByCurrencyName(origCurrency) if err != nil { - log.Printf("Failed to get original currency symbol: %s", err) + log.Errorf("Failed to get original currency symbol: %s", err) } return fmt.Sprintf("%s%.2f %s (%s%.2f %s)", @@ -55,7 +55,7 @@ func printConvertCurrencyFormat(origCurrency string, origPrice float64) string { func printTickerSummary(result ticker.Price, p pair.CurrencyPair, assetType, exchangeName string, err error) { if err != nil { - log.Printf("Failed to get %s %s ticker. Error: %s", + log.Errorf("Failed to get %s %s ticker. Error: %s", p.Pair().String(), exchangeName, err) @@ -65,7 +65,7 @@ func printTickerSummary(result ticker.Price, p pair.CurrencyPair, assetType, exc stats.Add(exchangeName, p, assetType, result.Last, result.Volume) if currency.IsFiatCurrency(p.SecondCurrency.String()) && p.SecondCurrency.String() != bot.config.Currency.FiatDisplayCurrency { origCurrency := p.SecondCurrency.Upper().String() - log.Printf("%s %s %s: TICKER: Last %s Ask %s Bid %s High %s Low %s Volume %.8f", + log.Infof("%s %s %s: TICKER: Last %s Ask %s Bid %s High %s Low %s Volume %.8f", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -77,7 +77,7 @@ func printTickerSummary(result ticker.Price, p pair.CurrencyPair, assetType, exc result.Volume) } else { if currency.IsFiatCurrency(p.SecondCurrency.String()) && p.SecondCurrency.Upper().String() == bot.config.Currency.FiatDisplayCurrency { - log.Printf("%s %s %s: TICKER: Last %s Ask %s Bid %s High %s Low %s Volume %.8f", + log.Infof("%s %s %s: TICKER: Last %s Ask %s Bid %s High %s Low %s Volume %.8f", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -88,7 +88,7 @@ func printTickerSummary(result ticker.Price, p pair.CurrencyPair, assetType, exc printCurrencyFormat(result.Low), result.Volume) } else { - log.Printf("%s %s %s: TICKER: Last %.8f Ask %.8f Bid %.8f High %.8f Low %.8f Volume %.8f", + log.Infof("%s %s %s: TICKER: Last %.8f Ask %.8f Bid %.8f High %.8f Low %.8f Volume %.8f", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -104,7 +104,7 @@ func printTickerSummary(result ticker.Price, p pair.CurrencyPair, assetType, exc func printOrderbookSummary(result orderbook.Base, p pair.CurrencyPair, assetType, exchangeName string, err error) { if err != nil { - log.Printf("Failed to get %s %s orderbook. Error: %s", + log.Errorf("Failed to get %s %s orderbook. Error: %s", p.Pair().String(), exchangeName, err) @@ -116,7 +116,7 @@ func printOrderbookSummary(result orderbook.Base, p pair.CurrencyPair, assetType if currency.IsFiatCurrency(p.SecondCurrency.String()) && p.SecondCurrency.String() != bot.config.Currency.FiatDisplayCurrency { origCurrency := p.SecondCurrency.Upper().String() - log.Printf("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %s Asks len: %d Amount: %f %s. Total value: %s", + log.Infof("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %s Asks len: %d Amount: %f %s. Total value: %s", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -131,7 +131,7 @@ func printOrderbookSummary(result orderbook.Base, p pair.CurrencyPair, assetType ) } else { if currency.IsFiatCurrency(p.SecondCurrency.String()) && p.SecondCurrency.Upper().String() == bot.config.Currency.FiatDisplayCurrency { - log.Printf("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %s Asks len: %d Amount: %f %s. Total value: %s", + log.Infof("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %s Asks len: %d Amount: %f %s. Total value: %s", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -145,7 +145,7 @@ func printOrderbookSummary(result orderbook.Base, p pair.CurrencyPair, assetType printCurrencyFormat(asksValue), ) } else { - log.Printf("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %f Asks len: %d Amount: %f %s. Total value: %f", + log.Infof("%s %s %s: ORDERBOOK: Bids len: %d Amount: %f %s. Total value: %f Asks len: %d Amount: %f %s. Total value: %f", exchangeName, exchange.FormatCurrency(p).String(), assetType, @@ -171,15 +171,15 @@ func relayWebsocketEvent(result interface{}, event, assetType, exchangeName stri } err := BroadcastWebsocketMessage(evt) if err != nil { - log.Println(fmt.Errorf("Failed to broadcast websocket event. Error: %s", - err)) + log.Errorf("Failed to broadcast websocket event. Error: %s", + err) } } // TickerUpdaterRoutine fetches and updates the ticker for all enabled // currency pairs and exchanges func TickerUpdaterRoutine() { - log.Println("Starting ticker updater routine.") + log.Debugf("Starting ticker updater routine.") var wg sync.WaitGroup for { wg.Add(len(bot.exchanges)) @@ -194,7 +194,7 @@ func TickerUpdaterRoutine() { supportsBatching := bot.exchanges[x].SupportsRESTTickerBatchUpdates() assetTypes, err := exchange.GetExchangeAssetTypes(exchangeName) if err != nil { - log.Printf("failed to get %s exchange asset types. Error: %s", + log.Debugf("failed to get %s exchange asset types. Error: %s", exchangeName, err) return } @@ -228,7 +228,7 @@ func TickerUpdaterRoutine() { }(x, &wg) } wg.Wait() - log.Println("All enabled currency tickers fetched.") + log.Debugln("All enabled currency tickers fetched.") time.Sleep(time.Second * 10) } } @@ -236,7 +236,7 @@ func TickerUpdaterRoutine() { // OrderbookUpdaterRoutine fetches and updates the orderbooks for all enabled // currency pairs and exchanges func OrderbookUpdaterRoutine() { - log.Println("Starting orderbook updater routine.") + log.Debugln("Starting orderbook updater routine.") var wg sync.WaitGroup for { wg.Add(len(bot.exchanges)) @@ -251,7 +251,7 @@ func OrderbookUpdaterRoutine() { enabledCurrencies := bot.exchanges[x].GetEnabledCurrencies() assetTypes, err := exchange.GetExchangeAssetTypes(exchangeName) if err != nil { - log.Printf("failed to get %s exchange asset types. Error: %s", + log.Errorf("failed to get %s exchange asset types. Error: %s", exchangeName, err) return } @@ -275,19 +275,19 @@ func OrderbookUpdaterRoutine() { }(x, &wg) } wg.Wait() - log.Println("All enabled currency orderbooks fetched.") + log.Debugln("All enabled currency orderbooks fetched.") time.Sleep(time.Second * 10) } } // WebsocketRoutine Initial routine management system for websocket func WebsocketRoutine(verbose bool) { - log.Println("Connecting exchange websocket services...") + log.Debugln("Connecting exchange websocket services...") for i := range bot.exchanges { go func(i int) { if verbose { - log.Printf("Establishing websocket connection for %s", + log.Debugf("Establishing websocket connection for %s", bot.exchanges[i].GetName()) } @@ -303,9 +303,9 @@ func WebsocketRoutine(verbose bool) { if err != nil { switch err.Error() { case exchange.WebsocketNotEnabled: - // Store in memory if enabled in future + log.Warnf("%s - websocket disabled", bot.exchanges[i].GetName()) default: - log.Println(err) + log.Error(err) } } }(i) @@ -320,7 +320,7 @@ var wg sync.WaitGroup func Websocketshutdown(ws *exchange.Websocket) error { err := ws.Shutdown() // shutdown routines on the exchange if err != nil { - log.Fatalf("routines.go error - failed to shutodwn %s", err) + log.Errorf("routines.go error - failed to shutodwn %s", err) } timer := time.NewTimer(5 * time.Second) @@ -354,12 +354,12 @@ func streamDiversion(ws *exchange.Websocket, verbose bool) { case <-ws.Connected: if verbose { - log.Printf("exchange %s websocket feed connected", ws.GetName()) + log.Debugf("exchange %s websocket feed connected", ws.GetName()) } case <-ws.Disconnected: if verbose { - log.Printf("exchange %s websocket feed disconnected, switching to REST functionality", + log.Debugf("exchange %s websocket feed disconnected, switching to REST functionality", ws.GetName()) } } @@ -385,12 +385,12 @@ func WebsocketDataHandler(ws *exchange.Websocket, verbose bool) { switch data.(string) { case exchange.WebsocketNotEnabled: if verbose { - log.Printf("routines.go warning - exchange %s weboscket not enabled", + log.Warnf("routines.go warning - exchange %s weboscket not enabled", ws.GetName()) } default: - log.Println(data.(string)) + log.Infof(data.(string)) } case error: @@ -399,33 +399,33 @@ func WebsocketDataHandler(ws *exchange.Websocket, verbose bool) { go WebsocketReconnect(ws, verbose) continue default: - log.Fatalf("routines.go exchange %s websocket error - %s", ws.GetName(), data) + log.Errorf("routines.go exchange %s websocket error - %s", ws.GetName(), data) } case exchange.TradeData: // Trade Data if verbose { - log.Println("Websocket trades Updated: ", data.(exchange.TradeData)) + log.Infoln("Websocket trades Updated: ", data.(exchange.TradeData)) } case exchange.TickerData: // Ticker data if verbose { - log.Println("Websocket Ticker Updated: ", data.(exchange.TickerData)) + log.Infoln("Websocket Ticker Updated: ", data.(exchange.TickerData)) } case exchange.KlineData: // Kline data if verbose { - log.Println("Websocket Kline Updated: ", data.(exchange.KlineData)) + log.Infoln("Websocket Kline Updated: ", data.(exchange.KlineData)) } case exchange.WebsocketOrderbookUpdate: // Orderbook data if verbose { - log.Println("Websocket Orderbook Updated:", data.(exchange.WebsocketOrderbookUpdate)) + log.Infoln("Websocket Orderbook Updated:", data.(exchange.WebsocketOrderbookUpdate)) } default: if verbose { - log.Println("Websocket Unknown type: ", data) + log.Warnf("Websocket Unknown type: %s", data) } } } @@ -435,12 +435,13 @@ func WebsocketDataHandler(ws *exchange.Websocket, verbose bool) { // WebsocketReconnect tries to reconnect to a websocket stream func WebsocketReconnect(ws *exchange.Websocket, verbose bool) { if verbose { - log.Printf("Websocket reconnection requested for %s", ws.GetName()) + log.Debugf("Websocket reconnection requested for %s", ws.GetName()) } err := ws.Shutdown() if err != nil { - log.Fatal(err) + log.Error(err) + return } wg.Add(1) diff --git a/testdata/configtest.json b/testdata/configtest.json index 72965ec1..6ddc6281 100644 --- a/testdata/configtest.json +++ b/testdata/configtest.json @@ -2,6 +2,13 @@ "name": "", "encryptConfig": -1, "globalHTTPTimeout": 15000000000, + "logging": { + "enabled": true, + "file": "debug.txt", + "colour": false, + "level": "DEBUG|WARN|INFO|ERROR|FATAL", + "rotate": true + }, "currencyConfig": { "forexProviders": [ { diff --git a/tools/exchange_template/wrapper_file.tmpl b/tools/exchange_template/wrapper_file.tmpl index 528f5ce0..1debfd0f 100644 --- a/tools/exchange_template/wrapper_file.tmpl +++ b/tools/exchange_template/wrapper_file.tmpl @@ -3,7 +3,6 @@ package {{.Name}} import ( "errors" - "log" "sync" {{if .WS}} "github.com/thrasher-/gocryptotrader/common" {{end}} @@ -11,6 +10,7 @@ import ( "github.com/thrasher-/gocryptotrader/exchanges" "github.com/thrasher-/gocryptotrader/exchanges/orderbook" "github.com/thrasher-/gocryptotrader/exchanges/ticker" + log "github.com/thrasher-/gocryptotrader/logger" ) // Start starts the {{.CapitalName}} go routine @@ -25,9 +25,9 @@ func ({{.Variable}} *{{.CapitalName}}) Start(wg *sync.WaitGroup) { // Run implements the {{.CapitalName}} wrapper func ({{.Variable}} *{{.CapitalName}}) Run() { if {{.Variable}}.Verbose { -{{if .WS}} log.Printf("%s Websocket: %s. (url: %s).\n", {{.Variable}}.GetName(), common.IsEnabled({{.Variable}}.Websocket.IsEnabled()), {{.Variable}}.Websocket.GetWebsocketURL()) {{end}} - log.Printf("%s polling delay: %ds.\n", {{.Variable}}.GetName(), {{.Variable}}.RESTPollingDelay) - log.Printf("%s %d currencies enabled: %s.\n", {{.Variable}}.GetName(), len({{.Variable}}.EnabledPairs), {{.Variable}}.EnabledPairs) +{{if .WS}} log.Debugf("%s Websocket: %s. (url: %s).\n", {{.Variable}}.GetName(), common.IsEnabled({{.Variable}}.Websocket.IsEnabled()), {{.Variable}}.Websocket.GetWebsocketURL()) {{end}} + log.Debugf("%s polling delay: %ds.\n", {{.Variable}}.GetName(), {{.Variable}}.RESTPollingDelay) + log.Debugf("%s %d currencies enabled: %s.\n", {{.Variable}}.GetName(), len({{.Variable}}.EnabledPairs), {{.Variable}}.EnabledPairs) } } diff --git a/websocket.go b/websocket.go index 04307982..6bd0f07b 100644 --- a/websocket.go +++ b/websocket.go @@ -2,13 +2,13 @@ package main import ( "errors" - "log" "net/http" "github.com/gorilla/websocket" "github.com/thrasher-/gocryptotrader/common" "github.com/thrasher-/gocryptotrader/config" "github.com/thrasher-/gocryptotrader/currency" + log "github.com/thrasher-/gocryptotrader/logger" ) // Const vars for websocket @@ -102,7 +102,7 @@ func (h *WebsocketHub) run() { h.Clients[client] = true case client := <-h.Unregister: if _, ok := h.Clients[client]; ok { - log.Printf("websocket: disconnected client") + log.Debugln("websocket: disconnected client") delete(h.Clients, client) close(client.Send) } @@ -111,7 +111,7 @@ func (h *WebsocketHub) run() { select { case client.Send <- message: default: - log.Printf("websocket: disconnected client") + log.Debugln("websocket: disconnected client") close(client.Send) delete(h.Clients, client) } @@ -124,7 +124,7 @@ func (h *WebsocketHub) run() { func (c *WebsocketClient) SendWebsocketMessage(evt interface{}) error { data, err := common.JSONEncode(evt) if err != nil { - log.Printf("websocket: failed to send message: %s", err) + log.Errorf("websocket: failed to send message: %s", err) return err } @@ -142,7 +142,7 @@ func (c *WebsocketClient) read() { msgType, message, err := c.Conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { - log.Printf("websocket: client disconnected, err: %s", err) + log.Errorf("websocket: client disconnected, err: %s", err) } break } @@ -151,39 +151,39 @@ func (c *WebsocketClient) read() { var evt WebsocketEvent err := common.JSONDecode(message, &evt) if err != nil { - log.Printf("websocket: failed to decode JSON sent from client %s", err) - break + log.Errorf("websocket: failed to decode JSON sent from client %s", err) + continue } if evt.Event == "" { - log.Printf("websocket: client sent a blank event, disconnecting") - break + log.Warnf("websocket: client sent a blank event, disconnecting") + continue } dataJSON, err := common.JSONEncode(evt.Data) if err != nil { - log.Printf("websocket: client sent data we couldn't JSON decode") + log.Errorf("websocket: client sent data we couldn't JSON decode") break } req := common.StringToLower(evt.Event) - log.Printf("websocket: request received: %s", req) + log.Debugf("websocket: request received: %s", req) result, ok := wsHandlers[req] if !ok { - log.Printf("websocket: unsupported event") + log.Debugln("websocket: unsupported event") continue } if result.authRequired && !c.Authenticated { - log.Printf("Websocket: request %s failed due to unauthenticated request on an authenticated API", evt.Event) + log.Warnf("Websocket: request %s failed due to unauthenticated request on an authenticated API", evt.Event) c.SendWebsocketMessage(WebsocketEventResponse{Event: evt.Event, Error: "unauthorised request on authenticated API"}) continue } err = result.handler(c, dataJSON) if err != nil { - log.Printf("websocket: request %s failed. Error %s", evt.Event, err) + log.Errorf("websocket: request %s failed. Error %s", evt.Event, err) continue } } @@ -199,13 +199,13 @@ func (c *WebsocketClient) write() { case message, ok := <-c.Send: if !ok { c.Conn.WriteMessage(websocket.CloseMessage, []byte{}) - log.Printf("websocket: hub closed the channel") + log.Debugln("websocket: hub closed the channel") return } w, err := c.Conn.NextWriter(websocket.TextMessage) if err != nil { - log.Printf("websocket: failed to create new io.writeCloser: %s", err) + log.Errorf("websocket: failed to create new io.writeCloser: %s", err) return } w.Write(message) @@ -217,7 +217,7 @@ func (c *WebsocketClient) write() { } if err := w.Close(); err != nil { - log.Printf("websocket: failed to close io.WriteCloser: %s", err) + log.Errorf("websocket: failed to close io.WriteCloser: %s", err) return } } @@ -260,7 +260,7 @@ func WebsocketClientHandler(w http.ResponseWriter, r *http.Request) { numClients := len(wsHub.Clients) if numClients >= connectionLimit { - log.Printf("websocket: client rejected due to websocket client limit reached. Number of clients %d. Limit %d.", + log.Warnf("websocket: client rejected due to websocket client limit reached. Number of clients %d. Limit %d.", numClients, connectionLimit) w.WriteHeader(http.StatusForbidden) return @@ -279,13 +279,13 @@ func WebsocketClientHandler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { - log.Println(err) + log.Error(err) return } client := &WebsocketClient{Hub: wsHub, Conn: conn, Send: make(chan []byte, 1024)} client.Hub.Register <- client - log.Printf("websocket: client connected. Connected clients: %d. Limit %d.", + log.Debugf("websocket: client connected. Connected clients: %d. Limit %d.", numClients+1, connectionLimit) go client.read() @@ -306,10 +306,11 @@ func wsAuth(client *WebsocketClient, data interface{}) error { } hashPW := common.HexEncodeToString(common.GetSHA256([]byte(bot.config.Webserver.AdminPassword))) + if auth.Username == bot.config.Webserver.AdminUsername && auth.Password == hashPW { client.Authenticated = true wsResp.Data = WebsocketResponseSuccess - log.Println("websocket: client authenticated successfully") + log.Debugf("websocket: client authenticated successfully") return client.SendWebsocketMessage(wsResp) } @@ -317,13 +318,13 @@ func wsAuth(client *WebsocketClient, data interface{}) error { client.authFailures++ client.SendWebsocketMessage(wsResp) if client.authFailures >= bot.config.Webserver.WebsocketMaxAuthFailures { - log.Printf("websocket: disconnecting client, maximum auth failures threshold reached (failures: %d limit: %d)", + log.Debugf("websocket: disconnecting client, maximum auth failures threshold reached (failures: %d limit: %d)", client.authFailures, bot.config.Webserver.WebsocketMaxAuthFailures) wsHub.Unregister <- client return nil } - log.Printf("websocket: client sent wrong username/password (failures: %d limit: %d)", + log.Debugf("websocket: client sent wrong username/password (failures: %d limit: %d)", client.authFailures, bot.config.Webserver.WebsocketMaxAuthFailures) return nil }