Skip to content

Commit 0595a0a

Browse files
committed
Use logrus as the new logger instead of fmt.
1 parent 949d90b commit 0595a0a

File tree

13 files changed

+93
-62
lines changed

13 files changed

+93
-62
lines changed

cmd/datasource-csv/main.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"os"
99

1010
"github.com/clems4ever/go-graphkb/graphkb"
11+
"github.com/sirupsen/logrus"
1112
"github.com/spf13/cobra"
1213
"github.com/spf13/viper"
1314
)
@@ -24,7 +25,7 @@ func NewCSVSource(graphAPI *graphkb.GraphAPI) *CSVSource {
2425
csvSource.dataPath = viper.GetString("path")
2526

2627
if csvSource.dataPath == "" {
27-
log.Fatal(fmt.Errorf("Unable to detect CSV file path in configuration. Check patch configuration is provided"))
28+
logrus.Fatal("Unable to detect CSV file path in configuration. Check patch configuration is provided")
2829
}
2930

3031
csvSource.graphAPI = graphAPI
@@ -74,7 +75,7 @@ func (cs *CSVSource) Publish() error {
7475

7576
err = tx.Commit()
7677
if err == nil {
77-
fmt.Println("CSV data has been sent successfully")
78+
logrus.Info("CSV data has been sent successfully")
7879
}
7980
return err
8081
}
@@ -118,6 +119,6 @@ func main() {
118119
"Provide the path to the configuration file (required)")
119120

120121
if err := rootCmd.Execute(); err != nil {
121-
log.Fatal(err)
122+
logrus.Fatal(err)
122123
}
123124
}

cmd/go-graphkb/main.go

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ package main
33
import (
44
"context"
55
"fmt"
6-
"log"
76
"strings"
87
"time"
98

109
"github.com/clems4ever/go-graphkb/internal/database"
1110
"github.com/clems4ever/go-graphkb/internal/knowledge"
1211
"github.com/clems4ever/go-graphkb/internal/server"
12+
"github.com/sirupsen/logrus"
1313
"github.com/spf13/cobra"
1414
"github.com/spf13/viper"
1515
)
@@ -20,10 +20,10 @@ var Database *database.MariaDB
2020
// ConfigPath string
2121
var ConfigPath string
2222

