log.go
 1  // Copyright 2017 The Prometheus Authors
 2  // Licensed under the Apache License, Version 2.0 (the "License");
 3  // you may not use this file except in compliance with the License.
 4  // You may obtain a copy of the License at
 5  //
 6  // http://www.apache.org/licenses/LICENSE-2.0
 7  //
 8  // Unless required by applicable law or agreed to in writing, software
 9  // distributed under the License is distributed on an "AS IS" BASIS,
10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  // See the License for the specific language governing permissions and
12  // limitations under the License.
13  
14  // Package promlog defines standardised ways to initialize Go kit loggers
15  // across Prometheus components.
16  // It should typically only ever be imported by main packages.
17  package promlog
18  
19  import (
20  	"os"
21  
22  	"github.com/go-kit/kit/log"
23  	"github.com/go-kit/kit/log/level"
24  	"github.com/pkg/errors"
25  )
26  
27  // AllowedLevel is a settable identifier for the minimum level a log entry
28  // must be have.
29  type AllowedLevel struct {
30  	s string
31  	o level.Option
32  }
33  
34  func (l *AllowedLevel) String() string {
35  	return l.s
36  }
37  
38  // Set updates the value of the allowed level.
39  func (l *AllowedLevel) Set(s string) error {
40  	switch s {
41  	case "debug":
42  		l.o = level.AllowDebug()
43  	case "info":
44  		l.o = level.AllowInfo()
45  	case "warn":
46  		l.o = level.AllowWarn()
47  	case "error":
48  		l.o = level.AllowError()
49  	default:
50  		return errors.Errorf("unrecognized log level %q", s)
51  	}
52  	l.s = s
53  	return nil
54  }
55  
56  // New returns a new leveled oklog logger in the logfmt format. Each logged line will be annotated
57  // with a timestamp. The output always goes to stderr.
58  func New(al AllowedLevel) log.Logger {
59  	l := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
60  	l = level.NewFilter(l, al.o)
61  	l = log.With(l, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
62  	return l
63  }