Permalink
Browse files

Improve logs

  • Loading branch information...
dunglas committed Sep 16, 2018
1 parent cc37f5a commit 1720a098d193a241b3500043e807f077f8761459
Showing with 75 additions and 26 deletions.
  1. +1 −0 .env
  2. +1 −0 README.md
  3. +7 −4 go.mod
  4. +14 −0 go.sum
  5. +1 −7 hub/hub.go
  6. +2 −2 hub/publish.go
  7. +12 −8 hub/server.go
  8. +12 −3 hub/subscribe.go
  9. +14 −1 main.go
  10. +4 −1 public/app.js
  11. +7 −0 public/index.html
1 .env
@@ -9,3 +9,4 @@ ACME_HOSTS=
ACME_CERT_DIR=
CERT_FILE=
CERT_KEY=
LOG_FORMAT=JSON
@@ -278,6 +278,7 @@ A Docker image is available on Docker Hub. The following command is enough to ge
* `ACME_CERT_DIR`: the directory where to store Let's Encrypt certificates
* `CERT_FILE`: a cert file (to use a custom certificate)
* `CERT_KEY`: a cert key (to use a custom certificate)
* `LOG_FORMAT`: the log format, can be `JSON`, `FLUENTD` or `TEXT` (default)
If `ACME_HOSTS` or both `CERT_FILE` and `CERT_KEY` are provided, an HTTPS server supporting HTTP/2 connection will be started.
If not, an HTTP server will be started (**not secure**).
11 go.mod

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
14 go.sum

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
@@ -1,9 +1,5 @@
package hub
import (
"log"
)
type serializedUpdate struct {
*Update
event string
@@ -72,9 +68,7 @@ func (h *Hub) Start() {
close(s)
}
}
if ok {
log.Printf("Broadcasted topic %s", serializedUpdate.Topics)
} else {
if !ok {
return
}
}
@@ -2,11 +2,11 @@ package hub
import (
"fmt"
"log"
"net/http"
"strconv"
jwt "github.com/dgrijalva/jwt-go"
log "github.com/sirupsen/logrus"
)
// PublishHandler allows publisher to broadcast updates to all subscribers
@@ -60,6 +60,7 @@ func (h *Hub) PublishHandler(w http.ResponseWriter, r *http.Request) {
// Broadcast the update
h.updates <- newSerializedUpdate(u)
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr, "event_id": u.ID}).Info("Event published")
}
// Checks the validity of the JWT
@@ -69,7 +70,6 @@ func (h *Hub) isAuthorizationValid(authorizationHeader string) bool {
}
token, _ := jwt.Parse(authorizationHeader[7:], func(token *jwt.Token) (interface{}, error) {
log.Println(token.Header["alg"])
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
@@ -2,12 +2,12 @@ package hub
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"github.com/gorilla/handlers"
log "github.com/sirupsen/logrus"
"github.com/unrolled/secure"
"golang.org/x/crypto/acme/autocert"
)
@@ -29,17 +29,17 @@ func (h *Hub) Serve() {
<-sigint
if err := srv.Shutdown(context.Background()); err != nil {
log.Println(err)
log.Error(err)
}
log.Println("My Baby Shot Me Down")
log.Infoln("My Baby Shot Me Down")
close(idleConnsClosed)
}()
acme := len(h.options.AcmeHosts) > 0
var err error
if !acme && h.options.CertFile == "" && h.options.KeyFile == "" {
log.Printf("Mercure is starting (http)...")
log.WithFields(log.Fields{"protocol": "http"}).Info("Mercure started")
err = srv.ListenAndServe()
} else {
// TLS
@@ -57,12 +57,12 @@ func (h *Hub) Serve() {
go http.ListenAndServe(":http", certManager.HTTPHandler(nil))
}
log.Printf("Mercure is starting (https)...")
log.WithFields(log.Fields{"protocol": "https"}).Info("Mercure started")
err = srv.ListenAndServeTLS(h.options.CertFile, h.options.KeyFile)
}
if err != http.ErrServerClosed {
log.Println(err)
log.Error(err)
}
<-idleConnsClosed
@@ -95,9 +95,13 @@ func (h *Hub) chainHandlers() http.Handler {
ContentSecurityPolicy: "default-src 'self'",
})
secureHandler := secureMiddleware.Handler(http.DefaultServeMux)
compressHandler := handlers.CompressHandler(http.DefaultServeMux)
secureHandler := secureMiddleware.Handler(compressHandler)
loggingHandler := handlers.CombinedLoggingHandler(os.Stderr, secureHandler)
recoveryHandler := handlers.RecoveryHandler(handlers.PrintRecoveryStack(h.options.Debug))(loggingHandler)
recoveryHandler := handlers.RecoveryHandler(
handlers.RecoveryLogger(log.New()),
handlers.PrintRecoveryStack(h.options.Debug),
)(loggingHandler)
return recoveryHandler
}
@@ -2,11 +2,11 @@ package hub
import (
"fmt"
"log"
"net/http"
"regexp"
jwt "github.com/dgrijalva/jwt-go"
log "github.com/sirupsen/logrus"
"github.com/yosida95/uritemplate"
)
@@ -50,7 +50,7 @@ func (h *Hub) SubscribeHandler(w http.ResponseWriter, r *http.Request) {
regexps[index] = tpl.Regexp()
}
log.Printf("%s connected.", r.RemoteAddr)
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info("New subscriber")
sendHeaders(w)
subscriber := &Subscriber{targets, regexps, retrieveLastEventID(r)}
@@ -72,7 +72,7 @@ func (h *Hub) SubscribeHandler(w http.ResponseWriter, r *http.Request) {
go func() {
<-notify
h.removedSubscribers <- updateChan
log.Printf("%s disconnected.", r.RemoteAddr)
log.WithFields(log.Fields{"remote_addr": r.RemoteAddr}).Info("Subscriber disconnected")
}()
for {
@@ -87,6 +87,10 @@ func (h *Hub) SubscribeHandler(w http.ResponseWriter, r *http.Request) {
}
fmt.Fprint(w, serializedUpdate.event)
log.WithFields(log.Fields{
"event_id": serializedUpdate.ID,
"remote_addr": r.RemoteAddr,
}).Info("Event sent")
f.Flush()
}
}
@@ -139,6 +143,11 @@ func retrieveLastEventID(r *http.Request) string {
func (h *Hub) sendMissedEvents(w http.ResponseWriter, r *http.Request, s *Subscriber) {
if err := h.history.FindFor(s, func(u *Update) bool {
fmt.Fprint(w, u.String())
log.WithFields(log.Fields{
"event_id": u.ID,
"last_event_id": s.LastEventID,
"remote_addr": r.RemoteAddr,
}).Info("Event sent")
return true
}); err != nil {
panic(err)
15 main.go
@@ -1,12 +1,25 @@
package main
import (
"log"
"os"
fluentd "github.com/joonix/log"
log "github.com/sirupsen/logrus"
"github.com/dunglas/mercure/hub"
_ "github.com/joho/godotenv/autoload"
)
func init() {
switch os.Getenv("LOG_FORMAT") {
case "JSON":
log.SetFormatter(&log.JSONFormatter{})
return
case "FLUENTD":
log.SetFormatter(&fluentd.FluentdFormatter{})
}
}
func main() {
db, err := hub.NewBoltFromEnv()
exitOnError(err)
@@ -26,11 +26,14 @@ document.forms.subscribe.onsubmit = function (e) {
e.preventDefault();
eventSource && eventSource.close();
const { elements: { topics, jwt } } = this;
const { elements: { topics, jwt, lastEventId } } = this;
const topicList = topics.value.split("\n");
const params = new URLSearchParams();
topicList.forEach(topic => params.append('topic', topic));
if (lastEventId) {
params.append('Last-Event-ID', lastEventId.value);
}
jwt.value ? document.cookie = `mercureAuthorization=${encodeURIComponent(jwt.value)}` : deleteCookie();
@@ -21,6 +21,13 @@ <h1>Subscriber</h1>
<small>One <a href="https://tools.ietf.org/html/rfc6570">URI template</a> per line.</small>
</div>
<div>
<label>
Last Event ID:
<input name="lastEventId">
</label>
</div>
<div>
<label>
JWT:

0 comments on commit 1720a09

Please sign in to comment.