github.com/Finschia/finschia-sdk@v0.48.1/x/simulation/event_stats.go (about)

     1  package simulation
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  )
     9  
    10  // EventStats defines an object that keeps a tally of each event that has occurred
    11  // during a simulation.
    12  type EventStats map[string]map[string]map[string]int
    13  
    14  // NewEventStats creates a new empty EventStats object
    15  func NewEventStats() EventStats {
    16  	return make(EventStats)
    17  }
    18  
    19  // Tally increases the count of a simulation event.
    20  func (es EventStats) Tally(route, op, evResult string) {
    21  	_, ok := es[route]
    22  	if !ok {
    23  		es[route] = make(map[string]map[string]int)
    24  	}
    25  
    26  	_, ok = es[route][op]
    27  	if !ok {
    28  		es[route][op] = make(map[string]int)
    29  	}
    30  
    31  	es[route][op][evResult]++
    32  }
    33  
    34  // Print the event stats in JSON format.
    35  func (es EventStats) Print(w io.Writer) {
    36  	obj, err := json.MarshalIndent(es, "", " ")
    37  	if err != nil {
    38  		panic(err)
    39  	}
    40  
    41  	fmt.Fprintln(w, string(obj))
    42  }
    43  
    44  // ExportJSON saves the event stats as a JSON file on a given path
    45  func (es EventStats) ExportJSON(path string) {
    46  	bz, err := json.MarshalIndent(es, "", " ")
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	err = os.WriteFile(path, bz, 0o600)
    52  	if err != nil {
    53  		panic(err)
    54  	}
    55  }