github.com/puellanivis/breton@v0.2.16/lib/glog/glog_file.go (about)

     1  // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ (With no dependency injection, the code had to be modified to integrate with github.com/puellanivis/breton/lib/gnuflag)
     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  	"path/filepath"
    26  	"strings"
    27  	"sync"
    28  	"time"
    29  
    30  	flag "github.com/puellanivis/breton/lib/gnuflag"
    31  	"github.com/puellanivis/breton/lib/os/user"
    32  )
    33  
    34  // MaxSize is the maximum size of a log file in bytes.
    35  var MaxSize uint64 = 1024 * 1024 * 1800
    36  
    37  // logDirs lists the candidate directories for new log files.
    38  var logDirs []string
    39  
    40  // If non-empty, overrides the choice of directory in which to write logs.
    41  // See createLogDirs for the full list of possible destinations.
    42  var logDir = flag.String("log_dir", "If non-empty, write log files in this directory")
    43  
    44  func createLogDirs() {
    45  	if *logDir != "" {
    46  		logDirs = append(logDirs, *logDir)
    47  	}
    48  	logDirs = append(logDirs, os.TempDir())
    49  }
    50  
    51  var (
    52  	pid      = os.Getpid()
    53  	program  = filepath.Base(os.Args[0])
    54  	host     = "unknownhost"
    55  	userName = "unknownuser"
    56  )
    57  
    58  // This would normally be a thread ID, but NO! NO NO NO NO NO! Go doesn’t have this notion.
    59  // So, we just precompute a byte slice that is 7-bytes wide, and contains the pid of the program.
    60  // Yes, this can be slow, because we only do it once at startup.
    61  var tid = []byte(fmt.Sprintf("%7d", pid))
    62  
    63  func init() {
    64  	h, err := os.Hostname()
    65  	if err == nil {
    66  		host = shortHostname(h)
    67  	}
    68  
    69  	currentUsername, err := user.CurrentUsername()
    70  	if err == nil {
    71  		userName = currentUsername
    72  	}
    73  
    74  	// Sanitize userName since it may contain filepath separators on Windows.
    75  	userName = strings.Replace(userName, `\`, "_", -1)
    76  }
    77  
    78  // shortHostname returns its argument, truncating at the first period.
    79  // For instance, given "www.google.com" it returns "www".
    80  func shortHostname(hostname string) string {
    81  	if i := strings.Index(hostname, "."); i >= 0 {
    82  		return hostname[:i]
    83  	}
    84  	return hostname
    85  }
    86  
    87  // logName returns a new log file name containing tag, with start time t, and
    88  // the name for the symlink for tag.
    89  func logName(tag string, t time.Time) (name, link string) {
    90  	name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
    91  		program,
    92  		host,
    93  		userName,
    94  		tag,
    95  		t.Year(),
    96  		t.Month(),
    97  		t.Day(),
    98  		t.Hour(),
    99  		t.Minute(),
   100  		t.Second(),
   101  		pid)
   102  	return name, program + "." + tag
   103  }
   104  
   105  var onceLogDirs sync.Once
   106  
   107  // create creates a new log file and returns the file and its filename, which
   108  // contains tag ("INFO", "FATAL", etc.) and t.  If the file is created
   109  // successfully, create also attempts to update the symlink for that tag, ignoring
   110  // errors.
   111  func create(tag string, t time.Time) (f *os.File, filename string, err error) {
   112  	onceLogDirs.Do(createLogDirs)
   113  	if len(logDirs) == 0 {
   114  		return nil, "", errors.New("log: no log dirs")
   115  	}
   116  	name, link := logName(tag, t)
   117  	var lastErr error
   118  	for _, dir := range logDirs {
   119  		fname := filepath.Join(dir, name)
   120  		f, err := os.Create(fname)
   121  		if err == nil {
   122  			symlink := filepath.Join(dir, link)
   123  			_ = os.Remove(symlink)        // ignore err
   124  			_ = os.Symlink(name, symlink) // ignore err
   125  			return f, fname, nil
   126  		}
   127  		lastErr = err
   128  	}
   129  	return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
   130  }