blob: c5ba084a59e8e9c05b5a5fe8087a971b5d2e8b18 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package logs
18
19import (
20 "flag"
21 "log"
22 "time"
23
24 "github.com/golang/glog"
25 "github.com/spf13/pflag"
26 "k8s.io/apimachinery/pkg/util/wait"
27)
28
29const logFlushFreqFlagName = "log-flush-frequency"
30
31var logFlushFreq = pflag.Duration(logFlushFreqFlagName, 5*time.Second, "Maximum number of seconds between log flushes")
32
33// TODO(thockin): This is temporary until we agree on log dirs and put those into each cmd.
34func init() {
35 flag.Set("logtostderr", "true")
36}
37
38// AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the
39// same value as the global flags.
40func AddFlags(fs *pflag.FlagSet) {
41 fs.AddFlag(pflag.Lookup(logFlushFreqFlagName))
42}
43
44// GlogWriter serves as a bridge between the standard log package and the glog package.
45type GlogWriter struct{}
46
47// Write implements the io.Writer interface.
48func (writer GlogWriter) Write(data []byte) (n int, err error) {
49 glog.Info(string(data))
50 return len(data), nil
51}
52
53// InitLogs initializes logs the way we want for kubernetes.
54func InitLogs() {
55 log.SetOutput(GlogWriter{})
56 log.SetFlags(0)
57 // The default glog flush interval is 5 seconds.
58 go wait.Forever(glog.Flush, *logFlushFreq)
59}
60
61// FlushLogs flushes logs immediately.
62func FlushLogs() {
63 glog.Flush()
64}
65
66// NewLogger creates a new log.Logger which sends logs to glog.Info.
67func NewLogger(prefix string) *log.Logger {
68 return log.New(GlogWriter{}, prefix, 0)
69}