glog_file.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 glog
  18. import (
  19. "errors"
  20. "fmt"
  21. flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
  22. "os"
  23. "os/user"
  24. "path/filepath"
  25. "sort"
  26. "strings"
  27. "sync"
  28. "time"
  29. )
  30. // MaxSize is the maximum size of a log file in bytes.
  31. var MaxSize uint64 = 1024 * 1024 * 1800
  32. var MaxFileCount = 5
  33. // logDirs lists the candidate directories for new log files.
  34. var logDirs []string
  35. // If non-empty, overrides the choice of directory in which to write logs.
  36. // See createLogDirs for the full list of possible destinations.
  37. var logDir = flag.String("logdir", "", "If non-empty, write log files in this directory")
  38. func createLogDirs() {
  39. if *logDir != "" {
  40. logDirs = append(logDirs, *logDir)
  41. } else {
  42. logDirs = append(logDirs, os.TempDir())
  43. }
  44. }
  45. var (
  46. pid = os.Getpid()
  47. program = filepath.Base(os.Args[0])
  48. host = "unknownhost"
  49. userName = "unknownuser"
  50. )
  51. func init() {
  52. h, err := os.Hostname()
  53. if err == nil {
  54. host = shortHostname(h)
  55. }
  56. current, err := user.Current()
  57. if err == nil {
  58. userName = current.Username
  59. }
  60. // Sanitize userName since it may contain filepath separators on Windows.
  61. userName = strings.Replace(userName, `\`, "_", -1)
  62. }
  63. // shortHostname returns its argument, truncating at the first period.
  64. // For instance, given "www.google.com" it returns "www".
  65. func shortHostname(hostname string) string {
  66. if i := strings.Index(hostname, "."); i >= 0 {
  67. return hostname[:i]
  68. }
  69. return hostname
  70. }
  71. // logName returns a new log file name containing tag, with start time t, and
  72. // the name for the symlink for tag.
  73. func logName(tag string, t time.Time) (name, link string) {
  74. name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
  75. program,
  76. host,
  77. userName,
  78. tag,
  79. t.Year(),
  80. t.Month(),
  81. t.Day(),
  82. t.Hour(),
  83. t.Minute(),
  84. t.Second(),
  85. pid)
  86. return name, program + "." + tag
  87. }
  88. func prefix(tag string) string {
  89. return fmt.Sprintf("%s.%s.%s.log.%s.",
  90. program,
  91. host,
  92. userName,
  93. tag,
  94. )
  95. }
  96. var onceLogDirs sync.Once
  97. // create creates a new log file and returns the file and its filename, which
  98. // contains tag ("INFO", "FATAL", etc.) and t. If the file is created
  99. // successfully, create also attempts to update the symlink for that tag, ignoring
  100. // errors.
  101. func create(tag string, t time.Time) (f *os.File, filename string, err error) {
  102. onceLogDirs.Do(createLogDirs)
  103. if len(logDirs) == 0 {
  104. return nil, "", errors.New("log: no log dirs")
  105. }
  106. name, link := logName(tag, t)
  107. logPrefix := prefix(tag)
  108. var lastErr error
  109. for _, dir := range logDirs {
  110. // remove old logs
  111. entries, _ := os.ReadDir(dir)
  112. var previousLogs []string
  113. for _, entry := range entries {
  114. if strings.HasPrefix(entry.Name(), logPrefix) {
  115. previousLogs = append(previousLogs, entry.Name())
  116. }
  117. }
  118. if len(previousLogs) >= MaxFileCount {
  119. sort.Strings(previousLogs)
  120. for i, entry := range previousLogs {
  121. if i > len(previousLogs)-MaxFileCount {
  122. break
  123. }
  124. os.Remove(filepath.Join(dir, entry))
  125. }
  126. }
  127. // create new log file
  128. fname := filepath.Join(dir, name)
  129. f, err := os.Create(fname)
  130. if err == nil {
  131. symlink := filepath.Join(dir, link)
  132. os.Remove(symlink) // ignore err
  133. os.Symlink(name, symlink) // ignore err
  134. return f, fname, nil
  135. }
  136. lastErr = err
  137. }
  138. return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
  139. }