smallstep-certificates/logging/logger.go
Mariano Cano 00d8d8f995
Allow to disable color in the text formatter
This commit adds support for NO_COLOR environment variable, if this is
set, colors will be disabled in the logrus text formatter.

This commit also adds support for the environment variables supported by
logrus, CLICOLOR and CLICOLOR_FORCE

Related to #1549
2023-09-26 12:10:22 -07:00

86 lines
2.1 KiB
Go

package logging
import (
"encoding/json"
"net/http"
"os"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// defaultTraceIdHeader is the default header used as a trace id.
const defaultTraceIDHeader = "X-Smallstep-Id"
// ErrorKey defines the key used to log errors.
var ErrorKey = logrus.ErrorKey
// Logger is an alias of logrus.Logger.
type Logger struct {
*logrus.Logger
name string
traceHeader string
}
// loggerConfig represents the configuration options for the logger.
type loggerConfig struct {
Format string `json:"format"`
TraceHeader string `json:"traceHeader"`
}
// New initializes the logger with the given options.
func New(name string, raw json.RawMessage) (*Logger, error) {
var config loggerConfig
if err := json.Unmarshal(raw, &config); err != nil {
return nil, errors.Wrap(err, "error unmarshalling logging attribute")
}
var formatter logrus.Formatter
switch strings.ToLower(config.Format) {
case "", "text":
_, noColor := os.LookupEnv("NO_COLOR")
// With EnvironmentOverrideColors set, logrus looks at CLICOLOR and
// CLICOLOR_FORCE
formatter = &logrus.TextFormatter{
DisableColors: noColor,
EnvironmentOverrideColors: true,
}
case "json":
formatter = new(logrus.JSONFormatter)
case "common":
formatter = new(CommonLogFormat)
default:
return nil, errors.Errorf("unsupported logger.format '%s'", config.Format)
}
logger := &Logger{
Logger: logrus.New(),
name: name,
traceHeader: config.TraceHeader,
}
if formatter != nil {
logger.Formatter = formatter
}
return logger, nil
}
// GetImpl returns the real implementation of the logger.
func (l *Logger) GetImpl() *logrus.Logger {
return l.Logger
}
// GetTraceHeader returns the trace header configured
func (l *Logger) GetTraceHeader() string {
if l.traceHeader == "" {
return defaultTraceIDHeader
}
return l.traceHeader
}
// Middleware returns the logger middleware that will trace the request of the
// given handler.
func (l *Logger) Middleware(next http.Handler) http.Handler {
return NewLoggerHandler(l.name, l, next)
}