github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/x/simulation/log.go (about)

     1  package simulation
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path"
     7  	"time"
     8  )
     9  
    10  // log writter
    11  type LogWriter interface {
    12  	AddEntry(OperationEntry)
    13  	PrintLogs()
    14  }
    15  
    16  // LogWriter - return a dummy or standard log writer given the testingmode
    17  func NewLogWriter(testingmode bool) LogWriter {
    18  	if !testingmode {
    19  		return &DummyLogWriter{}
    20  	}
    21  	return &StandardLogWriter{}
    22  }
    23  
    24  // log writter
    25  type StandardLogWriter struct {
    26  	OpEntries []OperationEntry `json:"op_entries" yaml:"op_entries"`
    27  }
    28  
    29  // add an entry to the log writter
    30  func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) {
    31  	lw.OpEntries = append(lw.OpEntries, opEntry)
    32  }
    33  
    34  // PrintLogs - print the logs to a simulation file
    35  func (lw *StandardLogWriter) PrintLogs() {
    36  	f := createLogFile()
    37  	for i := 0; i < len(lw.OpEntries); i++ {
    38  		writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal())
    39  		_, err := f.WriteString(writeEntry)
    40  		if err != nil {
    41  			panic("Failed to write logs to file")
    42  		}
    43  	}
    44  }
    45  
    46  func createLogFile() *os.File {
    47  	var f *os.File
    48  	fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02_15:04:05"))
    49  
    50  	folderPath := os.ExpandEnv("$HOME/.simapp/simulations")
    51  	filePath := path.Join(folderPath, fileName)
    52  
    53  	err := os.MkdirAll(folderPath, os.ModePerm)
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  	f, _ = os.Create(filePath)
    58  	fmt.Printf("Logs to writing to %s\n", filePath)
    59  	return f
    60  }
    61  
    62  //_____________________
    63  // dummy log writter
    64  type DummyLogWriter struct{}
    65  
    66  // do nothing
    67  func (lw *DummyLogWriter) AddEntry(_ OperationEntry) {}
    68  
    69  // do nothing
    70  func (lw *DummyLogWriter) PrintLogs() {}