github.com/mattevans/edward@v1.9.2/runner/logging.go (about)

     1  package runner
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/pkg/errors"
    11  	"github.com/mattevans/edward/instance/servicelogs"
    12  )
    13  
    14  // Log provides the io.Writer interface to publish service logs to file
    15  type Log struct {
    16  	file   *os.File
    17  	name   string
    18  	stream string
    19  	lines  int
    20  }
    21  
    22  func (r *Log) Len() int {
    23  	return r.lines
    24  }
    25  
    26  // Printf prints a message to a RunnerLog
    27  func (r *Log) Printf(format string, a ...interface{}) {
    28  	msg := fmt.Sprintf(format, a...)
    29  	r.Write([]byte(msg))
    30  }
    31  
    32  // Write writes a slice of bytes to a RunnerLog
    33  func (r *Log) Write(p []byte) (int, error) {
    34  	r.lines++
    35  	fmt.Println(strings.TrimRight(string(p), "\n"))
    36  	lineData := servicelogs.LogLine{
    37  		Name:    r.name,
    38  		Time:    time.Now(),
    39  		Stream:  r.stream,
    40  		Message: strings.TrimSpace(string(p)),
    41  	}
    42  
    43  	jsonContent, err := json.Marshal(lineData)
    44  	if err != nil {
    45  		return 0, errors.Wrap(err, "could not prepare log line")
    46  	}
    47  
    48  	line := fmt.Sprintln(string(jsonContent))
    49  	count, err := r.file.Write([]byte(line))
    50  	if err != nil {
    51  		return count, errors.Wrap(err, "could not write log line")
    52  	}
    53  	return len(p), nil
    54  }