forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logs.go
71 lines (56 loc) · 1.9 KB
/
logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package ui_helpers
import (
"fmt"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/cloudfoundry/cli/cf/terminal"
"github.com/cloudfoundry/loggregatorlib/logmessage"
)
func max(a, b int) int {
if a > b {
return a
}
return b
}
func ExtractLogHeader(msg *logmessage.LogMessage, loc *time.Location) (logHeader, coloredLogHeader string) {
logMsg := msg
sourceName := logMsg.GetSourceName()
sourceID := logMsg.GetSourceId()
t := time.Unix(0, logMsg.GetTimestamp())
timeFormat := "2006-01-02T15:04:05.00-0700"
timeString := t.In(loc).Format(timeFormat)
logHeader = fmt.Sprintf("%s [%s]", timeString, sourceName)
coloredLogHeader = terminal.LogSysHeaderColor(logHeader)
if sourceName == "App" {
logHeader = fmt.Sprintf("%s [%s/%s]", timeString, sourceName, sourceID)
coloredLogHeader = terminal.LogAppHeaderColor(logHeader)
}
// Calculate padding
longestHeader := fmt.Sprintf("%s [App/0] ", timeFormat)
expectedHeaderLength := utf8.RuneCountInString(longestHeader)
padding := strings.Repeat(" ", max(0, expectedHeaderLength-utf8.RuneCountInString(logHeader)))
logHeader = logHeader + padding
coloredLogHeader = coloredLogHeader + padding
return
}
var newLinesPattern = regexp.MustCompile("[\n\r]+$")
func ExtractLogContent(logMsg *logmessage.LogMessage, logHeader string) (logContent string) {
msgText := string(logMsg.GetMessage())
msgText = newLinesPattern.ReplaceAllString(msgText, "")
msgLines := strings.Split(msgText, "\n")
padding := strings.Repeat(" ", utf8.RuneCountInString(logHeader))
coloringFunc := terminal.LogStdoutColor
logType := "OUT"
if logMsg.GetMessageType() == logmessage.LogMessage_ERR {
coloringFunc = terminal.LogStderrColor
logType = "ERR"
}
logContent = fmt.Sprintf("%s %s", logType, msgLines[0])
for _, msgLine := range msgLines[1:] {
logContent = fmt.Sprintf("%s\n%s%s", logContent, padding, msgLine)
}
logContent = coloringFunc(logContent)
return
}