github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/logger/glog/glog_file.go (about)

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