...

Source file src/k8s.io/klog/v2/klog_file.go

Documentation: k8s.io/klog/v2

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

View as plain text