multi: add persistent logger

pull/99/head
Oliver Gugger 5 years ago
parent 0d76d6e162
commit b574e344ea
No known key found for this signature in database
GPG Key ID: 8E4256593F177720

@ -192,7 +192,7 @@ func (s *Client) Run(ctx context.Context,
if err != nil { if err != nil {
return fmt.Errorf("GetInfo error: %v", err) return fmt.Errorf("GetInfo error: %v", err)
} }
logger.Infof("Connected to lnd node %v with pubkey %v", log.Infof("Connected to lnd node %v with pubkey %v",
info.Alias, hex.EncodeToString(info.IdentityPubkey[:]), info.Alias, hex.EncodeToString(info.IdentityPubkey[:]),
) )
@ -235,22 +235,22 @@ func (s *Client) Run(ctx context.Context,
} }
if err != nil { if err != nil {
logger.Errorf("Swap client terminating: %v", err) log.Errorf("Swap client terminating: %v", err)
} else { } else {
logger.Info("Swap client terminating") log.Info("Swap client terminating")
} }
// Cancel all remaining active goroutines. // Cancel all remaining active goroutines.
mainCancel() mainCancel()
// Wait for all to finish. // Wait for all to finish.
logger.Debug("Wait for executor to finish") log.Debug("Wait for executor to finish")
s.executor.waitFinished() s.executor.waitFinished()
logger.Debug("Wait for goroutines to finish") log.Debug("Wait for goroutines to finish")
s.wg.Wait() s.wg.Wait()
logger.Info("Swap client terminated") log.Info("Swap client terminated")
return err return err
} }
@ -270,7 +270,7 @@ func (s *Client) resumeSwaps(ctx context.Context,
} }
swap, err := resumeLoopOutSwap(ctx, swapCfg, pend) swap, err := resumeLoopOutSwap(ctx, swapCfg, pend)
if err != nil { if err != nil {
logger.Errorf("resuming loop out swap: %v", err) log.Errorf("resuming loop out swap: %v", err)
continue continue
} }
@ -283,7 +283,7 @@ func (s *Client) resumeSwaps(ctx context.Context,
} }
swap, err := resumeLoopInSwap(ctx, swapCfg, pend) swap, err := resumeLoopInSwap(ctx, swapCfg, pend)
if err != nil { if err != nil {
logger.Errorf("resuming loop in swap: %v", err) log.Errorf("resuming loop in swap: %v", err)
continue continue
} }
@ -303,7 +303,7 @@ func (s *Client) resumeSwaps(ctx context.Context,
func (s *Client) LoopOut(globalCtx context.Context, func (s *Client) LoopOut(globalCtx context.Context,
request *OutRequest) (*lntypes.Hash, btcutil.Address, error) { request *OutRequest) (*lntypes.Hash, btcutil.Address, error) {
logger.Infof("LoopOut %v to %v (channel: %v)", log.Infof("LoopOut %v to %v (channel: %v)",
request.Amount, request.DestAddr, request.Amount, request.DestAddr,
request.LoopOutChannel, request.LoopOutChannel,
) )
@ -358,7 +358,7 @@ func (s *Client) LoopOutQuote(ctx context.Context,
return nil, err return nil, err
} }
logger.Infof("Offchain swap destination: %x", quote.SwapPaymentDest) log.Infof("Offchain swap destination: %x", quote.SwapPaymentDest)
swapFee := quote.SwapFee swapFee := quote.SwapFee
@ -418,7 +418,7 @@ func (s *Client) waitForInitialized(ctx context.Context) error {
func (s *Client) LoopIn(globalCtx context.Context, func (s *Client) LoopIn(globalCtx context.Context,
request *LoopInRequest) (*lntypes.Hash, btcutil.Address, error) { request *LoopInRequest) (*lntypes.Hash, btcutil.Address, error) {
logger.Infof("Loop in %v (channel: %v)", log.Infof("Loop in %v (channel: %v)",
request.Amount, request.Amount,
request.LoopInChannel, request.LoopInChannel,
) )

@ -1,5 +1,23 @@
package main package main
import (
"path/filepath"
"github.com/btcsuite/btcutil"
)
var (
loopDirBase = btcutil.AppDataDir("loop", false)
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "loopd.log"
defaultLogDir = filepath.Join(loopDirBase, defaultLogDirname)
defaultMaxLogFiles = 3
defaultMaxLogFileSize = 10
)
type lndConfig struct { type lndConfig struct {
Host string `long:"host" description:"lnd instance rpc address"` Host string `long:"host" description:"lnd instance rpc address"`
MacaroonDir string `long:"macaroondir" description:"Path to the directory containing all the required lnd macaroons"` MacaroonDir string `long:"macaroondir" description:"Path to the directory containing all the required lnd macaroons"`
@ -16,6 +34,12 @@ type config struct {
RPCListen string `long:"rpclisten" description:"Address to listen on for gRPC clients"` RPCListen string `long:"rpclisten" description:"Address to listen on for gRPC clients"`
RESTListen string `long:"restlisten" description:"Address to listen on for REST clients"` RESTListen string `long:"restlisten" description:"Address to listen on for REST clients"`
LogDir string `long:"logdir" description:"Directory to log output."`
MaxLogFiles int `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)"`
MaxLogFileSize int `long:"maxlogfilesize" description:"Maximum logfile size in MB"`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level for all subsystems {trace, debug, info, warn, error, critical} -- You may also specify <subsystem>=<level>,<subsystem2>=<level>,... to set the log level for individual subsystems -- Use show to list available subsystems"`
Lnd *lndConfig `group:"lnd" namespace:"lnd"` Lnd *lndConfig `group:"lnd" namespace:"lnd"`
View viewParameters `command:"view" alias:"v" description:"View all swaps in the database. This command can only be executed when loopd is not running."` View viewParameters `command:"view" alias:"v" description:"View all swaps in the database. This command can only be executed when loopd is not running."`
@ -27,10 +51,14 @@ const (
) )
var defaultConfig = config{ var defaultConfig = config{
Network: "mainnet", Network: "mainnet",
RPCListen: "localhost:11010", RPCListen: "localhost:11010",
RESTListen: "localhost:8081", RESTListen: "localhost:8081",
Insecure: false, Insecure: false,
LogDir: defaultLogDir,
MaxLogFiles: defaultMaxLogFiles,
MaxLogFileSize: defaultMaxLogFileSize,
DebugLevel: defaultLogLevel,
Lnd: &lndConfig{ Lnd: &lndConfig{
Host: "localhost:10009", Host: "localhost:10009",
}, },

@ -40,7 +40,7 @@ func daemon(config *config) error {
} }
} }
logger.Infof("Swap server address: %v", config.SwapServer) log.Infof("Swap server address: %v", config.SwapServer)
// Create an instance of the loop client library. // Create an instance of the loop client library.
swapClient, cleanup, err := getClient( swapClient, cleanup, err := getClient(
@ -73,7 +73,7 @@ func daemon(config *config) error {
looprpc.RegisterSwapClientServer(grpcServer, &server) looprpc.RegisterSwapClientServer(grpcServer, &server)
// Next, start the gRPC server listening for HTTP/2 connections. // Next, start the gRPC server listening for HTTP/2 connections.
logger.Infof("Starting gRPC listener") log.Infof("Starting gRPC listener")
grpcListener, err := net.Listen("tcp", config.RPCListen) grpcListener, err := net.Listen("tcp", config.RPCListen)
if err != nil { if err != nil {
return fmt.Errorf("RPC server unable to listen on %s", return fmt.Errorf("RPC server unable to listen on %s",
@ -95,7 +95,7 @@ func daemon(config *config) error {
return err return err
} }
logger.Infof("Starting REST proxy listener") log.Infof("Starting REST proxy listener")
restListener, err := net.Listen("tcp", config.RESTListen) restListener, err := net.Listen("tcp", config.RESTListen)
if err != nil { if err != nil {
return fmt.Errorf("REST proxy unable to listen on %s", return fmt.Errorf("REST proxy unable to listen on %s",
@ -115,14 +115,14 @@ func daemon(config *config) error {
go func() { go func() {
defer wg.Done() defer wg.Done()
logger.Infof("Starting swap client") log.Infof("Starting swap client")
err := swapClient.Run(mainCtx, statusChan) err := swapClient.Run(mainCtx, statusChan)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
logger.Infof("Swap client stopped") log.Infof("Swap client stopped")
logger.Infof("Stopping gRPC server") log.Infof("Stopping gRPC server")
grpcServer.Stop() grpcServer.Stop()
cancel() cancel()
@ -133,7 +133,7 @@ func daemon(config *config) error {
go func() { go func() {
defer wg.Done() defer wg.Done()
logger.Infof("Waiting for updates") log.Infof("Waiting for updates")
for { for {
select { select {
case swap := <-statusChan: case swap := <-statusChan:
@ -160,12 +160,12 @@ func daemon(config *config) error {
go func() { go func() {
defer wg.Done() defer wg.Done()
logger.Infof("RPC server listening on %s", grpcListener.Addr()) log.Infof("RPC server listening on %s", grpcListener.Addr())
logger.Infof("REST proxy listening on %s", restListener.Addr()) log.Infof("REST proxy listening on %s", restListener.Addr())
err = grpcServer.Serve(grpcListener) err = grpcServer.Serve(grpcListener)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
}() }()
@ -175,7 +175,7 @@ func daemon(config *config) error {
// Run until the users terminates loopd or an error occurred. // Run until the users terminates loopd or an error occurred.
select { select {
case <-interruptChannel: case <-interruptChannel:
logger.Infof("Received SIGINT (Ctrl+C).") log.Infof("Received SIGINT (Ctrl+C).")
// TODO: Remove debug code. // TODO: Remove debug code.
// Debug code to dump goroutines on hanging exit. // Debug code to dump goroutines on hanging exit.

@ -1,24 +1,40 @@
package main package main
import ( import (
"os"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/lightninglabs/loop"
"github.com/lightninglabs/loop/lndclient"
"github.com/lightninglabs/loop/loopdb"
"github.com/lightningnetwork/lnd/build"
) )
// log is a logger that is initialized with no output filters. This means the
// package will not perform any logging by default until the caller requests
// it.
var ( var (
backendLog = btclog.NewBackend(logWriter{}) logWriter = build.NewRotatingLogWriter()
logger = backendLog.Logger("LOOPD")
log = build.NewSubLogger("LOOPD", logWriter.GenSubLogger)
) )
// logWriter implements an io.Writer that outputs to both standard output and func init() {
// the write-end pipe of an initialized log rotator. setSubLogger("LOOPD", log, nil)
type logWriter struct{} addSubLogger("LOOP", loop.UseLogger)
addSubLogger("LNDC", lndclient.UseLogger)
addSubLogger("STORE", loopdb.UseLogger)
}
// addSubLogger is a helper method to conveniently create and register the
// logger of a sub system.
func addSubLogger(subsystem string, useLogger func(btclog.Logger)) {
logger := build.NewSubLogger(subsystem, logWriter.GenSubLogger)
setSubLogger(subsystem, logger, useLogger)
}
// setSubLogger is a helper method to conveniently register the logger of a sub
// system.
func setSubLogger(subsystem string, logger btclog.Logger,
useLogger func(btclog.Logger)) {
func (logWriter) Write(p []byte) (n int, err error) { logWriter.RegisterSubLogger(subsystem, logger)
os.Stdout.Write(p) if useLogger != nil {
return len(p), nil useLogger(logger)
}
} }

@ -7,10 +7,9 @@ import (
"strings" "strings"
"sync" "sync"
flags "github.com/jessevdk/go-flags" "github.com/jessevdk/go-flags"
"github.com/btcsuite/btcutil"
"github.com/lightninglabs/loop" "github.com/lightninglabs/loop"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/lntypes"
) )
@ -19,7 +18,6 @@ const (
) )
var ( var (
loopDirBase = btcutil.AppDataDir("loop", false)
defaultConfigFilename = "loopd.conf" defaultConfigFilename = "loopd.conf"
swaps = make(map[lntypes.Hash]loop.SwapInfo) swaps = make(map[lntypes.Hash]loop.SwapInfo)
@ -81,8 +79,32 @@ func start() error {
os.Exit(0) os.Exit(0)
} }
// Special show command to list supported subsystems and exit.
if config.DebugLevel == "show" {
fmt.Printf("Supported subsystems: %v\n",
logWriter.SupportedSubsystems())
os.Exit(0)
}
// Append the network type to the log directory so it is
// "namespaced" per network in the same fashion as the data directory.
config.LogDir = filepath.Join(config.LogDir, config.Network)
// Initialize logging at the default logging level.
err = logWriter.InitLogRotator(
filepath.Join(config.LogDir, defaultLogFilename),
config.MaxLogFileSize, config.MaxLogFiles,
)
if err != nil {
return err
}
err = build.ParseAndSetDebugLevels(config.DebugLevel, logWriter)
if err != nil {
return err
}
// Print the version before executing either primary directive. // Print the version before executing either primary directive.
logger.Infof("Version: %v", loop.Version()) log.Infof("Version: %v", loop.Version())
// Execute command. // Execute command.
if parser.Active == nil { if parser.Active == nil {

@ -40,7 +40,7 @@ func (s *swapClientServer) LoopOut(ctx context.Context,
in *looprpc.LoopOutRequest) ( in *looprpc.LoopOutRequest) (
*looprpc.SwapResponse, error) { *looprpc.SwapResponse, error) {
logger.Infof("Loop out request received") log.Infof("Loop out request received")
sweepConfTarget, err := validateConfTarget( sweepConfTarget, err := validateConfTarget(
in.SweepConfTarget, loop.DefaultSweepConfTarget, in.SweepConfTarget, loop.DefaultSweepConfTarget,
@ -82,7 +82,7 @@ func (s *swapClientServer) LoopOut(ctx context.Context,
} }
hash, htlc, err := s.impl.LoopOut(ctx, req) hash, htlc, err := s.impl.LoopOut(ctx, req)
if err != nil { if err != nil {
logger.Errorf("LoopOut: %v", err) log.Errorf("LoopOut: %v", err)
return nil, err return nil, err
} }
@ -140,7 +140,7 @@ func (s *swapClientServer) marshallSwap(loopSwap *loop.SwapInfo) (
func (s *swapClientServer) Monitor(in *looprpc.MonitorRequest, func (s *swapClientServer) Monitor(in *looprpc.MonitorRequest,
server looprpc.SwapClient_MonitorServer) error { server looprpc.SwapClient_MonitorServer) error {
logger.Infof("Monitor request received") log.Infof("Monitor request received")
send := func(info loop.SwapInfo) error { send := func(info loop.SwapInfo) error {
rpcSwap, err := s.marshallSwap(&info) rpcSwap, err := s.marshallSwap(&info)
@ -234,11 +234,11 @@ func (s *swapClientServer) Monitor(in *looprpc.MonitorRequest,
func (s *swapClientServer) LoopOutTerms(ctx context.Context, func (s *swapClientServer) LoopOutTerms(ctx context.Context,
req *looprpc.TermsRequest) (*looprpc.TermsResponse, error) { req *looprpc.TermsRequest) (*looprpc.TermsResponse, error) {
logger.Infof("Loop out terms request received") log.Infof("Loop out terms request received")
terms, err := s.impl.LoopOutTerms(ctx) terms, err := s.impl.LoopOutTerms(ctx)
if err != nil { if err != nil {
logger.Errorf("Terms request: %v", err) log.Errorf("Terms request: %v", err)
return nil, err return nil, err
} }
@ -280,11 +280,11 @@ func (s *swapClientServer) LoopOutQuote(ctx context.Context,
func (s *swapClientServer) GetLoopInTerms(ctx context.Context, req *looprpc.TermsRequest) ( func (s *swapClientServer) GetLoopInTerms(ctx context.Context, req *looprpc.TermsRequest) (
*looprpc.TermsResponse, error) { *looprpc.TermsResponse, error) {
logger.Infof("Loop in terms request received") log.Infof("Loop in terms request received")
terms, err := s.impl.LoopInTerms(ctx) terms, err := s.impl.LoopInTerms(ctx)
if err != nil { if err != nil {
logger.Errorf("Terms request: %v", err) log.Errorf("Terms request: %v", err)
return nil, err return nil, err
} }
@ -298,7 +298,7 @@ func (s *swapClientServer) GetLoopInTerms(ctx context.Context, req *looprpc.Term
func (s *swapClientServer) GetLoopInQuote(ctx context.Context, func (s *swapClientServer) GetLoopInQuote(ctx context.Context,
req *looprpc.QuoteRequest) (*looprpc.QuoteResponse, error) { req *looprpc.QuoteRequest) (*looprpc.QuoteResponse, error) {
logger.Infof("Loop in quote request received") log.Infof("Loop in quote request received")
quote, err := s.impl.LoopInQuote(ctx, &loop.LoopInQuoteRequest{ quote, err := s.impl.LoopInQuote(ctx, &loop.LoopInQuoteRequest{
Amount: btcutil.Amount(req.Amt), Amount: btcutil.Amount(req.Amt),
@ -318,7 +318,7 @@ func (s *swapClientServer) LoopIn(ctx context.Context,
in *looprpc.LoopInRequest) ( in *looprpc.LoopInRequest) (
*looprpc.SwapResponse, error) { *looprpc.SwapResponse, error) {
logger.Infof("Loop in request received") log.Infof("Loop in request received")
req := &loop.LoopInRequest{ req := &loop.LoopInRequest{
Amount: btcutil.Amount(in.Amt), Amount: btcutil.Amount(in.Amt),
@ -332,7 +332,7 @@ func (s *swapClientServer) LoopIn(ctx context.Context,
} }
hash, htlc, err := s.impl.LoopIn(ctx, req) hash, htlc, err := s.impl.LoopIn(ctx, req)
if err != nil { if err != nil {
logger.Errorf("Loop in: %v", err) log.Errorf("Loop in: %v", err)
return nil, err return nil, err
} }

@ -59,7 +59,7 @@ func (s *executor) run(mainCtx context.Context,
// Before starting, make sure we have an up to date block height. // Before starting, make sure we have an up to date block height.
// Otherwise we might reveal a preimage for a swap that is already // Otherwise we might reveal a preimage for a swap that is already
// expired. // expired.
logger.Infof("Wait for first block ntfn") log.Infof("Wait for first block ntfn")
var height int32 var height int32
setHeight := func(h int32) { setHeight := func(h int32) {
@ -77,7 +77,7 @@ func (s *executor) run(mainCtx context.Context,
} }
// Start main event loop. // Start main event loop.
logger.Infof("Starting event loop at height %v", height) log.Infof("Starting event loop at height %v", height)
// Signal that executor being ready with an up to date block height. // Signal that executor being ready with an up to date block height.
close(s.ready) close(s.ready)

@ -253,7 +253,7 @@ func (s *lightningClient) payInvoice(ctx context.Context, invoice string,
// Paid successfully. // Paid successfully.
case PaymentResultSuccess: case PaymentResultSuccess:
logger.Infof( log.Infof(
"Payment %v completed", hash, "Payment %v completed", hash,
) )
@ -274,7 +274,7 @@ func (s *lightningClient) payInvoice(ctx context.Context, invoice string,
// Invoice was already paid on a previous run. // Invoice was already paid on a previous run.
case PaymentResultAlreadyPaid: case PaymentResultAlreadyPaid:
logger.Infof( log.Infof(
"Payment %v already completed", hash, "Payment %v already completed", hash,
) )
@ -294,7 +294,7 @@ func (s *lightningClient) payInvoice(ctx context.Context, invoice string,
// TODO: Improve this when lnd expose more API to // TODO: Improve this when lnd expose more API to
// tracking existing payments. // tracking existing payments.
case PaymentResultInFlight: case PaymentResultInFlight:
logger.Infof( log.Infof(
"Payment %v already in flight", hash, "Payment %v already in flight", hash,
) )
@ -302,7 +302,7 @@ func (s *lightningClient) payInvoice(ctx context.Context, invoice string,
// Other errors are transformed into an error struct. // Other errors are transformed into an error struct.
default: default:
logger.Warnf( log.Warnf(
"Payment %v failed: %v", hash, "Payment %v failed: %v", hash,
payResp.PaymentError, payResp.PaymentError,
) )

@ -84,13 +84,13 @@ func NewLndServices(lndAddress, application, network, macaroonDir,
} }
// Setup connection with lnd // Setup connection with lnd
logger.Infof("Creating lnd connection to %v", lndAddress) log.Infof("Creating lnd connection to %v", lndAddress)
conn, err := getClientConn(lndAddress, network, tlsPath) conn, err := getClientConn(lndAddress, network, tlsPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
logger.Infof("Connected to lnd") log.Infof("Connected to lnd")
chainParams, err := swap.ChainParamsFromNetwork(network) chainParams, err := swap.ChainParamsFromNetwork(network)
if err != nil { if err != nil {
@ -125,19 +125,19 @@ func NewLndServices(lndAddress, application, network, macaroonDir,
routerClient := newRouterClient(conn, macaroons.routerMac) routerClient := newRouterClient(conn, macaroons.routerMac)
cleanup := func() { cleanup := func() {
logger.Debugf("Closing lnd connection") log.Debugf("Closing lnd connection")
conn.Close() conn.Close()
logger.Debugf("Wait for client to finish") log.Debugf("Wait for client to finish")
lightningClient.WaitForFinished() lightningClient.WaitForFinished()
logger.Debugf("Wait for chain notifier to finish") log.Debugf("Wait for chain notifier to finish")
notifierClient.WaitForFinished() notifierClient.WaitForFinished()
logger.Debugf("Wait for invoices to finish") log.Debugf("Wait for invoices to finish")
invoicesClient.WaitForFinished() invoicesClient.WaitForFinished()
logger.Debugf("Lnd services finished") log.Debugf("Lnd services finished")
} }
services := &GrpcLndServices{ services := &GrpcLndServices{
@ -154,7 +154,7 @@ func NewLndServices(lndAddress, application, network, macaroonDir,
cleanup: cleanup, cleanup: cleanup,
} }
logger.Infof("Using network %v", network) log.Infof("Using network %v", network)
return services, nil return services, nil
} }
@ -164,7 +164,7 @@ func NewLndServices(lndAddress, application, network, macaroonDir,
func (s *GrpcLndServices) Close() { func (s *GrpcLndServices) Close() {
s.cleanup() s.cleanup()
logger.Debugf("Lnd services finished") log.Debugf("Lnd services finished")
} }
var ( var (

@ -1,24 +1,23 @@
package lndclient package lndclient
import ( import (
"os"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/lightningnetwork/lnd/build"
) )
// log is a logger that is initialized with no output filters. This // log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller // means the package will not perform any logging by default until the
// requests it. // caller requests it.
var ( var log btclog.Logger
backendLog = btclog.NewBackend(logWriter{})
logger = backendLog.Logger("LNDCLIENT")
)
// logWriter implements an io.Writer that outputs to both standard output and // The default amount of logging is none.
// the write-end pipe of an initialized log rotator. func init() {
type logWriter struct{} UseLogger(build.NewSubLogger("LNDC", nil))
}
func (logWriter) Write(p []byte) (n int, err error) { // UseLogger uses a specified Logger to output package logging info.
os.Stdout.Write(p) // This should be used in preference to SetLogWriter if the caller is also
return len(p), nil // using btclog.
func UseLogger(logger btclog.Logger) {
log = logger
} }

@ -1,24 +1,23 @@
package loop package loop
import ( import (
"os"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/lightningnetwork/lnd/build"
) )
// log is a logger that is initialized with no output filters. This // log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller // means the package will not perform any logging by default until the
// requests it. // caller requests it.
var ( var log btclog.Logger
backendLog = btclog.NewBackend(logWriter{})
logger = backendLog.Logger("CLIENT")
)
// logWriter implements an io.Writer that outputs to both standard output and // The default amount of logging is none.
// the write-end pipe of an initialized log rotator. func init() {
type logWriter struct{} UseLogger(build.NewSubLogger("LOOP", nil))
}
func (logWriter) Write(p []byte) (n int, err error) { // UseLogger uses a specified Logger to output package logging info.
os.Stdout.Write(p) // This should be used in preference to SetLogWriter if the caller is also
return len(p), nil // using btclog.
func UseLogger(logger btclog.Logger) {
log = logger
} }

@ -1,21 +1,23 @@
package loopdb package loopdb
import ( import (
"os"
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
"github.com/lightningnetwork/lnd/build"
) )
var ( // log is a logger that is initialized with no output filters. This
backendLog = btclog.NewBackend(logWriter{}) // means the package will not perform any logging by default until the
log = backendLog.Logger("STORE") // caller requests it.
) var log btclog.Logger
// logWriter implements an io.Writer that outputs to both standard output and // The default amount of logging is none.
// the write-end pipe of an initialized log rotator. func init() {
type logWriter struct{} UseLogger(build.NewSubLogger("STORE", nil))
}
func (logWriter) Write(p []byte) (n int, err error) { // UseLogger uses a specified Logger to output package logging info.
os.Stdout.Write(p) // This should be used in preference to SetLogWriter if the caller is also
return len(p), nil // using btclog.
func UseLogger(logger btclog.Logger) {
log = logger
} }

@ -67,7 +67,7 @@ func newLoopInSwap(globalCtx context.Context, cfg *swapConfig,
swapFee := quote.SwapFee swapFee := quote.SwapFee
if swapFee > request.MaxSwapFee { if swapFee > request.MaxSwapFee {
logger.Warnf("Swap fee %v exceeding maximum of %v", log.Warnf("Swap fee %v exceeding maximum of %v",
swapFee, request.MaxSwapFee) swapFee, request.MaxSwapFee)
return nil, ErrSwapFeeTooHigh return nil, ErrSwapFeeTooHigh
@ -81,7 +81,7 @@ func newLoopInSwap(globalCtx context.Context, cfg *swapConfig,
// Generate random preimage. // Generate random preimage.
var swapPreimage lntypes.Preimage var swapPreimage lntypes.Preimage
if _, err := rand.Read(swapPreimage[:]); err != nil { if _, err := rand.Read(swapPreimage[:]); err != nil {
logger.Error("Cannot generate preimage") log.Error("Cannot generate preimage")
} }
swapHash := lntypes.Hash(sha256.Sum256(swapPreimage[:])) swapHash := lntypes.Hash(sha256.Sum256(swapPreimage[:]))
@ -111,7 +111,7 @@ func newLoopInSwap(globalCtx context.Context, cfg *swapConfig,
// Post the swap parameters to the swap server. The response contains // Post the swap parameters to the swap server. The response contains
// the server success key and the expiry height of the on-chain swap // the server success key and the expiry height of the on-chain swap
// htlc. // htlc.
logger.Infof("Initiating swap request at height %v", currentHeight) log.Infof("Initiating swap request at height %v", currentHeight)
swapResp, err := cfg.server.NewLoopInSwap(globalCtx, swapHash, swapResp, err := cfg.server.NewLoopInSwap(globalCtx, swapHash,
request.Amount, senderKey, swapInvoice, request.Amount, senderKey, swapInvoice,
) )
@ -179,7 +179,7 @@ func resumeLoopInSwap(reqContext context.Context, cfg *swapConfig,
hash := lntypes.Hash(sha256.Sum256(pend.Contract.Preimage[:])) hash := lntypes.Hash(sha256.Sum256(pend.Contract.Preimage[:]))
logger.Infof("Resuming loop in swap %v", hash) log.Infof("Resuming loop in swap %v", hash)
swapKit, err := newSwapKit( swapKit, err := newSwapKit(
hash, swap.TypeIn, cfg, &pend.Contract.SwapContract, hash, swap.TypeIn, cfg, &pend.Contract.SwapContract,

@ -52,7 +52,7 @@ func TestLoopInSuccess(t *testing.T) {
go func() { go func() {
err := swap.execute(context.Background(), ctx.cfg, height) err := swap.execute(context.Background(), ctx.cfg, height)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
errChan <- err errChan <- err
}() }()
@ -142,7 +142,7 @@ func TestLoopInTimeout(t *testing.T) {
go func() { go func() {
err := swap.execute(context.Background(), ctx.cfg, height) err := swap.execute(context.Background(), ctx.cfg, height)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
errChan <- err errChan <- err
}() }()
@ -289,7 +289,7 @@ func testLoopInResume(t *testing.T, state loopdb.SwapState, expired bool) {
go func() { go func() {
err := swap.execute(context.Background(), ctx.cfg, height) err := swap.execute(context.Background(), ctx.cfg, height)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
errChan <- err errChan <- err
}() }()

@ -61,7 +61,7 @@ func newLoopOutSwap(globalCtx context.Context, cfg *swapConfig,
// Generate random preimage. // Generate random preimage.
var swapPreimage [32]byte var swapPreimage [32]byte
if _, err := rand.Read(swapPreimage[:]); err != nil { if _, err := rand.Read(swapPreimage[:]); err != nil {
logger.Error("Cannot generate preimage") log.Error("Cannot generate preimage")
} }
swapHash := lntypes.Hash(sha256.Sum256(swapPreimage[:])) swapHash := lntypes.Hash(sha256.Sum256(swapPreimage[:]))
@ -77,7 +77,7 @@ func newLoopOutSwap(globalCtx context.Context, cfg *swapConfig,
// Post the swap parameters to the swap server. The response contains // Post the swap parameters to the swap server. The response contains
// the server revocation key and the swap and prepay invoices. // the server revocation key and the swap and prepay invoices.
logger.Infof("Initiating swap request at height %v", currentHeight) log.Infof("Initiating swap request at height %v", currentHeight)
swapResp, err := cfg.server.NewLoopOutSwap(globalCtx, swapHash, swapResp, err := cfg.server.NewLoopOutSwap(globalCtx, swapHash,
request.Amount, receiverKey, request.Amount, receiverKey,
@ -147,7 +147,7 @@ func resumeLoopOutSwap(reqContext context.Context, cfg *swapConfig,
hash := lntypes.Hash(sha256.Sum256(pend.Contract.Preimage[:])) hash := lntypes.Hash(sha256.Sum256(pend.Contract.Preimage[:]))
logger.Infof("Resuming loop out swap %v", hash) log.Infof("Resuming loop out swap %v", hash)
swapKit, err := newSwapKit( swapKit, err := newSwapKit(
hash, swap.TypeOut, cfg, &pend.Contract.SwapContract, hash, swap.TypeOut, cfg, &pend.Contract.SwapContract,
@ -309,7 +309,7 @@ func (s *loopOutSwap) executeSwap(globalCtx context.Context) error {
// Verify amount if preimage hasn't been revealed yet. // Verify amount if preimage hasn't been revealed yet.
if s.state != loopdb.StatePreimageRevealed && htlcValue < s.AmountRequested { if s.state != loopdb.StatePreimageRevealed && htlcValue < s.AmountRequested {
logger.Warnf("Swap amount too low, expected %v but received %v", log.Warnf("Swap amount too low, expected %v but received %v",
s.AmountRequested, htlcValue) s.AmountRequested, htlcValue)
s.state = loopdb.StateFailInsufficientValue s.state = loopdb.StateFailInsufficientValue
@ -494,7 +494,7 @@ func (s *loopOutSwap) waitForConfirmedHtlc(globalCtx context.Context) (
case notification := <-s.blockEpochChan: case notification := <-s.blockEpochChan:
s.height = notification.(int32) s.height = notification.(int32)
logger.Infof("Received block %v", s.height) log.Infof("Received block %v", s.height)
if checkMaxRevealHeightExceeded() { if checkMaxRevealHeightExceeded() {
return nil, nil return nil, nil
@ -690,21 +690,21 @@ func validateLoopOutContract(lnd *lndclient.LndServices,
swapFee := swapInvoiceAmt + prepayInvoiceAmt - request.Amount swapFee := swapInvoiceAmt + prepayInvoiceAmt - request.Amount
if swapFee > request.MaxSwapFee { if swapFee > request.MaxSwapFee {
logger.Warnf("Swap fee %v exceeding maximum of %v", log.Warnf("Swap fee %v exceeding maximum of %v",
swapFee, request.MaxSwapFee) swapFee, request.MaxSwapFee)
return ErrSwapFeeTooHigh return ErrSwapFeeTooHigh
} }
if prepayInvoiceAmt > request.MaxPrepayAmount { if prepayInvoiceAmt > request.MaxPrepayAmount {
logger.Warnf("Prepay amount %v exceeding maximum of %v", log.Warnf("Prepay amount %v exceeding maximum of %v",
prepayInvoiceAmt, request.MaxPrepayAmount) prepayInvoiceAmt, request.MaxPrepayAmount)
return ErrPrepayAmountTooHigh return ErrPrepayAmountTooHigh
} }
if response.expiry-height < MinLoopOutPreimageRevealDelta { if response.expiry-height < MinLoopOutPreimageRevealDelta {
logger.Warnf("Proposed expiry %v (delta %v) too soon", log.Warnf("Proposed expiry %v (delta %v) too soon",
response.expiry, response.expiry-height) response.expiry, response.expiry-height)
return ErrExpiryTooSoon return ErrExpiryTooSoon

@ -62,7 +62,7 @@ func TestLateHtlcPublish(t *testing.T) {
timerFactory: timerFactory, timerFactory: timerFactory,
}, height) }, height)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
errChan <- err errChan <- err
}() }()
@ -153,7 +153,7 @@ func TestCustomSweepConfTarget(t *testing.T) {
sweeper: sweeper, sweeper: sweeper,
}, ctx.Lnd.Height) }, ctx.Lnd.Height)
if err != nil { if err != nil {
logger.Error(err) log.Error(err)
} }
errChan <- err errChan <- err
}() }()

@ -44,7 +44,7 @@ func newSwapKit(hash lntypes.Hash, swapType swap.Type, cfg *swapConfig,
log := &swap.PrefixLog{ log := &swap.PrefixLog{
Hash: hash, Hash: hash,
Logger: logger, Logger: log,
} }
// Log htlc address for debugging. // Log htlc address for debugging.

@ -114,7 +114,7 @@ func createClientTestContext(t *testing.T,
runCtx, runCtx,
statusChan, statusChan,
) )
logger.Errorf("client run: %v", err) log.Errorf("client run: %v", err)
ctx.runErr <- err ctx.runErr <- err
}() }()

Loading…
Cancel
Save