github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/api/logs/noaa_message.go (about)

     1  package logs
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"time"
     7  	"unicode/utf8"
     8  
     9  	"code.cloudfoundry.org/cli/cf/terminal"
    10  	"github.com/cloudfoundry/sonde-go/events"
    11  )
    12  
    13  type noaaLogMessage struct {
    14  	msg *events.LogMessage
    15  }
    16  
    17  func NewNoaaLogMessage(m *events.LogMessage) *noaaLogMessage {
    18  	return &noaaLogMessage{
    19  		msg: m,
    20  	}
    21  }
    22  
    23  func (m *noaaLogMessage) ToSimpleLog() string {
    24  	msgText := string(m.msg.GetMessage())
    25  
    26  	return strings.TrimRight(msgText, "\r\n")
    27  }
    28  
    29  func (m *noaaLogMessage) GetSourceName() string {
    30  	return m.msg.GetSourceType()
    31  }
    32  
    33  func (m *noaaLogMessage) ToLog(loc *time.Location) string {
    34  	logMsg := m.msg
    35  
    36  	sourceName := logMsg.GetSourceType()
    37  	sourceID := logMsg.GetSourceInstance()
    38  	t := time.Unix(0, logMsg.GetTimestamp())
    39  	timeFormat := "2006-01-02T15:04:05.00-0700"
    40  	timeString := t.In(loc).Format(timeFormat)
    41  
    42  	var logHeader string
    43  
    44  	if sourceID == "" {
    45  		logHeader = fmt.Sprintf("%s [%s]", timeString, sourceName)
    46  	} else {
    47  		logHeader = fmt.Sprintf("%s [%s/%s]", timeString, sourceName, sourceID)
    48  	}
    49  
    50  	coloredLogHeader := terminal.LogSysHeaderColor(logHeader)
    51  
    52  	// Calculate padding
    53  	longestHeader := fmt.Sprintf("%s  [HEALTH/10] ", timeFormat)
    54  	expectedHeaderLength := utf8.RuneCountInString(longestHeader)
    55  	headerPadding := strings.Repeat(" ", max(0, expectedHeaderLength-utf8.RuneCountInString(logHeader)))
    56  
    57  	logHeader = logHeader + headerPadding
    58  	coloredLogHeader = coloredLogHeader + headerPadding
    59  
    60  	msgText := string(logMsg.GetMessage())
    61  	msgText = strings.TrimRight(msgText, "\r\n")
    62  
    63  	msgLines := strings.Split(msgText, "\n")
    64  	contentPadding := strings.Repeat(" ", utf8.RuneCountInString(logHeader))
    65  	coloringFunc := terminal.LogStdoutColor
    66  	logType := "OUT"
    67  
    68  	if logMsg.GetMessageType() == events.LogMessage_ERR {
    69  		coloringFunc = terminal.LogStderrColor
    70  		logType = "ERR"
    71  	}
    72  
    73  	logContent := fmt.Sprintf("%s %s", logType, msgLines[0])
    74  	for _, msgLine := range msgLines[1:] {
    75  		logContent = fmt.Sprintf("%s\n%s%s", logContent, contentPadding, msgLine)
    76  	}
    77  
    78  	logContent = coloringFunc(logContent)
    79  
    80  	return fmt.Sprintf("%s%s", coloredLogHeader, logContent)
    81  }