Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Commit

Permalink
Merge pull request #499 from BuxOrg/feat-200-unify-logs
Browse files Browse the repository at this point in the history
feat(BUX-199): unify logs
  • Loading branch information
mergify[bot] authored Dec 13, 2023
2 parents d941125 + 2a42f52 commit 6acfb97
Show file tree
Hide file tree
Showing 65 changed files with 853 additions and 484 deletions.
6 changes: 3 additions & 3 deletions action_utxo.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (c *Client) GetUtxo(ctx context.Context, xPubKey, txID string, outputIndex
var tx *Transaction
tx, err = getTransactionByID(ctx, "", utxo.TransactionID, c.DefaultModelOptions()...)
if err != nil {
c.Logger().Error(ctx, "failed finding transaction related to utxo: "+utxo.ID)
c.Logger().Error().Str("utxoID", utxo.ID).Msg("failed finding transaction related to utxo")
} else {
utxo.Transaction = tx
}
Expand All @@ -123,7 +123,7 @@ func (c *Client) GetUtxoByTransactionID(ctx context.Context, txID string, output
var tx *Transaction
tx, err = getTransactionByID(ctx, "", utxo.TransactionID, c.DefaultModelOptions()...)
if err != nil {
c.Logger().Error(ctx, "failed finding transaction related to utxo: "+utxo.ID)
c.Logger().Error().Str("utxoID", utxo.ID).Msg("failed finding transaction related to utxo")
} else {
utxo.Transaction = tx
}
Expand All @@ -144,7 +144,7 @@ func (c *Client) enrichUtxoTransactions(ctx context.Context, utxos []*Utxo) {
for index, utxo := range utxos {
tx, err := getTransactionByID(ctx, "", utxo.TransactionID, c.DefaultModelOptions()...)
if err != nil {
c.Logger().Error(ctx, "failed finding transaction related to utxo: "+utxo.ID)
c.Logger().Error().Str("utxoID", utxo.ID).Msg("failed finding transaction related to utxo")
} else {
utxos[index].Transaction = tx
}
Expand Down
10 changes: 3 additions & 7 deletions beef_tx_bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ func (beefTx *beefTx) toBeefBytes() ([]byte, error) {
transactions := make([][]byte, 0, len(beefTx.transactions))

for _, t := range beefTx.transactions {
txBytes, err := toBeefBytes(t, beefTx.bumps)
if err != nil {
return nil, err
}

txBytes := toBeefBytes(t, beefTx.bumps)
transactions = append(transactions, txBytes)
beefSize += len(txBytes)
}
Expand All @@ -60,7 +56,7 @@ func (beefTx *beefTx) toBeefBytes() ([]byte, error) {
return buffer, nil
}

func toBeefBytes(tx *bt.Tx, bumps BUMPs) ([]byte, error) {
func toBeefBytes(tx *bt.Tx, bumps BUMPs) []byte {
txBeefBytes := tx.Bytes()

bumpIdx := getBumpPathIndex(tx, bumps)
Expand All @@ -71,7 +67,7 @@ func toBeefBytes(tx *bt.Tx, bumps BUMPs) ([]byte, error) {
txBeefBytes = append(txBeefBytes, hasNoBUMP)
}

return txBeefBytes, nil
return txBeefBytes
}

func getBumpPathIndex(tx *bt.Tx, bumps BUMPs) int {
Expand Down
8 changes: 5 additions & 3 deletions bux_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import (
"time"

"github.com/BuxOrg/bux/chainstate"
"github.com/BuxOrg/bux/logging"
"github.com/BuxOrg/bux/taskmanager"
"github.com/BuxOrg/bux/tester"
"github.com/DATA-DOG/go-sqlmock"
"github.com/dolthub/go-mysql-server/server"
embeddedPostgres "github.com/fergusstrange/embedded-postgres"
"github.com/mrz1836/go-datastore"
"github.com/mrz1836/go-logger"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/tryvium-travels/memongo"
Expand Down Expand Up @@ -68,15 +68,17 @@ type EmbeddedDBTestSuite struct {
func (ts *EmbeddedDBTestSuite) serveMySQL() {
defer ts.wg.Done()

logger := logging.GetDefaultLogger()

for {
err := ts.MySQLServer.Start()
if err != nil {
select {
case <-ts.quit:
logger.Data(2, logger.DEBUG, "MySQL channel has closed")
logger.Debug().Msg("MySQL channel has closed")
return
default:
logger.Data(2, logger.ERROR, "mysql server error: "+err.Error())
logger.Error().Msgf("mysql server error: %s", err.Error())
}
}
}
Expand Down
28 changes: 13 additions & 15 deletions chainstate/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package chainstate

import (
"context"
"fmt"
"sync"
"time"

"github.com/BuxOrg/bux/logging"
"github.com/BuxOrg/bux/utils"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
broadcastClient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
"github.com/libsv/go-bt/v2"
zLogger "github.com/mrz1836/go-logger"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/rs/zerolog"
"github.com/tonicpow/go-minercraft/v2"
"github.com/tonicpow/go-minercraft/v2/apis/mapi"
)
Expand All @@ -25,12 +25,12 @@ type (

// clientOptions holds all the configuration for the client
clientOptions struct {
config *syncConfig // Configuration for broadcasting and other chain-state actions
debug bool // For extra logs and additional debug information
logger zLogger.GormLoggerInterface // Internal logger interface
monitor MonitorService // Monitor service
newRelicEnabled bool // If NewRelic is enabled (parent application)
userAgent string // Custom user agent for outgoing HTTP Requests
config *syncConfig // Configuration for broadcasting and other chain-state actions
debug bool // For extra logs and additional debug information
logger *zerolog.Logger // Logger interface
monitor MonitorService // Monitor service
newRelicEnabled bool // If NewRelic is enabled (parent application)
userAgent string // Custom user agent for outgoing HTTP Requests
}

// syncConfig holds all the configuration about the different sync processes
Expand Down Expand Up @@ -94,7 +94,7 @@ func NewClient(ctx context.Context, opts ...ClientOps) (ClientInterface, error)

// Set logger if not set
if client.options.logger == nil {
client.options.logger = zLogger.NewGormLogger(client.IsDebug(), 4)
client.options.logger = logging.GetDefaultLogger()
}

// Start Minercraft
Expand Down Expand Up @@ -133,9 +133,7 @@ func (c *Client) Debug(on bool) {

// DebugLog will display verbose logs
func (c *Client) DebugLog(text string) {
if c.IsDebug() {
c.options.logger.Info(context.Background(), text)
}
c.options.logger.Debug().Msg(text)
}

// IsDebug will return if debugging is enabled
Expand Down Expand Up @@ -220,21 +218,21 @@ func (c *Client) ValidateMiners(ctx context.Context) {
if c.Minercraft().APIType() == minercraft.MAPI {
quote, err := c.Minercraft().FeeQuote(ctx, miner.Miner)
if err != nil {
client.options.logger.Error(ctx, fmt.Sprintf("No FeeQuote response from miner %s. Reason: %s", miner.Miner.Name, err))
client.options.logger.Error().Msgf("No FeeQuote response from miner %s. Reason: %s", miner.Miner.Name, err)
miner.FeeUnit = nil
return
}

fee = quote.Quote.GetFee(mapi.FeeTypeData)
if fee == nil {
client.options.logger.Error(ctx, fmt.Sprintf("Fee is missing in %s's FeeQuote response", miner.Miner.Name))
client.options.logger.Error().Msgf("Fee is missing in %s's FeeQuote response", miner.Miner.Name)
return
}
// Arc doesn't support FeeQuote right now(2023.07.21), that's why PolicyQuote is used
} else if c.Minercraft().APIType() == minercraft.Arc {
quote, err := c.Minercraft().PolicyQuote(ctx, miner.Miner)
if err != nil {
client.options.logger.Error(ctx, fmt.Sprintf("No FeeQuote response from miner %s. Reason: %s", miner.Miner.Name, err))
client.options.logger.Error().Msgf("No FeeQuote response from miner %s. Reason: %s", miner.Miner.Name, err)
miner.FeeUnit = nil
return
}
Expand Down
4 changes: 2 additions & 2 deletions chainstate/client_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (

"github.com/bitcoin-sv/go-broadcast-client/broadcast"
broadcastClient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
zLogger "github.com/mrz1836/go-logger"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/rs/zerolog"
"github.com/tonicpow/go-minercraft/v2"
)

Expand Down Expand Up @@ -178,7 +178,7 @@ func WithNetwork(network Network) ClientOps {
}

// WithLogger will set a custom logger
func WithLogger(customLogger zLogger.GormLoggerInterface) ClientOps {
func WithLogger(customLogger *zerolog.Logger) ClientOps {
return func(c *clientOptions) {
if customLogger != nil {
c.logger = customLogger
Expand Down
8 changes: 4 additions & 4 deletions chainstate/client_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"testing"
"time"

"github.com/BuxOrg/bux/logging"
broadcast_client_mock "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client-mock"
zLogger "github.com/mrz1836/go-logger"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -305,10 +305,10 @@ func TestWithLogger(t *testing.T) {
options := &clientOptions{
config: &syncConfig{},
}
customClient := zLogger.NewGormLogger(true, 4)
opt := WithLogger(customClient)
customLogger := logging.GetDefaultLogger()
opt := WithLogger(customLogger)
opt(options)
assert.Equal(t, customClient, options.logger)
assert.Equal(t, customLogger, options.logger)
})
}

Expand Down
16 changes: 5 additions & 11 deletions chainstate/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,19 @@ import (
"net/http"
"time"

"github.com/BuxOrg/bux/utils"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
"github.com/centrifugal/centrifuge-go"
"github.com/libsv/go-bc"
"github.com/rs/zerolog"
"github.com/tonicpow/go-minercraft/v2"

"github.com/BuxOrg/bux/utils"
)

// HTTPInterface is the HTTP client interface
type HTTPInterface interface {
Do(req *http.Request) (*http.Response, error)
}

// Logger is the logger interface for debug messages
type Logger interface {
Info(ctx context.Context, message string, params ...interface{})
Error(ctx context.Context, message string, params ...interface{})
}

// ChainService is the chain related methods
type ChainService interface {
Broadcast(ctx context.Context, id, txHex string, timeout time.Duration) (string, error)
Expand Down Expand Up @@ -96,10 +90,10 @@ type MonitorProcessor interface {
GetFilters() map[string]*BloomProcessorFilter
GetHash() string
IsDebug() bool
Logger() Logger
Logger() *zerolog.Logger
Reload(regexString string, items []string) error
SetFilter(regex string, filter []byte) error
SetLogger(logger Logger)
SetLogger(logger *zerolog.Logger)
Test(regexString string, item string) bool
}

Expand All @@ -116,7 +110,7 @@ type MonitorService interface {
IsDebug() bool
LoadMonitoredDestinations() bool
AllowUnknownTransactions() bool
Logger() Logger
Logger() *zerolog.Logger
Processor() MonitorProcessor
SaveDestinations() bool
Start(ctx context.Context, handler MonitorHandler, onStop func()) error
Expand Down
4 changes: 2 additions & 2 deletions chainstate/merkle_root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ func (c *Client) VerifyMerkleRoots(ctx context.Context, merkleRoots []MerkleRoot
}

if merkleRootsRes.ConfirmationState == Invalid {
c.options.logger.Warn(context.Background(), "Warn: Not all merkle roots confirmed")
c.options.logger.Warn().Msg("Not all merkle roots confirmed")
return errors.New("not all merkle roots confirmed")
}

if merkleRootsRes.ConfirmationState == UnableToVerify {
c.options.logger.Warn(context.Background(), "Warn: Some merkle roots were unable to be verified. Proceeding regardless.")
c.options.logger.Warn().Msg("Some merkle roots were unable to be verified. Proceeding regardless.")
}

return nil
Expand Down
6 changes: 3 additions & 3 deletions chainstate/merkle_root_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ type MerkleRootConfirmationState string
const (
// Confirmed state occurs when Merkle Root is found in the longest chain.
Confirmed MerkleRootConfirmationState = "CONFIRMED"
// UnableToVerify state occurs when Pulse is behind in synchronization with the longest chain.
Invalid MerkleRootConfirmationState = "INVALID"
// Invalid state occurs when Merkle Root is not found in the longest chain.
Invalid MerkleRootConfirmationState = "INVALID"
// UnableToVerify state occurs when Pulse is behind in synchronization with the longest chain.
UnableToVerify MerkleRootConfirmationState = "UNABLE_TO_VERIFY"
)

Expand Down Expand Up @@ -71,7 +71,7 @@ func (p pulseClientProvider) verifyMerkleRoots(
}
res, err := client.Do(req)
if err != nil {
c.options.logger.Error(context.Background(), "Error during creating connection to pulse client: %s", err.Error())
c.options.logger.Error().Msgf("Error during creating connection to pulse client: %s", err.Error())
return nil, err
}
defer res.Body.Close() //nolint: all // Close the body
Expand Down
20 changes: 10 additions & 10 deletions chainstate/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package chainstate

import (
"context"
"fmt"

"github.com/BuxOrg/bux/logging"
"github.com/BuxOrg/bux/utils"
zLogger "github.com/mrz1836/go-logger"
"github.com/rs/zerolog"
)

// Monitor starts a new monitorConfig to monitor and filter transactions from a source
Expand All @@ -23,7 +23,7 @@ type Monitor struct {
handler MonitorHandler
loadMonitoredDestinations bool
lockID string
logger zLogger.GormLoggerInterface
logger *zerolog.Logger
maxNumberOfDestinations int
mempoolSyncChannelActive bool
mempoolSyncChannel chan bool
Expand Down Expand Up @@ -99,7 +99,7 @@ func NewMonitor(_ context.Context, options *MonitorOptions) (monitor *Monitor) {

// Set logger if not set
if monitor.logger == nil {
monitor.logger = zLogger.NewGormLogger(options.Debug, 4)
monitor.logger = logging.GetDefaultLogger()
}

// Switch on the filter type
Expand Down Expand Up @@ -127,7 +127,7 @@ func (m *Monitor) Add(regexString, item string) error {
return err
}
} else {
m.logger.Error(context.Background(), "client was expected but not found")
m.logger.Error().Msg("client was expected but not found")
}
return m.processor.Add(regexString, item)
}
Expand Down Expand Up @@ -183,7 +183,7 @@ func (m *Monitor) AllowUnknownTransactions() bool {
}

// Logger gets the current logger
func (m *Monitor) Logger() Logger {
func (m *Monitor) Logger() *zerolog.Logger {
return m.logger
}

Expand All @@ -203,11 +203,11 @@ func (m *Monitor) SetChainstateOptions(options *clientOptions) {
}

// Start open a socket to the service provider and monitorConfig transactions
func (m *Monitor) Start(ctx context.Context, handler MonitorHandler, onStop func()) error {
func (m *Monitor) Start(_ context.Context, handler MonitorHandler, onStop func()) error {
if m.client == nil {
handler.SetMonitor(m)
m.handler = handler
m.logger.Info(ctx, fmt.Sprintf("[MONITOR] Starting, connecting to server: %s", m.buxAgentURL))
m.logger.Info().Msgf("[MONITOR] Starting, connecting to server: %s", m.buxAgentURL)
m.client = newCentrifugeClient(m.buxAgentURL, handler)
if m.authToken != "" {
m.client.SetToken(m.authToken)
Expand All @@ -220,8 +220,8 @@ func (m *Monitor) Start(ctx context.Context, handler MonitorHandler, onStop func
}

// Stop closes the monitoring socket and pauses monitoring
func (m *Monitor) Stop(ctx context.Context) error {
m.logger.Info(ctx, "[MONITOR] Stopping monitor...")
func (m *Monitor) Stop(_ context.Context) error {
m.logger.Info().Msg("[MONITOR] Stopping monitor...")
if m.IsConnected() { // Only close if still connected
if m.mempoolSyncChannelActive {
close(m.mempoolSyncChannel)
Expand Down
Loading

0 comments on commit 6acfb97

Please sign in to comment.