Use log instead of fmt for logging

Also fix up a few errors to lower case
This commit is contained in:
Marc Di Luzio 2020-06-11 19:04:53 +01:00
parent 1cafd4f2ce
commit 2f5863b17a
10 changed files with 49 additions and 47 deletions

View file

@ -42,7 +42,7 @@ func (a *Accountant) RegisterAccount(name string) (acc Account, err error) {
// Verify this acount isn't already registered // Verify this acount isn't already registered
for _, a := range a.Accounts { for _, a := range a.Accounts {
if a.Name == acc.Name { if a.Name == acc.Name {
return Account{}, fmt.Errorf("Account name already registered") return Account{}, fmt.Errorf("account name already registered")
} }
} }

View file

@ -31,15 +31,15 @@ func (a *accountantServer) Register(ctx context.Context, in *accounts.RegisterIn
defer a.sync.Unlock() defer a.sync.Unlock()
// Try and register the account itself // Try and register the account itself
fmt.Printf("Registering account: %s\n", in.Name) log.Printf("Registering account: %s\n", in.Name)
if _, err := a.accountant.RegisterAccount(in.Name); err != nil { if _, err := a.accountant.RegisterAccount(in.Name); err != nil {
fmt.Printf("Error: %s\n", err) log.Printf("Error: %s\n", err)
return &accounts.RegisterResponse{Success: false, Error: fmt.Sprintf("error registering account: %s", err)}, nil return &accounts.RegisterResponse{Success: false, Error: fmt.Sprintf("error registering account: %s", err)}, nil
} }
// Save out the accounts // Save out the accounts
if err := persistence.Save("accounts", a.accountant); err != nil { if err := persistence.Save("accounts", a.accountant); err != nil {
fmt.Printf("Error: %s\n", err) log.Printf("Error: %s\n", err)
return &accounts.RegisterResponse{Success: false, Error: fmt.Sprintf("failed to save accounts: %s", err)}, nil return &accounts.RegisterResponse{Success: false, Error: fmt.Sprintf("failed to save accounts: %s", err)}, nil
} }
@ -52,10 +52,10 @@ func (a *accountantServer) AssignValue(_ context.Context, in *accounts.DataKeyVa
defer a.sync.RUnlock() defer a.sync.RUnlock()
// Try and assign the data // Try and assign the data
fmt.Printf("Assigning value for account %s: %s->%s\n", in.Account, in.Key, in.Value) log.Printf("Assigning value for account %s: %s->%s\n", in.Account, in.Key, in.Value)
err := a.accountant.AssignData(in.Account, in.Key, in.Value) err := a.accountant.AssignData(in.Account, in.Key, in.Value)
if err != nil { if err != nil {
fmt.Printf("Error: %s\n", err) log.Printf("Error: %s\n", err)
return &accounts.Response{Success: false, Error: err.Error()}, nil return &accounts.Response{Success: false, Error: err.Error()}, nil
} }
@ -69,10 +69,10 @@ func (a *accountantServer) GetValue(_ context.Context, in *accounts.DataKey) (*a
defer a.sync.RUnlock() defer a.sync.RUnlock()
// Try and fetch the rover // Try and fetch the rover
fmt.Printf("Getting value for account %s: %s\n", in.Account, in.Key) log.Printf("Getting value for account %s: %s\n", in.Account, in.Key)
data, err := a.accountant.GetValue(in.Account, in.Key) data, err := a.accountant.GetValue(in.Account, in.Key)
if err != nil { if err != nil {
fmt.Printf("Error: %s\n", err) log.Printf("Error: %s\n", err)
return &accounts.DataResponse{Success: false, Error: err.Error()}, nil return &accounts.DataResponse{Success: false, Error: err.Error()}, nil
} }
@ -110,12 +110,12 @@ func main() {
signal.Notify(c, os.Interrupt, syscall.SIGTERM) signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() { go func() {
<-c <-c
fmt.Println("Quit requested, exiting...") log.Println("Quit requested, exiting...")
grpcServer.Stop() grpcServer.Stop()
}() }()
// Serve the RPC server // Serve the RPC server
fmt.Printf("Serving accountant on %s\n", address) log.Printf("Serving accountant on %s\n", address)
if err := grpcServer.Serve(lis); err != nil { if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to server gRPC: %s", err) log.Fatalf("failed to server gRPC: %s", err)
} }

View file

@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log"
"net/http" "net/http"
"time" "time"
@ -82,7 +83,7 @@ func HandleRegister(s *Server, vars map[string]string, b io.ReadCloser, w io.Wri
var data rove.RegisterData var data rove.RegisterData
err := json.NewDecoder(b).Decode(&data) err := json.NewDecoder(b).Decode(&data)
if err != nil { if err != nil {
fmt.Printf("Failed to decode json: %s\n", err) log.Printf("Failed to decode json: %s\n", err)
response.Error = err.Error() response.Error = err.Error()
} else if len(data.Name) == 0 { } else if len(data.Name) == 0 {
@ -109,7 +110,7 @@ func HandleRegister(s *Server, vars map[string]string, b io.ReadCloser, w io.Wri
response.Success = true response.Success = true
} }
fmt.Printf("register response:%+v\n", response) log.Printf("register response:%+v\n", response)
return response, nil return response, nil
} }
@ -124,7 +125,7 @@ func HandleCommand(s *Server, vars map[string]string, b io.ReadCloser, w io.Writ
// Decode the commands, verify them and the account, and execute the commands // Decode the commands, verify them and the account, and execute the commands
var data rove.CommandData var data rove.CommandData
if err := json.NewDecoder(b).Decode(&data); err != nil { if err := json.NewDecoder(b).Decode(&data); err != nil {
fmt.Printf("Failed to decode json: %s\n", err) log.Printf("Failed to decode json: %s\n", err)
response.Error = err.Error() response.Error = err.Error()
} }
@ -151,7 +152,7 @@ func HandleCommand(s *Server, vars map[string]string, b io.ReadCloser, w io.Writ
response.Success = true response.Success = true
} }
fmt.Printf("command response \taccount:%s\tresponse:%+v\n", id, response) log.Printf("command response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil return response, nil
} }
@ -189,7 +190,7 @@ func HandleRadar(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer
response.Success = true response.Success = true
} }
fmt.Printf("radar response \taccount:%s\tresponse:%+v\n", id, response) log.Printf("radar response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil return response, nil
} }
@ -223,6 +224,6 @@ func HandleRover(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer
response.Success = true response.Success = true
} }
fmt.Printf("rover response \taccount:%s\tresponse:%+v\n", id, response) log.Printf("rover response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil return response, nil
} }