23-
func main() {
24-
// Display the code line where log.Fatal appeared for troubleshooting
25-
log.SetFlags(log.LstdFlags | log.Lshortfile)
23+
// LogLevel the log level
24+
var LogLevel string
2625

26+
func main() {
2727
// Also read env variables prefixed with GRAPHKB_.
2828
viper.SetEnvPrefix("GRAPHKB")
2929
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
@@ -61,15 +61,32 @@ func main() {
6161
}
6262

6363
rootCmd.PersistentFlags().StringVar(&ConfigPath, "config", "config.yml", "Provide the path to the configuration file (required)")
64+
rootCmd.PersistentFlags().StringVar(&LogLevel, "log-level", "info", "The log level among 'debug', 'info', 'warn', 'error'")
6465

6566
cobra.OnInitialize(onInit)
6667

6768
rootCmd.AddCommand(cleanCmd, listenCmd, countCmd, readCmd, queryCmd)
6869
if err := rootCmd.Execute(); err != nil {
69-
log.Fatal(err)
70+
logrus.Fatal(err)
7071
}
7172
}
7273

74+
func logLevelParamToSeverity(level string) logrus.Level {
75+
switch level {
76+
case "debug":
77+
return logrus.DebugLevel
78+
case "info":
79+
return logrus.InfoLevel
80+
case "warn":
81+
return logrus.WarnLevel
82+
case "error":
83+
return logrus.ErrorLevel
84+
}
85+
logrus.Fatal("Provided level %s is not a valid option")
86+
// This should never be reached but needed by the compiler
87+
return logrus.InfoLevel
88+
}
89+
7390
func onInit() {
7491
viper.SetConfigFile(ConfigPath)
7592
viper.SetConfigType("yaml")
@@ -78,11 +95,13 @@ func onInit() {
7895
panic(fmt.Errorf("Cannot read configuration file from %s", ConfigPath))
7996
}
8097

81-
fmt.Println("Using config file:", viper.ConfigFileUsed())
98+
logrus.Info("Using config file: ", viper.ConfigFileUsed())
99+
logrus.SetLevel(logLevelParamToSeverity(LogLevel))
100+
logrus.Info("Using log severity: ", LogLevel)
82101

83102
dbName := viper.GetString("mariadb_database")
84103
if dbName == "" {
85-
log.Fatal("Please provide database_name option in your configuration file")
104+
logrus.Fatal("Please provide database_name option in your configuration file")
86105
}
87106
Database = database.NewMariaDB(
88107
viper.GetString("mariadb_username"),
@@ -95,26 +114,26 @@ func onInit() {
95114
func count(cmd *cobra.Command, args []string) {
96115
countAssets, err := Database.CountAssets()
97116
if err != nil {
98-
log.Fatal(err)
117+
logrus.Fatal(err)
99118
}
100119

101120
countRelations, err := Database.CountRelations()
102121
if err != nil {
103-
log.Fatal(err)
122+
logrus.Fatal(err)
104123
}
105124
fmt.Printf("%d assets\n%d relations\n", countAssets, countRelations)
106125
}
107126

108127
func flush(cmd *cobra.Command, args []string) {
109128
if err := Database.FlushAll(); err != nil {
110-
log.Fatal(err)
129+
logrus.Fatal(err)
111130
}
112-
fmt.Println("Successul flush")
131+
logrus.Info("Successul flush")
113132
}
114133

115134
func listen(cmd *cobra.Command, args []string) {
116135
if err := Database.InitializeSchema(); err != nil {
117-
log.Fatal(err)
136+
logrus.Fatal(err)
118137
}
119138

120139
listenInterface := viper.GetString("server_listen")
@@ -130,7 +149,7 @@ func read(cmd *cobra.Command, args []string) {
130149
g := knowledge.NewGraph()
131150
err := Database.ReadGraph(args[0], g)
132151
if err != nil {
133-
log.Fatal(err)
152+
logrus.Fatal(err)
134153
}
135154

136155
fmt.Printf("assets = %d\nrelations = %d\n", len(g.Assets()), len(g.Relations()))
@@ -144,15 +163,15 @@ func queryFunc(cmd *cobra.Command, args []string) {
144163

145164
r, err := q.Query(ctx, args[0])
146165
if err != nil {
147-
log.Fatal(err)
166+
logrus.Fatal(err)
148167
}
149168

150169
resultsCount := 0
151170
for r.Cursor.HasMore() {
152171
var m interface{}
153172
err := r.Cursor.Read(context.Background(), &m)
154173
if err != nil {
155-
log.Fatal(err)
174+
logrus.Fatal(err)
156175
}
157176

158177
doc := m.([]interface{})

internal/client/graph_api.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"time"
66

77
"github.com/clems4ever/go-graphkb/internal/knowledge"
8+
"github.com/sirupsen/logrus"
89
)
910

1011
// GraphAPI represent the graph API from a data source point of view
@@ -52,7 +53,7 @@ func NewGraphAPI(options GraphAPIOptions) *GraphAPI {
5253
// with previous version of it.
5354
func (gapi *GraphAPI) CreateTransaction() (*Transaction, error) {
5455
if gapi.currentGraph == nil {
55-
fmt.Println("transaction: fetching remote graph")
56+
logrus.Debug("transaction: fetching remote graph")
5657
g, err := gapi.ReadCurrentGraph()
5758
if err != nil {
5859
return nil, fmt.Errorf("create transaction: %w", err)
@@ -100,7 +101,7 @@ func (gapi *GraphAPI) CreateTransaction() (*Transaction, error) {
100101
transaction.onError = func(err error) {
101102
// there was an error, we don't know the remote graph state.
102103
// we clear the cached copy to refresh in on the next run.
103-
fmt.Println("transaction: clearing graph cache because of error:", err)
104+
logrus.Debug("transaction: clearing graph cache because of error:", err)
104105
gapi.currentGraph = nil
105106
}
106107

internal/client/transaction.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/clems4ever/go-graphkb/internal/knowledge"
1212
"github.com/clems4ever/go-graphkb/internal/schema"
1313
"github.com/clems4ever/go-graphkb/internal/utils"
14+
"github.com/sirupsen/logrus"
1415
)
1516

1617
// Transaction represent a transaction generating updates by diffing the provided graph against
@@ -62,7 +63,7 @@ func withRetryOnTooManyRequests(fn func() error, backoffFactor float64, maxRetri
6263
err := fn()
6364
if err != nil {
6465
backoffTime := time.Duration(int(math.Pow(backoffFactor, float64(trials)))) * delay
65-
fmt.Printf("Sleeping for %d seconds\n", backoffTime/time.Second)
66+
logrus.Info("Sleeping for %f seconds\n", backoffTime/time.Second)
6667
time.Sleep(backoffTime)
6768
} else {
6869
return nil
@@ -78,18 +79,18 @@ func withRetryOnTooManyRequests(fn func() error, backoffFactor float64, maxRetri
7879
func (cgt *Transaction) Commit() error {
7980
sg := cgt.newGraph.ExtractSchema()
8081

81-
fmt.Println("Start uploading the schema of the graph...")
82+
logrus.Debug("Start uploading the schema of the graph...")
8283
if err := cgt.client.UpdateSchema(sg); err != nil {
8384
err := fmt.Errorf("Unable to update the schema of the graph: %v", err)
8485
cgt.onError(err)
8586
return err
8687
}
8788

88-
fmt.Println("Finished uploading the schema of the graph...")
89+
logrus.Debug("Finished uploading the schema of the graph...")
8990

9091
bulk := knowledge.GenerateGraphUpdatesBulk(cgt.currentGraph, cgt.newGraph)
9192

92-
fmt.Println("Start uploading the graph...")
93+
logrus.Debug("Start uploading the graph...")
9394

9495
progress := pb.New(len(bulk.GetAssetRemovals()) + len(bulk.GetAssetUpserts()) + len(bulk.GetRelationRemovals()) + len(bulk.GetRelationUpserts()))
9596

@@ -103,7 +104,7 @@ func (cgt *Transaction) Commit() error {
103104

104105
chunkSize := cgt.chunkSize
105106

106-
fmt.Printf("Assets to be inserted=%d removed=%d, Relations to be inserted=%d removed=%d\n",
107+
logrus.Debug("Assets to be inserted=%d removed=%d, Relations to be inserted=%d removed=%d\n",
107108
len(bulk.GetAssetUpserts()), len(bulk.GetAssetRemovals()),
108109
len(bulk.GetRelationUpserts()), len(bulk.GetRelationRemovals()))
109110

@@ -192,7 +193,7 @@ func (cgt *Transaction) Commit() error {
192193
}
193194
}
194195

195-
fmt.Println("Finished uploading the graph...")
196+
logrus.Debug("Finished uploading the graph...")
196197

197198
cgt.onSuccess(cgt.newGraph)
198199
cgt.newGraph = knowledge.NewGraph()

internal/database/mariadb.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"encoding/json"
77
"fmt"
88
"hash/fnv"
9-
"log"
109
"reflect"
1110
"strconv"
1211
"time"
@@ -31,7 +30,7 @@ func NewMariaDB(username string, password string, host string, databaseName stri
3130
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@(%s)/%s?allowCleartextPasswords=%s", username, password,
3231
host, databaseName, strconv.FormatBool(allowCleartextPassword)))
3332
if err != nil {
34-
log.Fatal(err)
33+
logrus.Fatal(err)
3534
}
3635
db.SetMaxIdleConns(10)
3736
db.SetMaxOpenConns(10)
@@ -426,7 +425,7 @@ func (m *MariaDB) RemoveRelations(source string, relations []knowledge.Relation)
426425

427426
// ReadGraph read source subgraph
428427
func (m *MariaDB) ReadGraph(sourceName string, graph *knowledge.Graph) error {
429-
fmt.Printf("Start reading graph of data source with name %s\n", sourceName)
428+
logrus.Debugf("Start reading graph of data source with name %s", sourceName)
430429
sourceID, err := m.resolveSourceID(sourceName)
431430
if err != nil {
432431
return fmt.Errorf("Unable to resolve source ID from name %s: %v", sourceName, err)
@@ -507,7 +506,7 @@ WHERE abs.source_id = ?
507506
}
508507

509508
elapsed := time.Since(now)
510-
fmt.Printf("Read graph of data source with name %s in %fs\n", sourceName, elapsed.Seconds())
509+
logrus.Debugf("Read graph of data source with name %s in %fs\n", sourceName, elapsed.Seconds())
511510
return nil
512511
}
513512

@@ -607,7 +606,7 @@ func (m *MariaDB) Query(ctx context.Context, sql knowledge.SQLTranslation) (*kno
607606
// Query can take 35 seconds max before being aborted...
608607
sql.Query = fmt.Sprintf("SET STATEMENT max_statement_time=%f FOR %s", time.Until(deadline).Seconds()+5, sql.Query)
609608
}
610-
fmt.Println(sql.Query)
609+
logrus.Debug("Query to be executed: ", sql.Query)
611610

612611
rows, err := m.db.QueryContext(ctx, sql.Query)
613612
if err != nil {

internal/handlers/handler_query.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package handlers
33
import (
44
"context"
55
"encoding/json"
6-
"fmt"
76
"net/http"
87
"time"
98

@@ -38,8 +37,7 @@ func PostQuery(database knowledge.GraphDB, queryHistorizer history.Historizer) h
3837

3938
if requestBody.Query == "" {
4039
w.WriteHeader(http.StatusBadRequest)
41-
fmt.Println("Empty query parameter")
42-
_, err = w.Write([]byte("Empty query parameter"))
40+
_, err = w.Write([]byte("Empty 'query' parameter"))
4341
if err != nil {
4442
ReplyWithInternalError(w, err)
4543
}

internal/handlers/replies.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ package handlers
22

33
import (
44
"encoding/json"
5-
"fmt"
65
"net/http"
76

87
"github.com/clems4ever/go-graphkb/internal/schema"
8+
"github.com/sirupsen/logrus"
99
)
1010

1111
// ReplyWithSourceGraph sends a reply containing the schema graph
@@ -23,11 +23,21 @@ func ReplyWithSourceGraph(w http.ResponseWriter, sg *schema.SchemaGraph) {
2323

2424
// ReplyWithInternalError send response with internal error.
2525
func ReplyWithInternalError(w http.ResponseWriter, err error) {
26-
fmt.Println(err)
26+
logrus.Error(err)
2727
w.WriteHeader(http.StatusInternalServerError)
2828
_, werr := w.Write([]byte(err.Error()))
2929
if werr != nil {
30-
fmt.Println(werr)
30+
logrus.Error(werr)
31+
}
32+
}
33+
34+
// ReplyWithBadRequest send response with bad request.
35+
func ReplyWithBadRequest(w http.ResponseWriter, err error) {
36+
logrus.Error(err)
37+
w.WriteHeader(http.StatusBadRequest)
38+
_, werr := w.Write([]byte(err.Error()))
39+
if werr != nil {
40+
logrus.Error(werr)
3141
}
3242
}
3343

@@ -36,7 +46,7 @@ func ReplyWithUnauthorized(w http.ResponseWriter) {
3646
w.WriteHeader(http.StatusUnauthorized)
3747
_, werr := w.Write([]byte("Unauthorized"))
3848
if werr != nil {
39-
fmt.Println(werr)
49+
logrus.Error(werr)
4050
}
4151
}
4252

@@ -45,6 +55,6 @@ func ReplyWithTooManyRequests(w http.ResponseWriter) {
4555
w.WriteHeader(http.StatusTooManyRequests)
4656
_, werr := w.Write([]byte("Too Many Requests. Retry later."))
4757
if werr != nil {
48-
fmt.Println(werr)
58+
logrus.Error(werr)
4959
}
5060
}

0 commit comments

Comments
 (0)