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