From 4e80090046d58d8ddd80a38939262a957d6dea1f Mon Sep 17 00:00:00 2001 From: Andrew Newdigate Date: Wed, 24 Jul 2019 09:50:11 +0200 Subject: Add full HTTP metrics and logging to GitLab pages using LabKit --- internal/logging/logging.go | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 internal/logging/logging.go (limited to 'internal/logging/logging.go') diff --git a/internal/logging/logging.go b/internal/logging/logging.go new file mode 100644 index 00000000..f0682573 --- /dev/null +++ b/internal/logging/logging.go @@ -0,0 +1,80 @@ +package logging + +import ( + "net/http" + + "github.com/sirupsen/logrus" + "gitlab.com/gitlab-org/labkit/log" + + "gitlab.com/gitlab-org/gitlab-pages/internal/request" +) + +// ConfigureLogging will initialize the system logger. +func ConfigureLogging(format string, verbose bool) error { + var levelOption log.LoggerOption + + if format == "" { + format = "text" + } + + if verbose { + levelOption = log.WithLogLevel("debug") + } else { + levelOption = log.WithLogLevel("info") + } + + _, err := log.Initialize( + log.WithFormatter(format), + levelOption, + ) + return err +} + +// getAccessLogger will return the default logger, except when +// the log format is text, in which case a combined HTTP access +// logger will be configured. This behaviour matches Workhorse +func getAccessLogger(format string) (*logrus.Logger, error) { + if format != "text" && format != "" { + return logrus.StandardLogger(), nil + } + + accessLogger := log.New() + _, err := log.Initialize( + log.WithLogger(accessLogger), // Configure `accessLogger` + log.WithFormatter("combined"), // Use the combined formatter + ) + if err != nil { + return nil, err + } + + return accessLogger, nil +} + +// getExtraLogFields is used to inject additional fields into the +// HTTP access logger middleware. +func getExtraLogFields(r *http.Request) log.Fields { + var projectID uint64 + if d := request.GetDomain(r); d != nil { + projectID = d.GetID(r) + } + + return log.Fields{ + "pages_https": request.IsHTTPS(r), + "pages_host": request.GetHost(r), + "pages_project_id": projectID, + } +} + +// AccessLogger configures the GitLab pages HTTP access logger middleware +func AccessLogger(handler http.Handler, format string) (http.Handler, error) { + + accessLogger, err := getAccessLogger(format) + if err != nil { + return nil, err + } + + return log.AccessLogger(handler, + log.WithExtraFields(getExtraLogFields), + log.WithAccessLogger(accessLogger), + ), nil +} -- cgit v1.2.3