Skip to content

Commit ecf84ba

Browse files
bietkulsiddharthlatest
authored andcommitted
feat: improve logging with logrus (#60)
* fix: users test * feat: add expired value in permissions * fix: revert isExpired method changes * fix: minor fixes * feat: better logs with logrus * fix: error logging * fix: set default log level to error * Update README.md
1 parent 6e21be1 commit ecf84ba

42 files changed

Lines changed: 294 additions & 214 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,39 +80,56 @@ You can build the binary locally by executing the following command from the pro
8080

8181
This produces an executable & plugin libraries in the root project directory. To start the Arc server, run:
8282

83-
./build/arc --log=stdout --env=config/manual.env
83+
./build/arc --env=config/manual.env
8484

8585
Alternatively, you could execute the following commands to start the server without producing an executable, (but still produce the plugin libraries):
8686

8787
make plugins
88-
go run main.go --log=stdout --env=config/manual.env
88+
go run main.go --env=config/manual.env
89+
8990

9091
**Note**: Running the executable assumes an active Elasticsearch connection whose url is to be provided in the `.env` file. manual.env configures it to be the localhost.
9192

93+
### Logging
94+
Define the run time flag (`log`) to change the default log mode, the possible options are:
95+
96+
#### debug
97+
Most verbose, use this to get logs for elasticsearch interactions.
98+
#### info
99+
Prints the basic information
100+
#### error (default)
101+
Only log the errors
102+
92103
#### TLS Support
93104

94105
You can optionally start arc to serve https requests instead of http requests using the flag https.
95106
You also need to provide the server key & certificate file location through the environment file.
96107
manual.env is configured to use demo server key & certificates, which work for localhost.
108+
```bash
97109
go run main.go --log=stdout --env=config/manual.env --https
98-
110+
```
99111
If you wish to manually test TLS support at localhost,
100112
curl needs to be also passed an extra parameter providing the cacert, in this case.
113+
```bash
101114
curl https://foo:bar@localhost:8000/_user --cacert sample/rootCA.pem
115+
```
102116

103117
#### JWT Key Loading through HTTP
104118

105119
If you wish to test loading JWT Key through HTTP, you can use the following commands to start a HTTP
106120
server serving the key
121+
```bash
107122
cd sample
108123
python -m SimpleHTTPServer 8500
109-
124+
```
110125
Then start arc using the command:
126+
```bash
111127
go run main.go --log=stdout --env=config/manual-http-jwt.env
128+
```
112129

113130
#### Run Tests
114131

115-
Currently, tests are WIP and implemented for auth and logs modules. You can run tests using:
132+
Currently, tests are WIP and implemented for auth, permissions and users modules. You can run tests using:
116133

117134
go test ./...
118135

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ require (
1313
github.com/robfig/cron v1.1.0
1414
github.com/rogpeppe/go-internal v1.2.2 // indirect
1515
github.com/rs/cors v1.6.0
16+
github.com/siddharthlatest/mustache v0.0.0-20160118163553-00029677272d
17+
github.com/sirupsen/logrus v1.4.2
1618
github.com/smartystreets/goconvey v1.6.4
1719
github.com/ulule/limiter v2.2.0+incompatible
1820
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,11 +355,14 @@ github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:
355355
github.com/shurcooL/highlight_go v0.0.0-20170515013102-78fb10f4a5f8/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag=
356356
github.com/shurcooL/octicon v0.0.0-20180602230221-c42b0e3b24d9/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ=
357357
github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
358+
github.com/siddharthlatest/mustache v0.0.0-20160118163553-00029677272d/go.mod h1:ej02m5sGsrB5WBnM5xLGTfxUInBAbfNFPAsoJxBjn50=
358359
github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
359360
github.com/sirupsen/logrus v1.1.0/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A=
360361
github.com/sirupsen/logrus v1.1.1/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A=
361362
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
362363
github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
364+
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
365+
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
363366
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
364367
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
365368
github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
@@ -459,6 +462,7 @@ golang.org/x/sys v0.0.0-20190102155601-82a175fd1598/go.mod h1:STP8DvDyc/dI5b8T5h
459462
golang.org/x/sys v0.0.0-20190116161447-11f53e031339/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
460463
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
461464
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
465+
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
462466
golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU=
463467
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
464468
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

main.go

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import (
55
"flag"
66
"fmt"
77
"io"
8-
"io/ioutil"
9-
"log"
108
"net/http"
119
"os"
1210
"path/filepath"
@@ -22,14 +20,14 @@ import (
2220
"github.com/robfig/cron"
2321
"github.com/rs/cors"
2422

25-
"gopkg.in/natefinch/lumberjack.v2"
23+
log "github.com/sirupsen/logrus"
2624
)
2725

2826
const logTag = "[cmd]"
2927

3028
var (
3129
envFile string
32-
logFile string
30+
logMode string
3331
listPlugins bool
3432
address string
3533
port int
@@ -49,7 +47,7 @@ var (
4947

5048
func init() {
5149
flag.StringVar(&envFile, "env", ".env", "Path to file with environment variables to load in KEY=VALUE format")
52-
flag.StringVar(&logFile, "log", "", "Process log file")
50+
flag.StringVar(&logMode, "log", "", "Process log file")
5351
flag.BoolVar(&listPlugins, "plugins", false, "List currently registered plugins")
5452
flag.StringVar(&address, "addr", "", "Address to serve on")
5553
flag.IntVar(&port, "port", 8000, "Port number")
@@ -60,26 +58,23 @@ func init() {
6058
func main() {
6159
flag.Parse()
6260

63-
log.SetFlags(log.LstdFlags | log.Lshortfile)
64-
switch logFile {
65-
case "stdout":
66-
log.SetOutput(os.Stdout)
67-
case "stderr":
68-
log.SetOutput(os.Stderr)
69-
case "":
70-
log.SetOutput(ioutil.Discard)
61+
log.SetFormatter(&log.TextFormatter{
62+
FullTimestamp: true,
63+
TimestampFormat: "2006/01/02 15:04:05",
64+
})
65+
66+
switch logMode {
67+
case "debug":
68+
log.SetLevel(log.DebugLevel)
69+
case "info":
70+
log.SetLevel(log.InfoLevel)
7171
default:
72-
log.SetOutput(&lumberjack.Logger{
73-
Filename: logFile,
74-
MaxSize: 100,
75-
MaxAge: 14,
76-
MaxBackups: 10,
77-
})
72+
log.SetLevel(log.ErrorLevel)
7873
}
7974

8075
// Load all env vars from envFile
8176
if err := LoadEnvFromFile(envFile); err != nil {
82-
log.Printf("%s: reading env file %q: %v", logTag, envFile, err)
77+
log.Error(logTag, ": reading env file", envFile, ": ", err)
8378
}
8479

8580
router := mux.NewRouter().StrictSlash(true)
@@ -89,7 +84,7 @@ func main() {
8984
} else {
9085
_, err := strconv.Atoi(PlanRefreshInterval)
9186
if err != nil {
92-
log.Fatal("PLAN_REFRESH_INTERVAL must be an integer")
87+
log.Fatal("PLAN_REFRESH_INTERVAL must be an integer: ", err)
9388
}
9489
}
9590

middleware/interceptor/interceptor.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
package interceptor
22

33
import (
4-
"log"
54
"net/http"
65
"net/url"
76
"os"
87

8+
log "github.com/sirupsen/logrus"
9+
910
"github.com/appbaseio/arc/errors"
1011
"github.com/appbaseio/arc/middleware"
1112
"github.com/appbaseio/arc/util"
@@ -26,12 +27,12 @@ func redirect(h http.HandlerFunc) http.HandlerFunc {
2627
rawURL := os.Getenv("ES_CLUSTER_URL")
2728
if rawURL == "" {
2829
err := errors.NewEnvVarNotSetError(envEsClusterURL)
29-
log.Printf("%s: %v", logTag, err)
30+
log.Error(logTag, ": ", err)
3031
return
3132
}
3233
esURL, err := url.Parse(rawURL)
3334
if err != nil {
34-
log.Printf("%s: error parsing %s=%s: %v", logTag, rawURL, envEsClusterURL, err)
35+
log.Error(logTag, ": error parsing ", rawURL, "=", envEsClusterURL, ": ", err)
3536
return
3637
}
3738

@@ -41,7 +42,7 @@ func redirect(h http.HandlerFunc) http.HandlerFunc {
4142

4243
req, err := redirectRequest(r)
4344
if err != nil {
44-
log.Printf("%s: %v\n", logTag, err)
45+
log.Error(logTag, ": ", err)
4546
util.WriteBackError(w, err.Error(), http.StatusInternalServerError)
4647
return
4748
}

middleware/logger/logger.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package logger
22

33
import (
44
"fmt"
5-
"log"
5+
log "github.com/sirupsen/logrus"
66
"net/http"
77
"strings"
88
"time"

middleware/ratelimiter/ratelimiter.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ package ratelimiter
33
import (
44
"context"
55
"fmt"
6-
"log"
76
"net/http"
87
"sync"
98
"time"
109

10+
log "github.com/sirupsen/logrus"
11+
1112
"github.com/appbaseio/arc/middleware"
1213
"github.com/appbaseio/arc/model/category"
1314
"github.com/appbaseio/arc/model/credential"
@@ -60,7 +61,7 @@ func (rl *Ratelimiter) rateLimit(h http.HandlerFunc) http.HandlerFunc {
6061

6162
reqCredential, err := credential.FromContext(ctx)
6263
if err != nil {
63-
log.Printf("%s: %v\n", logTag, err)
64+
log.Error(logTag, ": ", err)
6465
util.WriteBackError(w, err.Error(), http.StatusInternalServerError)
6566
return
6667
}
@@ -70,14 +71,14 @@ func (rl *Ratelimiter) rateLimit(h http.HandlerFunc) http.HandlerFunc {
7071
errMsg := "An error occurred while validating rate limit"
7172
reqPermission, err := permission.FromContext(ctx)
7273
if err != nil {
73-
log.Printf("%s: %v", logTag, err)
74+
log.Error(logTag, ": ", err)
7475
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
7576
return
7677
}
7778

7879
reqCategory, err := category.FromContext(ctx)
7980
if err != nil {
80-
log.Printf("%s: %v", logTag, err)
81+
log.Error(logTag, ": ", err)
8182
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
8283
return
8384
}

middleware/validate/acl.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ package validate
33
import (
44
"context"
55
"fmt"
6-
"log"
76
"net/http"
87

8+
log "github.com/sirupsen/logrus"
9+
910
"github.com/appbaseio/arc/middleware"
1011
"github.com/appbaseio/arc/model/acl"
1112
"github.com/appbaseio/arc/model/credential"
@@ -26,21 +27,21 @@ func validateACL(h http.HandlerFunc) http.HandlerFunc {
2627
errMsg := "an error occurred while validating request acl"
2728
reqACL, err := acl.FromContext(ctx)
2829
if err != nil {
29-
log.Printf("%s: %v", logTag, err)
30+
log.Error(logTag, ": ", err)
3031
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
3132
return
3233
}
3334

3435
reqCredential, err := credential.FromContext(ctx)
3536
if err != nil {
36-
log.Printf("%s: %v", logTag, err)
37+
log.Error(logTag, ": ", err)
3738
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
3839
return
3940
}
4041

4142
ok, err := hasACL(ctx, reqCredential, reqACL)
4243
if err != nil {
43-
log.Printf("%s: %v", logTag, err)
44+
log.Error(logTag, ": ", err)
4445
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
4546
return
4647
}

middleware/validate/category.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ package validate
33
import (
44
"context"
55
"fmt"
6-
"log"
76
"net/http"
87

8+
log "github.com/sirupsen/logrus"
9+
910
"github.com/appbaseio/arc/middleware"
1011
"github.com/appbaseio/arc/model/category"
1112
"github.com/appbaseio/arc/model/credential"
@@ -26,21 +27,21 @@ func validateCategory(h http.HandlerFunc) http.HandlerFunc {
2627
errMsg := "an error occurred while validating request category"
2728
reqCategory, err := category.FromContext(ctx)
2829
if err != nil {
29-
log.Printf("%s: %v", logTag, err)
30+
log.Error(logTag, ": ", err)
3031
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
3132
return
3233
}
3334

3435
reqCredential, err := credential.FromContext(ctx)
3536
if err != nil {
36-
log.Printf("%s: %v", logTag, err)
37+
log.Error(logTag, ": ", err)
3738
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
3839
return
3940
}
4041

4142
ok, err := hasCategory(ctx, reqCredential, reqCategory)
4243
if err != nil {
43-
log.Printf("%s: %v", logTag, err)
44+
log.Error(logTag, ": ", err)
4445
util.WriteBackError(w, errMsg, http.StatusInternalServerError)
4546
return
4647
}

middleware/validate/expiry.go

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

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

7+
log "github.com/sirupsen/logrus"
8+
89
"github.com/appbaseio/arc/middleware"
910
"github.com/appbaseio/arc/model/credential"
1011
"github.com/appbaseio/arc/model/permission"
@@ -22,22 +23,22 @@ func validateExpiry(h http.HandlerFunc) http.HandlerFunc {
2223

2324
reqCredential, err := credential.FromContext(ctx)
2425
if err != nil {
25-
log.Printf("%s: %v", logTag, err)
26+
log.Error(logTag, ": ", err)
2627
util.WriteBackError(w, err.Error(), http.StatusInternalServerError)
2728
return
2829
}
2930

3031
if reqCredential == credential.Permission {
3132
reqPermission, err := permission.FromContext(ctx)
3233
if err != nil {
33-
log.Printf("%s: %v", logTag, err)
34+
log.Error(logTag, ": ", err)
3435
util.WriteBackError(w, err.Error(), http.StatusInternalServerError)
3536
return
3637
}
3738

3839
expired, err := reqPermission.IsExpired()
3940
if err != nil {
40-
log.Printf("%s: %v", logTag, err)
41+
log.Error(logTag, ": ", err)
4142
util.WriteBackError(w, err.Error(), http.StatusInternalServerError)
4243
return
4344
}

0 commit comments

Comments
 (0)