klog_file.go 3.2 KB

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