Skip to content

Commit

Permalink
Added logging with slog (#232)
Browse files Browse the repository at this point in the history
* Added logging with `slog`

* Converted all log messages

* Prepare some testing
  • Loading branch information
oxisto authored Dec 12, 2023
1 parent 05f7f74 commit 74b31bc
Show file tree
Hide file tree
Showing 13 changed files with 128 additions and 81 deletions.
35 changes: 0 additions & 35 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,41 +18,6 @@
// integrated client.
package cli

import (
"fmt"
"os"
)

var cmdMap map[string]Command = make(map[string]Command)

// AddCommand adds a command using the specific symbol.
func AddCommand(symbol string, cmd Command) {
cmdMap[symbol] = cmd
}

// Session holds all necessary information about the current CLI session.
type Session struct {
}

// Run runs our CLI command, based on the args. We keep it very simple for now
// without any extra package, so we just take the first arg and see if if
// matches any of our commands
func Run(args []string) {
var (
cmd Command
ok bool
s *Session
)

// Create a new session. TODO(oxisto): We do not yet have auth, but in the
// future we need to fetch a token here
s = new(Session)

// Try to look up command in our command map
cmd, ok = cmdMap[args[1]]
if ok {
cmd.Exec(s, os.Args[1:]...)
} else {
fmt.Print("Command not found.\n")
}
}
9 changes: 4 additions & 5 deletions cli/commands/portfolio.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -59,7 +58,7 @@ func (l *ListPortfolioCmd) Run(s *cli.Session) error {
connect.NewRequest(&portfoliov1.ListPortfoliosRequest{}),
)
if err != nil {
log.Println(err)
return err
} else {
in := `This is a list of all portfolios.
`
Expand Down Expand Up @@ -121,7 +120,7 @@ func (cmd *CreatePortfolioCmd) Run(s *cli.Session) error {
return err
}

log.Println(res.Msg)
fmt.Println(res.Msg)
return nil
}

Expand All @@ -145,7 +144,7 @@ func (cmd *ShowPortfolioCmd) Run(s *cli.Session) error {
return err
}

log.Println(res.Msg)
fmt.Println(res.Msg)
return nil
}

Expand Down Expand Up @@ -259,7 +258,7 @@ func (cmd *ImportTransactionsCmd) Run(s *cli.Session) error {
return err
}

log.Println(res.Msg)
fmt.Println(res.Msg)
return nil
}

Expand Down
7 changes: 4 additions & 3 deletions cli/commands/securities.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ package commands

import (
"context"
"log"
"fmt"
"net/http"

"connectrpc.com/connect"
kongcompletion "github.com/jotaen/kong-completion"
"github.com/posener/complete"

"github.com/oxisto/money-gopher/cli"
portfoliov1 "github.com/oxisto/money-gopher/gen"
"github.com/oxisto/money-gopher/gen/portfoliov1connect"
"github.com/posener/complete"
)

type SecurityCmd struct {
Expand All @@ -49,7 +50,7 @@ func (cmd *ListSecuritiesCmd) Run(s *cli.Session) error {
return err
}

log.Println(res.Msg.Securities)
fmt.Println(res.Msg.Securities)
return nil
}

Expand Down
1 change: 1 addition & 0 deletions cmd/mgo/mgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

"github.com/alecthomas/kong"
kongcompletion "github.com/jotaen/kong-completion"

"github.com/oxisto/money-gopher/cli"
"github.com/oxisto/money-gopher/cli/commands"
)
Expand Down
56 changes: 46 additions & 10 deletions cmd/moneyd/moneyd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,62 @@
package main

