Matteo Scandolo | a428586 | 2020-12-01 18:10:10 -0800 | [diff] [blame] | 1 | // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ |
| 2 | // |
| 3 | // Copyright 2013 Google Inc. All Rights Reserved. |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | // File I/O for logs. |
| 18 | |
| 19 | package klog |
| 20 | |
| 21 | import ( |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | "os" |
| 25 | "os/user" |
| 26 | "path/filepath" |
| 27 | "runtime" |
| 28 | "strings" |
| 29 | "sync" |
| 30 | "time" |
| 31 | ) |
| 32 | |
| 33 | // MaxSize is the maximum size of a log file in bytes. |
| 34 | var MaxSize uint64 = 1024 * 1024 * 1800 |
| 35 | |
| 36 | // logDirs lists the candidate directories for new log files. |
| 37 | var logDirs []string |
| 38 | |
| 39 | func createLogDirs() { |
| 40 | if logging.logDir != "" { |
| 41 | logDirs = append(logDirs, logging.logDir) |
| 42 | } |
| 43 | logDirs = append(logDirs, os.TempDir()) |
| 44 | } |
| 45 | |
| 46 | var ( |
| 47 | pid = os.Getpid() |
| 48 | program = filepath.Base(os.Args[0]) |
| 49 | host = "unknownhost" |
| 50 | userName = "unknownuser" |
| 51 | userNameOnce sync.Once |
| 52 | ) |
| 53 | |
| 54 | func init() { |
| 55 | if h, err := os.Hostname(); err == nil { |
| 56 | host = shortHostname(h) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func getUserName() string { |
| 61 | userNameOnce.Do(func() { |
| 62 | // On Windows, the Go 'user' package requires netapi32.dll. |
| 63 | // This affects Windows Nano Server: |
| 64 | // https://github.com/golang/go/issues/21867 |
| 65 | // Fallback to using environment variables. |
| 66 | if runtime.GOOS == "windows" { |
| 67 | u := os.Getenv("USERNAME") |
| 68 | if len(u) == 0 { |
| 69 | return |
| 70 | } |
| 71 | // Sanitize the USERNAME since it may contain filepath separators. |
| 72 | u = strings.Replace(u, `\`, "_", -1) |
| 73 | |
| 74 | // user.Current().Username normally produces something like 'USERDOMAIN\USERNAME' |
| 75 | d := os.Getenv("USERDOMAIN") |
| 76 | if len(d) != 0 { |
| 77 | userName = d + "_" + u |
| 78 | } else { |
| 79 | userName = u |
| 80 | } |
| 81 | } else { |
| 82 | current, err := user.Current() |
| 83 | if err == nil { |
| 84 | userName = current.Username |
| 85 | } |
| 86 | } |
| 87 | }) |
| 88 | |
| 89 | return userName |
| 90 | } |
| 91 | |
| 92 | // shortHostname returns its argument, truncating at the first period. |
| 93 | // For instance, given "www.google.com" it returns "www". |
| 94 | func shortHostname(hostname string) string { |
| 95 | if i := strings.Index(hostname, "."); i >= 0 { |
| 96 | return hostname[:i] |
| 97 | } |
| 98 | return hostname |
| 99 | } |
| 100 | |
| 101 | // logName returns a new log file name containing tag, with start time t, and |
| 102 | // the name for the symlink for tag. |
| 103 | func logName(tag string, t time.Time) (name, link string) { |
| 104 | name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", |
| 105 | program, |
| 106 | host, |
| 107 | getUserName(), |
| 108 | tag, |
| 109 | t.Year(), |
| 110 | t.Month(), |
| 111 | t.Day(), |
| 112 | t.Hour(), |
| 113 | t.Minute(), |
| 114 | t.Second(), |
| 115 | pid) |
| 116 | return name, program + "." + tag |
| 117 | } |
| 118 | |
| 119 | var onceLogDirs sync.Once |
| 120 | |
| 121 | // create creates a new log file and returns the file and its filename, which |
| 122 | // contains tag ("INFO", "FATAL", etc.) and t. If the file is created |
| 123 | // successfully, create also attempts to update the symlink for that tag, ignoring |
| 124 | // errors. |
| 125 | // The startup argument indicates whether this is the initial startup of klog. |
| 126 | // If startup is true, existing files are opened for appending instead of truncated. |
| 127 | func create(tag string, t time.Time, startup bool) (f *os.File, filename string, err error) { |
| 128 | if logging.logFile != "" { |
| 129 | f, err := openOrCreate(logging.logFile, startup) |
| 130 | if err == nil { |
| 131 | return f, logging.logFile, nil |
| 132 | } |
| 133 | return nil, "", fmt.Errorf("log: unable to create log: %v", err) |
| 134 | } |
| 135 | onceLogDirs.Do(createLogDirs) |
| 136 | if len(logDirs) == 0 { |
| 137 | return nil, "", errors.New("log: no log dirs") |
| 138 | } |
| 139 | name, link := logName(tag, t) |
| 140 | var lastErr error |
| 141 | for _, dir := range logDirs { |
| 142 | fname := filepath.Join(dir, name) |
| 143 | f, err := openOrCreate(fname, startup) |
| 144 | if err == nil { |
| 145 | symlink := filepath.Join(dir, link) |
| 146 | os.Remove(symlink) // ignore err |
| 147 | os.Symlink(name, symlink) // ignore err |
| 148 | return f, fname, nil |
| 149 | } |
| 150 | lastErr = err |
| 151 | } |
| 152 | return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) |
| 153 | } |
| 154 | |
| 155 | // The startup argument indicates whether this is the initial startup of klog. |
| 156 | // If startup is true, existing files are opened for appending instead of truncated. |
| 157 | func openOrCreate(name string, startup bool) (*os.File, error) { |
| 158 | if startup { |
| 159 | f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) |
| 160 | return f, err |
| 161 | } |
| 162 | f, err := os.Create(name) |
| 163 | return f, err |
| 164 | } |