22 baseTimestamp time.Time
27 baseTimestamp = time.Now()
28 isTerminal = IsTerminal()
32 return int(time.Since(baseTimestamp) / time.Second)
35 type TextFormatter struct {
36 // Set to true to bypass checking for a TTY before outputting colors.
39 // Force disabling colors.
42 // Disable timestamp logging. useful when output is redirected to logging
43 // system that already adds timestamps.
46 // Enable logging the full timestamp when a TTY is attached instead of just
47 // the time passed since beginning of execution.
50 // TimestampFormat to use for display when a full timestamp is printed
51 TimestampFormat string
53 // The fields are sorted by default for a consistent output. For applications
54 // that log extremely frequently and don't use the JSON formatter this may not
59 func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
60 var keys []string = make([]string, 0, len(entry.Data))
61 for k := range entry.Data {
62 keys = append(keys, k)
65 if !f.DisableSorting {
71 prefixFieldClashes(entry.Data)
73 isColorTerminal := isTerminal && (runtime.GOOS != "windows")
74 isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
76 timestampFormat := f.TimestampFormat
77 if timestampFormat == "" {
78 timestampFormat = DefaultTimestampFormat
81 f.printColored(b, entry, keys, timestampFormat)
83 if !f.DisableTimestamp {
84 f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
86 f.appendKeyValue(b, "level", entry.Level.String())
87 if entry.Message != "" {
88 f.appendKeyValue(b, "msg", entry.Message)
90 for _, key := range keys {
91 f.appendKeyValue(b, key, entry.Data[key])
99 func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
106 case ErrorLevel, FatalLevel, PanicLevel:
112 levelText := strings.ToUpper(entry.Level.String())[0:4]
114 if !f.FullTimestamp {
115 fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
117 fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
119 for _, k := range keys {
121 fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v)
125 func needsQuoting(text string) bool {
126 for _, ch := range text {
127 if !((ch >= 'a' && ch <= 'z') ||
128 (ch >= 'A' && ch <= 'Z') ||
129 (ch >= '0' && ch <= '9') ||
130 ch == '-' || ch == '.') {
137 func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
142 switch value := value.(type) {
144 if needsQuoting(value) {
147 fmt.Fprintf(b, "%q", value)
150 errmsg := value.Error()
151 if needsQuoting(errmsg) {
152 b.WriteString(errmsg)
154 fmt.Fprintf(b, "%q", value)