import (
"log"
"log/slog"
"net/http"
"os"
"strings"
"time"

"github.com/alecthomas/kong"
"github.com/lmittmann/tint"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"

"github.com/oxisto/money-gopher/gen/portfoliov1connect"
"github.com/oxisto/money-gopher/persistence"
"github.com/oxisto/money-gopher/service/portfolio"
"github.com/oxisto/money-gopher/service/securities"

"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)

var cmd moneydCmd

type moneydCmd struct {
Debug bool `help:"Enable debug mode."`
}

func main() {
log.SetPrefix("[🤑] ")
log.SetFlags(log.Lmsgprefix | log.Ltime)
log.Print("Welcome to The Money Gopher")
log.SetOutput(colorable.NewColorableStdout())
ctx := kong.Parse(&cmd)

err := ctx.Run()
ctx.FatalIfErrorf(err)
}

func (cmd *moneydCmd) Run() error {
var (
w = os.Stdout
level = slog.LevelInfo
)

if cmd.Debug {
level = slog.LevelDebug
}

logger := slog.New(
tint.NewHandler(colorable.NewColorable(w), &tint.Options{
TimeFormat: time.TimeOnly,
Level: level,
NoColor: !isatty.IsTerminal(w.Fd()),
}),
)

slog.SetDefault(logger)
slog.Info("Welcome to the Money Gopher")

db, err := persistence.OpenDB(persistence.Options{})
if err != nil {
log.Fatalf("Error while opening database: %v", err)
slog.Error("Error while opening database", tint.Err(err))
}

mux := http.NewServeMux()
Expand All @@ -57,7 +90,10 @@ func main() {
"localhost:8080",
h2c.NewHandler(handleCORS(mux), &http2.Server{}),
)
log.Fatalf("listen failed: %v", err)

slog.Error("listen failed", tint.Err(err))

return err
}

func handleCORS(h http.Handler) http.Handler {
Expand Down
9 changes: 9 additions & 0 deletions gen/portfolio.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"hash/fnv"
"strconv"
"time"
"log/slog"
)

func (p *Portfolio) EventMap() (m map[string][]*PortfolioEvent) {
Expand Down Expand Up @@ -48,3 +49,11 @@ func (tx *PortfolioEvent) MakeUniqueName() {

tx.Name = strconv.FormatUint(h.Sum64(), 16)
}

// LogValue implements slog.LogValuer.
func (ls *ListedSecurity) LogValue() slog.Value {
return slog.GroupValue(
slog.String("name", ls.SecurityName),
slog.String("ticker", ls.Ticker),
)
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ require (
github.com/alecthomas/kong v0.8.1
github.com/fatih/color v1.16.0
github.com/jotaen/kong-completion v0.0.6
github.com/lmittmann/tint v1.0.3
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.20
github.com/mattn/go-sqlite3 v1.14.18
github.com/oxisto/assert v0.0.6
github.com/posener/complete v1.2.3
Expand All @@ -17,7 +19,6 @@ require (
)

require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/riywo/loginshell v0.0.0-20200815045211-7d26008be1ab // indirect
golang.org/x/sys v0.15.0 // indirect
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/jotaen/kong-completion v0.0.6 h1:VP1KGvXPeB7MytYR+zZQoWw1gf/HIV1/EvWC38BHZN4=
github.com/jotaen/kong-completion v0.0.6/go.mod h1:fuWw9snL6joY5mXbI0Dd5FWEZODaWXAeqaRxo6dAvLk=
github.com/lmittmann/tint v1.0.3 h1:W5PHeA2D8bBJVvabNfQD/XW9HPLZK1XoPZH0cq8NouQ=
github.com/lmittmann/tint v1.0.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand Down
5 changes: 3 additions & 2 deletions import/csv/csv_importer.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"slices"
"strconv"
"strings"
"time"

"github.com/lmittmann/tint"
moneygopher "github.com/oxisto/money-gopher"
portfoliov1 "github.com/oxisto/money-gopher/gen"
"github.com/oxisto/money-gopher/service/securities"
Expand Down Expand Up @@ -72,7 +73,7 @@ func Import(r io.Reader, pname string) (txs []*portfoliov1.PortfolioEvent, secs
break
} else if err != nil {
// Skip this transaction
log.Printf("Could not parse line: %v\n", err)
slog.Warn("Could not parse line", tint.Err(err))
continue
}

Expand Down
3 changes: 3 additions & 0 deletions money-gopher.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
"cSpell.words": [
"Banse",
"bufbuild",
"connectrpc",
"emptypb",
"fieldmaskpb",
"headlessui",
"heroicons",
"isatty",
"ISIN",
"jotaen",
"kongcompletion",
"lmittmann",
"modernc",
"moneyd",
"moneygopher",
Expand Down
29 changes: 13 additions & 16 deletions persistence/persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ import (
"database/sql"
"errors"
"fmt"
"log"
"os"
"log/slog"
"strings"

_ "github.com/mattn/go-sqlite3"
Expand All @@ -37,13 +36,18 @@ type Options struct {
DSN string
}

// LogValue implements slog.LogValuer.
func (o Options) LogValue() slog.Value {
return slog.GroupValue(
slog.Bool("in-memory", o.UseInMemory),
slog.String("dsn", o.DSN))
}

// DB is a wrapper around [sql.DB]. This allows us to access all the
// functionalities of [sql.DB] as well as accessing the DB object in our
// internal functions.
type DB struct {
*sql.DB

log *log.Logger
}

type StorageObject interface {
Expand Down Expand Up @@ -88,13 +92,11 @@ func OpenDB(opts Options) (db *DB, err error) {
}

db = &DB{
DB: inner,
log: log.New(os.Stderr, "", log.Lmsgprefix|log.Ltime),
DB: inner,
}
db.log.SetPrefix("[📄] ")
db.initTables()

db.log.Print("Successfully opened database connection")
slog.Info("Successfully opened database connection", "opts", opts)

return
}
Expand Down Expand Up @@ -125,11 +127,10 @@ func (ops *ops[T]) Replace(o StorageObject) (err error) {
return fmt.Errorf("could not execute query: %w", err)
}

rows, err := res.RowsAffected()
_, err = res.RowsAffected()
if err != nil {
return fmt.Errorf("could not fetch number of affected rows: %w", err)
}
ops.DB.log.Printf("%d row(s) affected by replace", rows)

return nil
}
Expand Down Expand Up @@ -228,13 +229,11 @@ func (ops *ops[T]) Update(key any, in T, columns []string) (out T, err error) {
return out, fmt.Errorf("could not execute query: %w", err)
}

rows, err := res.RowsAffected()
_, err = res.RowsAffected()
if err != nil {
return out, fmt.Errorf("could not fetch number of affected rows: %w", err)
}

ops.DB.log.Printf("%d row(s) affected by replace", rows)

// Need to fetch it again
return ops.Get(key)
}
Expand All @@ -255,13 +254,11 @@ func (ops *ops[T]) Delete(key any) (err error) {
return fmt.Errorf("could not execute query: %w", err)
}

rows, err := res.RowsAffected()
_, err = res.RowsAffected()
if err != nil {
return fmt.Errorf("could not fetch number of affected rows: %w", err)
}

ops.DB.log.Printf("%d row(s) affected by delete", rows)

return
}

Expand Down
Loading

0 comments on commit 74b31bc

Please sign in to comment.