Skip to content

Commit

Permalink
Darren/enhancement/use slog (#781)
Browse files Browse the repository at this point in the history
* refactor: use built in slog package

* enhancement: replace log15 with slog

* fix: remove go < 1.21

* chore:  tidy imports

* fix: lint errors

* fix: revert IDE refactor

* refactor: rename log.New to log.WithContext

* refactor: update disco logging

* chore: update log readme

* fix: add license header
  • Loading branch information
darrenvechain authored Jul 15, 2024
1 parent e5d76aa commit 810c4bd
Show file tree
Hide file tree
Showing 42 changed files with 1,563 additions and 242 deletions.
6 changes: 3 additions & 3 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/inconshreveable/log15"
"github.com/vechain/thor/v2/api/accounts"
"github.com/vechain/thor/v2/api/blocks"
"github.com/vechain/thor/v2/api/debug"
Expand All @@ -24,13 +23,14 @@ import (
"github.com/vechain/thor/v2/api/transfers"
"github.com/vechain/thor/v2/bft"
"github.com/vechain/thor/v2/chain"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/state"
"github.com/vechain/thor/v2/thor"
"github.com/vechain/thor/v2/txpool"
)

var log = log15.New("pkg", "api")
var logger = log.WithContext("pkg", "api")

// New return api router
func New(
Expand Down Expand Up @@ -109,7 +109,7 @@ func New(
)(handler)

if enableReqLogger {
handler = RequestLoggerHandler(handler, log)
handler = RequestLoggerHandler(handler, logger)
}

return handler.ServeHTTP, subs.Close // subscriptions handles hijacked conns, which need to be closed
Expand Down
4 changes: 2 additions & 2 deletions api/request_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import (
"net/http"
"time"

"github.com/inconshreveable/log15"
"github.com/vechain/thor/v2/log"
)

// RequestLoggerHandler returns a http handler to ensure requests are syphoned into the writer
func RequestLoggerHandler(handler http.Handler, logger log15.Logger) http.Handler {
func RequestLoggerHandler(handler http.Handler, logger log.Logger) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Read and log the body (note: this can only be done once)
// Ensure you don't disrupt the request body for handlers that need to read it
Expand Down
22 changes: 18 additions & 4 deletions api/request_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,39 @@
package api

import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/inconshreveable/log15"
"github.com/stretchr/testify/assert"
"github.com/vechain/thor/v2/log"
)

// mockLogger is a simple logger implementation for testing purposes
type mockLogger struct {
loggedData []interface{}
}

func (m *mockLogger) New(ctx ...interface{}) log15.Logger { return m }
func (m *mockLogger) With(ctx ...interface{}) log.Logger {
return m
}

func (m *mockLogger) Log(level slog.Level, msg string, ctx ...interface{}) {}

func (m *mockLogger) Trace(msg string, ctx ...interface{}) {}

func (m *mockLogger) Write(level slog.Level, msg string, attrs ...any) {}

func (m *mockLogger) Enabled(ctx context.Context, level slog.Level) bool {
return true
}

func (m *mockLogger) GetHandler() log15.Handler { return nil }
func (m *mockLogger) Handler() slog.Handler { return nil }

func (m *mockLogger) SetHandler(h log15.Handler) {}
func (m *mockLogger) New(ctx ...interface{}) log.Logger { return m }

func (m *mockLogger) Debug(msg string, ctx ...interface{}) {}

Expand Down
5 changes: 0 additions & 5 deletions api/subscriptions/block_reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"time"

"github.com/ethereum/go-ethereum/crypto"
"github.com/inconshreveable/log15"
"github.com/stretchr/testify/assert"
"github.com/vechain/thor/v2/block"
"github.com/vechain/thor/v2/chain"
Expand All @@ -24,10 +23,6 @@ import (
"github.com/vechain/thor/v2/txpool"
)

func init() {
log15.Root().SetHandler(log15.DiscardHandler())
}

func TestBlockReader_Read(t *testing.T) {
repo, generatedBlocks, _ := initChain(t)
genesisBlk := generatedBlocks[0]
Expand Down
14 changes: 7 additions & 7 deletions api/subscriptions/subscriptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import (

"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/inconshreveable/log15"
"github.com/pkg/errors"
"github.com/vechain/thor/v2/api/utils"
"github.com/vechain/thor/v2/block"
"github.com/vechain/thor/v2/chain"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/thor"
"github.com/vechain/thor/v2/tx"
"github.com/vechain/thor/v2/txpool"
Expand All @@ -38,7 +38,7 @@ type msgReader interface {
}

var (
log = log15.New("pkg", "subscriptions")
logger = log.WithContext("pkg", "subscriptions")
)

const (
Expand Down Expand Up @@ -205,7 +205,7 @@ func (s *Subscriptions) handleSubject(w http.ResponseWriter, req *http.Request)
conn, closed, err := s.setupConn(w, req)
// since the conn is hijacked here, no error should be returned in lines below
if err != nil {
log.Debug("upgrade to websocket", "err", err)
logger.Debug("upgrade to websocket", "err", err)
return nil
}

Expand All @@ -221,7 +221,7 @@ func (s *Subscriptions) handlePendingTransactions(w http.ResponseWriter, req *ht
conn, closed, err := s.setupConn(w, req)
// since the conn is hijacked here, no error should be returned in lines below
if err != nil {
log.Debug("upgrade to websocket", "err", err)
logger.Debug("upgrade to websocket", "err", err)
return nil
}
defer s.closeConn(conn, err)
Expand Down Expand Up @@ -271,7 +271,7 @@ func (s *Subscriptions) setupConn(w http.ResponseWriter, req *http.Request) (*we
})
for {
if _, _, err := conn.ReadMessage(); err != nil {
log.Debug("websocket read err", "err", err)
logger.Debug("websocket read err", "err", err)
close(closed)
break
}
Expand All @@ -290,11 +290,11 @@ func (s *Subscriptions) closeConn(conn *websocket.Conn, err error) {
}

if err := conn.WriteMessage(websocket.CloseMessage, closeMsg); err != nil {
log.Debug("write close message", "err", err)
logger.Debug("write close message", "err", err)
}

if err := conn.Close(); err != nil {
log.Debug("close websocket", "err", err)
logger.Debug("close websocket", "err", err)
}
}

Expand Down
5 changes: 0 additions & 5 deletions api/transactions/transactions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
"github.com/gorilla/mux"
"github.com/inconshreveable/log15"
"github.com/stretchr/testify/assert"
"github.com/vechain/thor/v2/api/transactions"
"github.com/vechain/thor/v2/chain"
Expand All @@ -34,10 +33,6 @@ import (
"github.com/vechain/thor/v2/txpool"
)

func init() {
log15.Root().SetHandler(log15.DiscardHandler())
}

var repo *chain.Repository
var ts *httptest.Server
var transaction *tx.Transaction
Expand Down
12 changes: 6 additions & 6 deletions block/header_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func TestHeader_BetterThan(t *testing.T) {

func TestHeaderEncoding(t *testing.T) {
var sig [65]byte
rand.Read(sig[:]) // nolint:gosec
rand.Read(sig[:]) // nolint

block := new(Builder).Build().WithSignature(sig[:])
h := block.Header()
Expand All @@ -86,8 +86,8 @@ func TestHeaderEncoding(t *testing.T) {

var proof [81]byte
var alpha [32]byte
rand.Read(proof[:]) // nolint:gosec
rand.Read(alpha[:]) // nolint:gosec
rand.Read(proof[:]) // nolint
rand.Read(alpha[:]) // nolint

complex, err := NewComplexSignature(sig[:], proof[:])
if err != nil {
Expand All @@ -110,7 +110,7 @@ func TestHeaderEncoding(t *testing.T) {
// type extension struct{Alpha []byte}
func TestEncodingBadExtension(t *testing.T) {
var sig [65]byte
rand.Read(sig[:]) // nolint:gosec
rand.Read(sig[:]) // nolint

block := new(Builder).Build().WithSignature(sig[:])
h := block.Header()
Expand Down Expand Up @@ -157,8 +157,8 @@ func TestEncodingBadExtension(t *testing.T) {
func TestEncodingExtension(t *testing.T) {
var sig [ComplexSigSize]byte
var alpha [32]byte
rand.Read(sig[:]) // nolint:gosec
rand.Read(alpha[:]) // nolint:gosec
rand.Read(sig[:]) // nolint
rand.Read(alpha[:]) // nolint

block := new(Builder).Alpha(alpha[:]).Build().WithSignature(sig[:])
h := block.Header()
Expand Down
2 changes: 1 addition & 1 deletion cache/prio_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func TestPrioCacheAddRemove(t *testing.T) {

func TestPrioCache(t *testing.T) {
c := cache.NewPrioCache(5)
rand.Seed(time.Now().UnixNano())
rand.Seed(time.Now().UnixNano()) // nolint:staticcheck

type kvp struct {
k, v int
Expand Down
2 changes: 1 addition & 1 deletion cache/rnd_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

func init() {
rand.Seed(time.Now().UnixNano())
rand.Seed(time.Now().UnixNano()) // nolint:staticcheck
}

// RandCache a simple cache which randomly evicts entries when
Expand Down
2 changes: 1 addition & 1 deletion cmd/disco/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.2
1.0.3
42 changes: 42 additions & 0 deletions cmd/disco/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) 2024 The VeChainThor developers
//
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>

package main

import (
"github.com/vechain/thor/v2/log"
"gopkg.in/urfave/cli.v1"
)

var (
addrFlag = cli.StringFlag{
Name: "addr",
Value: ":55555",
Usage: "listen address",
}
keyFileFlag = cli.StringFlag{
Name: "keyfile",
Usage: "private key file path",
Value: defaultKeyFile(),
}
keyHexFlag = cli.StringFlag{
Name: "keyhex",
Usage: "private key as hex",
}
natFlag = cli.StringFlag{
Name: "nat",
Value: "none",
Usage: "port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
}
netRestrictFlag = cli.StringFlag{
Name: "netrestrict",
Usage: "restrict network communication to the given IP networks (CIDR masks)",
}
verbosityFlag = cli.IntFlag{
Name: "verbosity",
Value: log.LegacyLevelWarn,
Usage: "log verbosity (0-9)",
}
)
42 changes: 9 additions & 33 deletions cmd/disco/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import (
"os"

"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discv5"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/p2p/netutil"
"github.com/pkg/errors"
"github.com/vechain/thor/v2/log"
cli "gopkg.in/urfave/cli.v1"
)

Expand All @@ -28,41 +28,17 @@ var (
copyrightYear string

flags = []cli.Flag{
cli.StringFlag{
Name: "addr",
Value: ":55555",
Usage: "listen address",
},
cli.StringFlag{
Name: "keyfile",
Usage: "private key file path",
Value: defaultKeyFile(),
},
cli.StringFlag{
Name: "keyhex",
Usage: "private key as hex",
},
cli.StringFlag{
Name: "nat",
Value: "none",
Usage: "port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
},
cli.StringFlag{
Name: "netrestrict",
Usage: "restrict network communication to the given IP networks (CIDR masks)",
},
cli.IntFlag{
Name: "verbosity",
Value: int(log.LvlWarn),
Usage: "log verbosity (0-9)",
},
addrFlag,
keyFileFlag,
keyHexFlag,
natFlag,
netRestrictFlag,
verbosityFlag,
}
)

func run(ctx *cli.Context) error {
logHandler := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(true)))
logHandler.Verbosity(log.Lvl(ctx.Int("verbosity")))
log.Root().SetHandler(logHandler)
initLogger(ctx)

natm, err := nat.Parse(ctx.String("nat"))
if err != nil {
Expand Down Expand Up @@ -113,7 +89,7 @@ func run(ctx *cli.Context) error {
if err != nil {
return err
}
fmt.Println("Running", net.Self().String())
log.Info("Running", "URI", net.Self().String())

select {}
}
Expand Down
Loading

0 comments on commit 810c4bd

Please sign in to comment.