klog_file.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. // File I/O for logs.
  17. package log
  18. import (
  19. "errors"
  20. "fmt"
  21. "os"
  22. "os/user"
  23. "path/filepath"
  24. "runtime"
  25. "strings"
  26. "sync"
  27. "time"
  28. )
  29. // MaxSize is the maximum size of a log file in bytes.
  30. var MaxSize uint64 = 1024 * 1024 * 1800
  31. // logDirs lists the candidate directories for new log files.
  32. var logDirs []string
  33. func createLogDirs() {
  34. if logging.logDir != "" {
  35. logDirs = append(logDirs, logging.logDir)
  36. }
  37. logDirs = append(logDirs, os.TempDir())
  38. }
  39. var (
  40. pid = os.Getpid()
  41. program = filepath.Base(os.Args[0])
  42. host = "unknownhost"
  43. userName = "unknownuser"
  44. userNameOnce sync.Once
  45. )
  46. func init() {
  47. if h, err := os.Hostname(); err == nil {
  48. host = shortHostname(h)
  49. }
  50. }
  51. func getUserName() string {
  52. userNameOnce.Do(func() {
  53. // On Windows, the Go 'user' package requires netapi32.dll.
  54. // This affects Windows Nano Server:
  55. // https://github.com/golang/go/issues/21867
  56. // Fallback to using environment variables.
  57. if runtime.GOOS == "windows" {
  58. u := os.Getenv("USERNAME")
  59. if len(u) == 0 {
  60. return
  61. }
  62. // Sanitize the USERNAME since it may contain filepath separators.
  63. u = strings.Replace(u, `\`, "_", -1)
  64. // user.Current().Username normally produces something like 'USERDOMAIN\USERNAME'
  65. d := os.Getenv("USERDOMAIN")
  66. if len(d) != 0 {
  67. userName = d + "_" + u
  68. } else {
  69. userName = u
  70. }
  71. } else {
  72. current, err := user.Current()
  73. if err == nil {
  74. userName = current.Username
  75. }
  76. }
  77. })
  78. return userName
  79. }
  80. // shortHostname returns its argument, truncating at the first period.
  81. // For instance, given "www.google.com" it returns "www".
  82. func shortHostname(hostname string) string {
  83. if i := strings.Index(hostname, "."); i >= 0 {
  84. return hostname[:i]
  85. }
  86. return hostname
  87. }
  88. // logName returns a new log file name containing tag, with start time t, and
  89. // the name for the symlink for tag.
  90. func logName(tag string, t time.Time) (name, link string) {
  91. name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
  92. program,
  93. host,
  94. getUserName(),
  95. tag,
  96. t.Year(),
  97. t.Month(),
  98. t.Day(),
  99. t.Hour(),
  100. t.Minute(),
  101. t.Second(),
  102. pid)
  103. return name, program + "." + tag
  104. }
  105. var onceLogDirs sync.Once
  106. // create creates a new log file and returns the file and its filename, which
  107. // contains tag ("INFO", "FATAL", etc.) and t. If the file is created
  108. // successfully, create also attempts to update the symlink for that tag, ignoring
  109. // errors.
  110. // The startup argument indicates whether this is the initial startup of klog.
  111. // If startup is true, existing files are opened for appending instead of truncated.
  112. func create(tag string, t time.Time, startup bool) (f *os.File, filename string, err error) {
  113. if logging.logFile != "" {
  114. f, err := openOrCreate(logging.logFile, startup)
  115. if err == nil {
  116. return f, logging.logFile, nil
  117. }
  118. return nil, "", fmt.Errorf("log: unable to create log: %v", err)
  119. }
  120. onceLogDirs.Do(createLogDirs)
  121. if len(logDirs) == 0 {
  122. return nil, "", errors.New("log: no log dirs")
  123. }
  124. name, link := logName(tag, t)
  125. var lastErr error
  126. for _, dir := range logDirs {
  127. fname := filepath.Join(dir, name)
  128. f, err := openOrCreate(fname, startup)
  129. if err == nil {
  130. symlink := filepath.Join(dir, link)
  131. os.Remove(symlink) // ignore err
  132. os.Symlink(name, symlink) // ignore err
  133. return f, fname, nil
  134. }
  135. lastErr = err
  136. }
  137. return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
  138. }
  139. // The startup argument indicates whether this is the initial startup of klog.
  140. // If startup is true, existing files are opened for appending instead of truncated.
  141. func openOrCreate(name string, startup bool) (*os.File, error) {
  142. if startup {
  143. f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  144. return f, err
  145. }
  146. f, err := os.Create(name)
  147. return f, err
  148. }