klog_file.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 klog
  18. import (
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "sync"
  25. "time"
  26. )
  27. // MaxSize is the maximum size of a log file in bytes.
  28. var MaxSize uint64 = 1024 * 1024 * 1800
  29. // logDirs lists the candidate directories for new log files.
  30. var logDirs []string
  31. func createLogDirs() {
  32. if logging.logDir != "" {
  33. logDirs = append(logDirs, logging.logDir)
  34. }
  35. logDirs = append(logDirs, os.TempDir())
  36. }
  37. var (
  38. pid = os.Getpid()
  39. program = filepath.Base(os.Args[0])
  40. host = "unknownhost"
  41. userName = "unknownuser"
  42. userNameOnce sync.Once
  43. )
  44. func init() {
  45. if h, err := os.Hostname(); err == nil {
  46. host = shortHostname(h)
  47. }
  48. }
  49. // shortHostname returns its argument, truncating at the first period.
  50. // For instance, given "www.google.com" it returns "www".
  51. func shortHostname(hostname string) string {
  52. if i := strings.Index(hostname, "."); i >= 0 {
  53. return hostname[:i]
  54. }
  55. return hostname
  56. }
  57. // logName returns a new log file name containing tag, with start time t, and
  58. // the name for the symlink for tag.
  59. func logName(tag string, t time.Time) (name, link string) {
  60. name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
  61. program,
  62. host,
  63. getUserName(),
  64. tag,
  65. t.Year(),
  66. t.Month(),
  67. t.Day(),
  68. t.Hour(),
  69. t.Minute(),
  70. t.Second(),
  71. pid)
  72. return name, program + "." + tag
  73. }
  74. var onceLogDirs sync.Once
  75. // create creates a new log file and returns the file and its filename, which
  76. // contains tag ("INFO", "FATAL", etc.) and t. If the file is created
  77. // successfully, create also attempts to update the symlink for that tag, ignoring
  78. // errors.
  79. // The startup argument indicates whether this is the initial startup of klog.
  80. // If startup is true, existing files are opened for appending instead of truncated.
  81. func create(tag string, t time.Time, startup bool) (f *os.File, filename string, err error) {
  82. if logging.logFile != "" {
  83. f, err := openOrCreate(logging.logFile, startup)
  84. if err == nil {
  85. return f, logging.logFile, nil
  86. }
  87. return nil, "", fmt.Errorf("log: unable to create log: %v", err)
  88. }
  89. onceLogDirs.Do(createLogDirs)
  90. if len(logDirs) == 0 {
  91. return nil, "", errors.New("log: no log dirs")
  92. }
  93. name, link := logName(tag, t)
  94. var lastErr error
  95. for _, dir := range logDirs {
  96. fname := filepath.Join(dir, name)
  97. f, err := openOrCreate(fname, startup)
  98. if err == nil {
  99. symlink := filepath.Join(dir, link)
  100. os.Remove(symlink) // ignore err
  101. os.Symlink(name, symlink) // ignore err
  102. return f, fname, nil
  103. }
  104. lastErr = err
  105. }
  106. return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
  107. }
  108. // The startup argument indicates whether this is the initial startup of klog.
  109. // If startup is true, existing files are opened for appending instead of truncated.
  110. func openOrCreate(name string, startup bool) (*os.File, error) {
  111. if startup {
  112. f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  113. return f, err
  114. }
  115. f, err := os.Create(name)
  116. return f, err
  117. }