glog_file.go 3.2 KB

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