Skip to content

Commit

Permalink
add prefix for health (#10)
Browse files Browse the repository at this point in the history
* normalise the logging between services

* normalise the logging between services

* normalise the logging between services

* minor tweak

* minor tweak

* minor tweak

* Merge branches 'correct_logging' and 'master' of github.com:JSainsburyPLC/xecho into correct_logging

� Conflicts:
�	app.go
�	logging.go

* Merge branches 'correct_logging' and 'master' of github.com:JSainsburyPLC/xecho into correct_logging

� Conflicts:
�	app.go
�	logging.go

* Merge branches 'correct_logging' and 'master' of github.com:JSainsburyPLC/xecho into correct_logging

� Conflicts:
�	app.go
�	logging.go
  • Loading branch information
KevinJCross authored Mar 4, 2020
1 parent bab3d28 commit 95fc386
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 20 deletions.
46 changes: 40 additions & 6 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package xecho
import (
"fmt"
"net/http"
"os"
"time"

"github.com/labstack/echo"
Expand All @@ -25,6 +26,7 @@ type Config struct {
NewRelicEnabled bool
ErrorHandler ErrorHandlerFunc
UseDefaultHeaders bool
RoutePrefix string
}

func NewConfig() Config {
Expand All @@ -33,6 +35,7 @@ func NewConfig() Config {
AppName: "",
EnvName: "",
BuildVersion: "",
RoutePrefix: "",
LogLevel: logrus.InfoLevel,
LogFormatter: &logrus.JSONFormatter{},
IsDebug: false,
Expand All @@ -44,16 +47,23 @@ func NewConfig() Config {
}

func Echo(conf Config) *echo.Echo {
logger := logrus.New()
logger.SetLevel(conf.LogLevel)
logger.SetFormatter(conf.LogFormatter)
logger := logger(conf)
logger.WithFields(
logrus.Fields{
"project": conf.ProjectName,
"application": conf.AppName,
"environment": conf.EnvName,
"build_version": conf.BuildVersion,
"hostname": getHostName(),
}).Infof("XEcho app created %s(%s)", conf.AppName, conf.BuildVersion)

newRelicApp := createNewRelicApp(conf, logger)

e := echo.New()

e.HideBanner = true
e.HidePort = true
e.Logger = appScopeLogger(logger, conf.AppName, conf.EnvName, conf.BuildVersion)
e.Logger = appScopeLogger(logger, conf.AppName, conf.EnvName)

// the order of these middleware is important - context should be first, error should be after logging ones
e.Use(ContextMiddleware(conf.AppName, conf.EnvName, conf.BuildVersion, logger, conf.IsDebug, newRelicApp))
Expand All @@ -65,14 +75,38 @@ func Echo(conf Config) *echo.Echo {
e.Use(DebugLoggerMiddleware(conf.IsDebug))
e.Use(ErrorHandlerMiddleware(conf.ErrorHandler))

e.GET("/health", EchoHandler(func(c *Context) error {
addHealthCheck(conf, e)

return e
}

func addHealthCheck(conf Config, e *echo.Echo) {
healthRoute := "/health"
if conf.RoutePrefix != "" {
healthRoute = fmt.Sprintf("%s/health", conf.RoutePrefix)
}

e.GET(healthRoute, EchoHandler(func(c *Context) error {
if len(conf.BuildVersion) > 0 {
c.Response().Header().Add(headerBuildVersion, conf.BuildVersion)
}
return c.JSONBlob(http.StatusOK, []byte(`{"status": "ok"}`))
}))
}

return e
func getHostName() string {
name, err := os.Hostname()
if err != nil {
name = "ERROR"
}
return name
}

func logger(conf Config) *logrus.Logger {
logger := logrus.New()
logger.SetLevel(conf.LogLevel)
logger.SetFormatter(conf.LogFormatter)
return logger
}

func createNewRelicApp(conf Config, logger *logrus.Logger) newrelic.Application {
Expand Down
12 changes: 10 additions & 2 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,24 @@ import (

func TestHealthCheck(t *testing.T) {
apitest.New().
Handler(xecho.Echo(config())).
Handler(xecho.Echo(config(""))).
Get("/health").
Expect(t).
Status(http.StatusOK).
Body(`{"status": "ok"}`).
End()
apitest.New().
Handler(xecho.Echo(config("test"))).
Get("/test/health").
Expect(t).
Status(http.StatusOK).
Body(`{"status": "ok"}`).
End()
}

func config() xecho.Config {
func config(routePrefix string) xecho.Config {
config := xecho.NewConfig()
config.RoutePrefix = routePrefix
config.ProjectName = "acme"
config.AppName = "login"
config.EnvName = "dev"
Expand Down
1 change: 0 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ func ContextMiddleware(
correlationID,
appName,
envName,
buildVersion,
)

cc := NewContext(c, newRelicApp, logger, correlationID, isDebug, buildVersion)
Expand Down
25 changes: 14 additions & 11 deletions logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,11 @@ func appScopeLogger(
logger *logrus.Logger,
appName string,
envName string,
buildVersion string,
) *Logger {
entry := logger.WithFields(logrus.Fields{
"application": appName,
"env": envName,
"build_version": buildVersion,
"scope": "app",
"application": appName,
"env": envName,
"scope": "application",
})
return &Logger{entry}
}
Expand All @@ -100,19 +98,24 @@ func requestScopeLogger(
correlationID string,
appName string,
envName string,
buildVersion string,
) *Logger {
ctxLogger := logger.WithFields(logrus.Fields{
"application": appName,
"env": envName,
"build_version": buildVersion,
"scope": "request",
"correlation_id": correlationID,
"url": r.URL.String(),
"path": route,
"url": r.RequestURI,
"route": route,
"remote_addr": r.RemoteAddr,
"method": r.Method,
"ip": ip,
"headers": logrus.Fields{
"host": r.Host,
"user-agent": r.UserAgent(),
"referer": r.Referer(),
"x-forwarded-for": r.Header.Get("X-Forwarded-For"),
"x-forwarded-proto": r.Header.Get("X-Forwarded-Proto"),
},
})
return &Logger{ctxLogger}
}
Expand All @@ -135,7 +138,7 @@ func (l *Logger) Prefix() string {
return "" // not implemented - only added for API compatibility with echo logger
}

func (l *Logger) SetPrefix(prefix string) {
func (l *Logger) SetPrefix(_ string) {
// not implemented - only added for API compatibility with echo logger
}

Expand All @@ -147,7 +150,7 @@ func (l *Logger) SetLevel(lvl log.Lvl) {
l.Logger.Level = echoLeveltoLogrusLevel(lvl)
}

func (l *Logger) SetHeader(h string) {
func (l *Logger) SetHeader(_ string) {
// not implemented - only added for API compatibility with echo logger
}

Expand Down

0 comments on commit 95fc386

Please sign in to comment.