github.com/swisscom/cloudfoundry-cli@v7.1.0+incompatible/cf/api/logs/log_cache_message.go (about)

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