70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package logfile
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/volker-raschek/flucky/pkg/types"
|
|
)
|
|
|
|
type jsonLogfile struct {
|
|
logfile string
|
|
}
|
|
|
|
func (jl *jsonLogfile) Read() ([]*types.MeasuredValue, error) {
|
|
|
|
if _, err := os.Stat(jl.logfile); os.IsNotExist(err) {
|
|
if _, err := os.Stat(filepath.Dir(jl.logfile)); os.IsNotExist(err) {
|
|
if err := os.MkdirAll(filepath.Dir(jl.logfile), 0755); err != nil {
|
|
return nil, fmt.Errorf("%v: %v", errorDirectoryCreate, filepath.Dir(jl.logfile))
|
|
}
|
|
}
|
|
|
|
f, err := os.Create(jl.logfile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%v: %v", errorLogfileCreate, jl.logfile)
|
|
}
|
|
f.WriteString("{}")
|
|
f.Close()
|
|
}
|
|
|
|
f, err := os.Open(jl.logfile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%v %v: %v", errorLogfileOpen, jl.logfile, err)
|
|
}
|
|
|
|
measuredValues := make([]*types.MeasuredValue, 0)
|
|
|
|
if err := json.NewDecoder(f).Decode(&measuredValues); err != nil {
|
|
return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, jl.logfile, err)
|
|
}
|
|
|
|
return measuredValues, nil
|
|
}
|
|
|
|
func (jl *jsonLogfile) Write(measuredValues []*types.MeasuredValue) error {
|
|
|
|
if _, err := os.Stat(filepath.Dir(jl.logfile)); os.IsNotExist(err) {
|
|
if err := os.MkdirAll(filepath.Dir(jl.logfile), 755); err != nil {
|
|
return fmt.Errorf("Directory for the logfile can not be created: %v", err)
|
|
}
|
|
}
|
|
|
|
f, err := os.Create(jl.logfile)
|
|
if err != nil {
|
|
return fmt.Errorf("%v %v: %v", errorLogfileCreate, jl.logfile, err)
|
|
}
|
|
|
|
jsonEncoder := json.NewEncoder(f)
|
|
jsonEncoder.SetIndent("", " ")
|
|
err = jsonEncoder.Encode(measuredValues)
|
|
if err != nil {
|
|
return fmt.Errorf("%v %v: %v", errorLogfileEncode, jl.logfile, err)
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|