github.com/microsoft/moc@v0.17.1/pkg/logging/loggingRedirect.go (about)

     1  // Copyright (c) Microsoft Corporation.
     2  // Licensed under the Apache v2.0 license.
     3  
     4  // Package loggingRedirect - Creates a log file the redirects STD output.
     5  package logging
     6  
     7  import (
     8  	"log"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	path "github.com/microsoft/moc/pkg/path"
    13  )
    14  
    15  var (
    16  	oldStdOut *os.File
    17  	oldStdErr *os.File
    18  	logFile   *os.File
    19  )
    20  
    21  func createLogFile(logFileAbsolutePath string, logFileName string) (*os.File, error) {
    22  	// Create log path
    23  	os.MkdirAll(logFileAbsolutePath, os.ModeDir)
    24  
    25  	err := path.CheckPath(logFileAbsolutePath)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	path := filepath.Join(logFileAbsolutePath, logFileName)
    30  	logFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	st, err := logFile.Stat()
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	// If there are contents in the file already, move the file and replace it.
    41  	if st.Size() > 0 {
    42  		logFile.Close()
    43  		os.Rename(path, path+".old")
    44  		logFile, err = os.Create(path)
    45  		if err != nil {
    46  			return nil, err
    47  		}
    48  	}
    49  
    50  	return logFile, nil
    51  }
    52  
    53  // StartRedirectingOutput
    54  func StartRedirectingOutput(logFileAbsolutePath string, logFileName string) error {
    55  	// Save previous values
    56  	oldStdOut = os.Stdout
    57  	oldStdErr = os.Stderr
    58  
    59  	// Create output file
    60  	var err error
    61  	logFile, err = createLogFile(logFileAbsolutePath, logFileName)
    62  	if err != nil {
    63  		return err
    64  	}
    65  
    66  	RedirectStdErr(logFile)
    67  	// Set output to file
    68  	os.Stdout = logFile
    69  	log.SetOutput(logFile)
    70  
    71  	return nil
    72  }
    73  
    74  // RestoreOutput
    75  func RestoreOutput() {
    76  	// Restoring previous values
    77  	os.Stdout = oldStdOut
    78  	os.Stderr = oldStdErr
    79  	log.SetOutput(os.Stderr)
    80  
    81  	if logFile != nil {
    82  		// Close log file
    83  		logFile.Close()
    84  		logFile = nil
    85  	}
    86  }