Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2014 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package logs |
| 18 | |
| 19 | import ( |
| 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 | |
| 29 | const logFlushFreqFlagName = "log-flush-frequency" |
| 30 | |
| 31 | var 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. |
| 34 | func 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. |
| 40 | func 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. |
| 45 | type GlogWriter struct{} |
| 46 | |
| 47 | // Write implements the io.Writer interface. |
| 48 | func (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. |
| 54 | func 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. |
| 62 | func FlushLogs() { |
| 63 | glog.Flush() |
| 64 | } |
| 65 | |
| 66 | // NewLogger creates a new log.Logger which sends logs to glog.Info. |
| 67 | func NewLogger(prefix string) *log.Logger { |
| 68 | return log.New(GlogWriter{}, prefix, 0) |
| 69 | } |