| 230 | } |
| 231 | |
| 232 | func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { |
| 233 | var levelColor int |
| 234 | switch entry.Level { |
| 235 | case DebugLevel, TraceLevel: |
| 236 | levelColor = gray |
| 237 | case WarnLevel: |
| 238 | levelColor = yellow |
| 239 | case ErrorLevel, FatalLevel, PanicLevel: |
| 240 | levelColor = red |
| 241 | case InfoLevel: |
| 242 | levelColor = blue |
| 243 | default: |
| 244 | levelColor = blue |
| 245 | } |
| 246 | |
| 247 | levelText := strings.ToUpper(entry.Level.String()) |
| 248 | if !f.DisableLevelTruncation && !f.PadLevelText { |
| 249 | levelText = levelText[0:4] |
| 250 | } |
| 251 | if f.PadLevelText { |
| 252 | // Generates the format string used in the next line, for example "%-6s" or "%-7s". |
| 253 | // Based on the max level text length. |
| 254 | formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" |
| 255 | // Formats the level text by appending spaces up to the max length, for example: |
| 256 | // - "INFO " |
| 257 | // - "WARNING" |
| 258 | levelText = fmt.Sprintf(formatString, levelText) |
| 259 | } |
| 260 | |
| 261 | // Remove a single newline if it already exists in the message to keep |
| 262 | // the behavior of logrus text_formatter the same as the stdlib log package |
| 263 | entry.Message = strings.TrimSuffix(entry.Message, "\n") |
| 264 | |
| 265 | caller := "" |
| 266 | if entry.HasCaller() { |
| 267 | funcVal := fmt.Sprintf("%s()", entry.Caller.Function) |
| 268 | fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) |
| 269 | |
| 270 | if f.CallerPrettyfier != nil { |
| 271 | funcVal, fileVal = f.CallerPrettyfier(entry.Caller) |
| 272 | } |
| 273 | |
| 274 | if fileVal == "" { |
| 275 | caller = funcVal |
| 276 | } else if funcVal == "" { |
| 277 | caller = fileVal |
| 278 | } else { |
| 279 | caller = fileVal + " " + funcVal |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | switch { |
| 284 | case f.DisableTimestamp: |
| 285 | fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) |
| 286 | case !f.FullTimestamp: |
| 287 | fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) |
| 288 | default: |
| 289 | fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) |