View file

@ -116,7 +116,7 @@ func (s *Server) Initialise(fillWorld bool) (err error) {
s.sync.Add(1) s.sync.Add(1)
// Connect to the accountant // Connect to the accountant
fmt.Printf("Dialing accountant on %s\n", accountantAddress) log.Printf("Dialing accountant on %s\n", accountantAddress)
s.clientConn, err = grpc.Dial(accountantAddress, grpc.WithInsecure()) s.clientConn, err = grpc.Dial(accountantAddress, grpc.WithInsecure())
if err != nil { if err != nil {
return err return err
@ -139,7 +139,7 @@ func (s *Server) Initialise(fillWorld bool) (err error) {
} }
// Start the listen // Start the listen
fmt.Printf("Listening on %s\n", s.server.Addr) log.Printf("Listening on %s\n", s.server.Addr)
if s.listener, err = net.Listen("tcp", s.server.Addr); err != nil { if s.listener, err = net.Listen("tcp", s.server.Addr); err != nil {
return err return err
} }
@ -164,7 +164,7 @@ func (s *Server) Run() {
s.sync.Add(1) s.sync.Add(1)
defer s.sync.Done() defer s.sync.Done()
fmt.Println("Executing server tick") log.Println("Executing server tick")
// Run the command queues // Run the command queues
s.world.ExecuteCommandQueues() s.world.ExecuteCommandQueues()
@ -175,7 +175,7 @@ func (s *Server) Run() {
log.Fatal(err) log.Fatal(err)
} }
s.schedule.Start() s.schedule.Start()
fmt.Printf("First server tick scheduled for %s\n", s.schedule.Entries()[0].Next.Format("15:04:05")) log.Printf("First server tick scheduled for %s\n", s.schedule.Entries()[0].Next.Format("15:04:05"))
} }
// Serve the http requests // Serve the http requests
@ -252,7 +252,7 @@ func (s *Server) LoadWorld() error {
func (s *Server) wrapHandler(method string, handler Handler) func(w http.ResponseWriter, r *http.Request) { func (s *Server) wrapHandler(method string, handler Handler) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
// Log the request // Log the request
fmt.Printf("%s\t%s\n", r.Method, r.RequestURI) log.Printf("%s\t%s\n", r.Method, r.RequestURI)
vars := mux.Vars(r) vars := mux.Vars(r)
@ -261,11 +261,11 @@ func (s *Server) wrapHandler(method string, handler Handler) func(w http.Respons
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
} else if val, err := handler(s, vars, r.Body, w); err != nil { } else if val, err := handler(s, vars, r.Body, w); err != nil {
fmt.Printf("Failed to handle http request: %s", err) log.Printf("Failed to handle http request: %s", err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
} else if err := json.NewEncoder(w).Encode(val); err != nil { } else if err := json.NewEncoder(w).Encode(val); err != nil {
fmt.Printf("Failed to encode reply to json: %s", err) log.Printf("Failed to encode reply to json: %s", err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
} else { } else {
@ -280,17 +280,17 @@ func (s *Server) SpawnRoverForAccount(account string) (game.RoverAttributes, uui
return game.RoverAttributes{}, uuid.UUID{}, err return game.RoverAttributes{}, uuid.UUID{}, err
} else if attribs, err := s.world.RoverAttributes(inst); err != nil { } else if attribs, err := s.world.RoverAttributes(inst); err != nil {
return game.RoverAttributes{}, uuid.UUID{}, fmt.Errorf("No attributes found for created rover: %s", err) return game.RoverAttributes{}, uuid.UUID{}, fmt.Errorf("no attributes found for created rover: %s", err)
} else { } else {
keyval := accounts.DataKeyValue{Account: account, Key: "rover", Value: inst.String()} keyval := accounts.DataKeyValue{Account: account, Key: "rover", Value: inst.String()}
resp, err := s.accountant.AssignValue(context.Background(), &keyval) resp, err := s.accountant.AssignValue(context.Background(), &keyval)
if err != nil || !resp.Success { if err != nil || !resp.Success {
fmt.Printf("Failed to assign rover to account, %s, %s", err, resp.Error) log.Printf("Failed to assign rover to account, %s, %s", err, resp.Error)
// Try and clear up the rover // Try and clear up the rover
if err := s.world.DestroyRover(inst); err != nil { if err := s.world.DestroyRover(inst); err != nil {
fmt.Printf("Failed to destroy rover after failed rover assign: %s", err) log.Printf("Failed to destroy rover after failed rover assign: %s", err)
} }
return game.RoverAttributes{}, uuid.UUID{}, err return game.RoverAttributes{}, uuid.UUID{}, err

View file

@ -2,7 +2,6 @@ package main
import ( import (
"flag" "flag"
"fmt"
"log" "log"
"os" "os"
"os/signal" "os/signal"
@ -32,11 +31,11 @@ func InnerMain() {
// Print the version if requested // Print the version if requested
if *ver { if *ver {
fmt.Println(version.Version) log.Println(version.Version)
return return
} }
fmt.Printf("Initialising version %s...\n", version.Version) log.Printf("Initialising version %s...\n", version.Version)
// Set the persistence path // Set the persistence path
persistence.SetPath(data) persistence.SetPath(data)
@ -67,7 +66,7 @@ func InnerMain() {
signal.Notify(c, os.Interrupt, syscall.SIGTERM) signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() { go func() {
<-c <-c
fmt.Println("Quit requested, exiting...") log.Println("Quit requested, exiting...")
if err := s.Stop(); err != nil { if err := s.Stop(); err != nil {
panic(err) panic(err)
} }
@ -82,7 +81,7 @@ func InnerMain() {
} }
// Run the server // Run the server
fmt.Printf("Serving HTTP on %s\n", s.Addr()) log.Printf("Serving HTTP on %s\n", s.Addr())
s.Run() s.Run()
// Close the server // Close the server

View file

@ -125,7 +125,7 @@ func InnerMain(command string) error {
return err return err
case !response.Success: case !response.Success:
return fmt.Errorf("Server returned failure: %s", response.Error) return fmt.Errorf("server returned failure: %s", response.Error)
default: default:
fmt.Printf("Registered account with id: %s\n", *name) fmt.Printf("Registered account with id: %s\n", *name)
@ -153,7 +153,7 @@ func InnerMain(command string) error {
return err return err
case !response.Success: case !response.Success:
return fmt.Errorf("Server returned failure: %s", response.Error) return fmt.Errorf("server returned failure: %s", response.Error)
default: default:
fmt.Printf("Request succeeded\n") fmt.Printf("Request succeeded\n")
@ -170,7 +170,7 @@ func InnerMain(command string) error {
return err return err
case !response.Success: case !response.Success:
return fmt.Errorf("Server returned failure: %s", response.Error) return fmt.Errorf("server returned failure: %s", response.Error)
default: default:
// Print out the radar // Print out the radar
@ -188,7 +188,7 @@ func InnerMain(command string) error {
return err return err
case !response.Success: case !response.Success:
return fmt.Errorf("Server returned failure: %s", response.Error) return fmt.Errorf("server returned failure: %s", response.Error)
default: default:
fmt.Printf("attributes: %+v\n", response.Attributes) fmt.Printf("attributes: %+v\n", response.Attributes)

View file

@ -56,7 +56,7 @@ func FromString(s string) (Bearing, error) {
return Bearing(i), nil return Bearing(i), nil
} }
} }
return -1, fmt.Errorf("Unknown bearing: %s", s) return -1, fmt.Errorf("unknown bearing: %s", s)
} }
var bearingVectors = []vector.Vector{ var bearingVectors = []vector.Vector{

View file

@ -174,7 +174,7 @@ func (a *Atlas) Grow(size int) error {
} }
delta := size - a.Size delta := size - a.Size
if delta < 0 { if delta < 0 {
return fmt.Errorf("Cannot shrink an atlas") return fmt.Errorf("cannot shrink an atlas")
} else if delta == 0 { } else if delta == 0 {
return nil return nil
} }

View file

@ -2,6 +2,7 @@ package game
import ( import (
"fmt" "fmt"
"log"
"math" "math"
"math/rand" "math/rand"
"strings" "strings"
@ -101,7 +102,7 @@ func (w *World) SpawnRover() (uuid.UUID, error) {
return uuid.Nil, err return uuid.Nil, err
} }
fmt.Printf("Spawned rover at %+v\n", rover.Attributes.Pos) log.Printf("Spawned rover at %+v\n", rover.Attributes.Pos)
// Append the rover to the list // Append the rover to the list
w.Rovers[rover.Id] = rover w.Rovers[rover.Id] = rover
@ -167,7 +168,7 @@ func (w *World) WarpRover(id uuid.UUID, pos vector.Vector) error {
if tile, err := w.Atlas.GetTile(pos); err != nil { if tile, err := w.Atlas.GetTile(pos); err != nil {
return fmt.Errorf("coudln't get state of destination rover tile: %s", err) return fmt.Errorf("coudln't get state of destination rover tile: %s", err)
} else if tile == TileRover { } else if tile == TileRover {
return fmt.Errorf("Can't warp rover to occupied tile, check before warping") return fmt.Errorf("can't warp rover to occupied tile, check before warping")
} else if err := w.Atlas.SetTile(pos, TileRover); err != nil { } else if err := w.Atlas.SetTile(pos, TileRover); err != nil {
return fmt.Errorf("coudln't set rover tile: %s", err) return fmt.Errorf("coudln't set rover tile: %s", err)
} else if err := w.Atlas.SetTile(i.Attributes.Pos, TileEmpty); err != nil { } else if err := w.Atlas.SetTile(i.Attributes.Pos, TileEmpty); err != nil {
@ -328,7 +329,7 @@ func (w *World) ExecuteCommandQueues() {
// Execute the command and clear up if requested // Execute the command and clear up if requested
if done, err := w.ExecuteCommand(&c, rover); err != nil { if done, err := w.ExecuteCommand(&c, rover); err != nil {
w.CommandQueue[rover] = cmds[1:] w.CommandQueue[rover] = cmds[1:]
fmt.Println(err) log.Println(err)
} else if done { } else if done {
w.CommandQueue[rover] = cmds[1:] w.CommandQueue[rover] = cmds[1:]
} else { } else {
@ -349,7 +350,7 @@ func (w *World) ExecuteCommandQueues() {
// ExecuteCommand will execute a single command // ExecuteCommand will execute a single command
func (w *World) ExecuteCommand(c *Command, rover uuid.UUID) (finished bool, err error) { func (w *World) ExecuteCommand(c *Command, rover uuid.UUID) (finished bool, err error) {
fmt.Printf("Executing command: %+v\n", *c) log.Printf("Executing command: %+v\n", *c)
switch c.Command { switch c.Command {
case "move": case "move":
@ -380,7 +381,7 @@ func PrintTiles(tiles []Tile) {
num := int(math.Sqrt(float64(len(tiles)))) num := int(math.Sqrt(float64(len(tiles))))
for j := num - 1; j >= 0; j-- { for j := num - 1; j >= 0; j-- {
for i := 0; i < num; i++ { for i := 0; i < num; i++ {
fmt.Printf("%d", tiles[i+num*j]) log.Printf("%d", tiles[i+num*j])
} }
fmt.Print("\n") fmt.Print("\n")
} }

View file

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"path" "path"
) )
@ -38,7 +39,7 @@ func Save(name string, data interface{}) error {
} }
} }
fmt.Printf("Saved %s\n", p) log.Printf("Saved %s\n", p)
return nil return nil
} }
@ -48,7 +49,7 @@ func Load(name string, data interface{}) error {
// Don't load anything if the file doesn't exist // Don't load anything if the file doesn't exist
_, err := os.Stat(p) _, err := os.Stat(p)
if os.IsNotExist(err) { if os.IsNotExist(err) {
fmt.Printf("File %s didn't exist, loading with fresh data\n", p) log.Printf("File %s didn't exist, loading with fresh data\n", p)
return nil return nil
} }
@ -56,13 +57,13 @@ func Load(name string, data interface{}) error {
if b, err := ioutil.ReadFile(p); err != nil { if b, err := ioutil.ReadFile(p); err != nil {
return err return err
} else if len(b) == 0 { } else if len(b) == 0 {
fmt.Printf("File %s was empty, loading with fresh data\n", p) log.Printf("File %s was empty, loading with fresh data\n", p)
return nil return nil
} else if err := json.Unmarshal(b, data); err != nil { } else if err := json.Unmarshal(b, data); err != nil {
return fmt.Errorf("failed to load file %s error: %s", p, err) return fmt.Errorf("failed to load file %s error: %s", p, err)
} }
fmt.Printf("Loaded %s\n", p) log.Printf("Loaded %s\n", p)
return nil return nil
} }
@ -76,7 +77,7 @@ func doAll(f saveLoadFunc, args ...interface{}) error {
var ok bool var ok bool
name, ok = a.(string) name, ok = a.(string)
if !ok { if !ok {
return fmt.Errorf("Incorrect args") return fmt.Errorf("incorrect args")
} }
} else { } else {
if err := f(name, a); err != nil { if err := f(name, a); err != nil {