package logrus

import (
	
	
	
	
	
	
	
	
	
	
	
)

var baseTimestamp = time.Now()

// TextFormatter formats logs into text.
//
// Output is logfmt-like: key=value pairs separated by spaces. Fields from
// [Entry.Data] are included together with the standard fields derived from the
// entry. If a field conflicts with a standard field, it is prefixed with
// "fields.". Standard field names can be customized through FieldMap.
//
// Field keys are written as-is (unquoted and unescaped) in the plain
// (non-colored) format; only field values may be quoted depending on
// DisableQuote, ForceQuote, QuoteEmptyFields, and the value content.
//
// When colors are enabled, ANSI escape sequences may be added for presentation.
// For fully escaped structured output (including safe keys), use JSONFormatter.
type TextFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors bool

	// Force disabling colors.
	DisableColors bool

	// Force quoting of all values
	ForceQuote bool

	// DisableQuote disables quoting for all values.
	// DisableQuote will have a lower priority than ForceQuote.
	// If both of them are set to true, quote will be forced on all values.
	DisableQuote bool

	// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
	EnvironmentOverrideColors bool

	// Disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp bool

	// Enable logging the full timestamp when a TTY is attached instead of just
	// the time passed since beginning of execution.
	FullTimestamp bool

	// TimestampFormat to use for display when a full timestamp is printed.
	// The format to use is the same than for time.Format or time.Parse from the standard
	// library.
	// The standard Library already provides a set of predefined format.
	TimestampFormat string

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool

	// The keys sorting function, when uninitialized it uses slices.Sort.
	SortingFunc func([]string)

	// Disables the truncation of the level text to 4 characters.
	DisableLevelTruncation bool

	// PadLevelText Adds padding the level text so that all the levels output at the same length
	// PadLevelText is a superset of the DisableLevelTruncation option
	PadLevelText bool

	// QuoteEmptyFields will wrap empty fields in quotes if true
	QuoteEmptyFields bool

	// Whether the logger's out is to a terminal. Don't use this field
	// directly; use TextFormatter.isTerminal instead.
	terminal bool

	// FieldMap allows users to customize the names of keys for default fields.
	// Mapped keys are written as-is, so they should be safe for plain-text output.
	//
	// As an example:
	//
	// formatter := &TextFormatter{
	// 	FieldMap: FieldMap{
	// 		FieldKeyTime:  "@timestamp",
	// 		FieldKeyLevel: "@level",
	// 		FieldKeyMsg:   "@message",
	// 	},
	// }
	FieldMap FieldMap

	// CallerPrettyfier can be set by the user to modify the content
	// of the function and file keys in the data when ReportCaller is
	// activated. If any of the returned value is the empty string the
	// corresponding key will be removed from fields.
	CallerPrettyfier func(*runtime.Frame) (function string, file string)

	terminalInitOnce sync.Once
}

func ( *TextFormatter) ( *Entry) bool {
	if  == nil || .Logger == nil {
		// Don't run the terminalInitOnce without a logger, otherwise we'd
		// cache the default (false) forever even if a logger is attached
		// later.
		return false
	}

	.terminalInitOnce.Do(func() {
		.Logger.mu.Lock()
		 := .Logger.Out
		.Logger.mu.Unlock()

		.terminal = checkIfTerminal()
	})

	return .terminal
}

func ( *TextFormatter) ( bool) bool {
	if .DisableColors {
		return false
	}

	 := .ForceColors || 
	if !.EnvironmentOverrideColors {
		return 
	}
	if ,  := os.LookupEnv("CLICOLOR_FORCE");  {
		return  != "0"
	}
	if os.Getenv("CLICOLOR") == "0" {
		return false
	}
	return 
}

// Format renders a single log entry
func ( *TextFormatter) ( *Entry) ([]byte, error) {
	 := make(Fields, len(.Data))
	maps.Copy(, .Data)
	 := .isColored(.isTerminal())

	 := .Caller
	 :=  != nil
	prefixFieldClashes(, .FieldMap, )
	 := make([]string, 0, len())
	for  := range  {
		 = append(, )
	}

	 := .Buffer
	if  == nil {
		 = new(bytes.Buffer)
	}

	if  {
		.printColored(, , , )
	} else {
		.printPlain(, , , )
	}

	return .Bytes(), nil
}

func ( *TextFormatter) ( *bytes.Buffer,  *Entry,  []string,  Fields) {
	 := .Caller
	 :=  != nil

	 := make([]string, 0, len()+defaultFields)
	if !.DisableTimestamp {
		 = append(, .FieldMap.resolve(FieldKeyTime))
	}
	 = append(, .FieldMap.resolve(FieldKeyLevel))
	if .Message != "" {
		 = append(, .FieldMap.resolve(FieldKeyMsg))
	}
	if .err != "" {
		 = append(, .FieldMap.resolve(FieldKeyLogrusError))
	}

	var ,  string
	if  != nil {
		if .CallerPrettyfier != nil {
			,  = .CallerPrettyfier()
		} else {
			 = .Function
			 = .File + ":" + strconv.FormatInt(int64(.Line), 10)
		}

		if  != "" {
			 = append(, .FieldMap.resolve(FieldKeyFunc))
		}
		if  != "" {
			 = append(, .FieldMap.resolve(FieldKeyFile))
		}
	}

	if !.DisableSorting {
		if .SortingFunc == nil {
			// Default sorting does not sort the "fixed keys";
			// see https://github.com/sirupsen/logrus/commit/73bc94e60c753099e8bae902f81fbd6e7dd95f26
			slices.Sort()
			 = append(, ...)
		} else {
			 = append(, ...)
			.SortingFunc()
		}
	} else {
		 = append(, ...)
	}

	for ,  := range  {
		var  any
		switch {
		case  == .FieldMap.resolve(FieldKeyTime):
			if .TimestampFormat == "" {
				 = .Time.Format(defaultTimestampFormat)
			} else {
				 = .Time.Format(.TimestampFormat)
			}
		case  == .FieldMap.resolve(FieldKeyLevel):
			 = .Level.String()
		case  == .FieldMap.resolve(FieldKeyMsg):
			 = .Message
		case  == .FieldMap.resolve(FieldKeyLogrusError):
			 = .err
		case  == .FieldMap.resolve(FieldKeyFunc) && :
			 = 
		case  == .FieldMap.resolve(FieldKeyFile) && :
			 = 
		default:
			 = []
		}
		.appendKeyValue(, , )
	}

	.WriteByte('\n')
}

func ( *TextFormatter) ( *bytes.Buffer,  *Entry,  []string,  Fields) {
	// Remove a single newline if it already exists in the message to keep
	// the behavior of logrus text_formatter the same as the stdlib log package
	.Message = strings.TrimSuffix(.Message, "\n")

	var  string
	if  := .Caller;  != nil {
		var ,  string
		if .CallerPrettyfier != nil {
			,  = .CallerPrettyfier()
		} else {
			if .Function != "" {
				 = .Function + "()"
			}
			 = .File + ":" + strconv.FormatInt(int64(.Line), 10)
		}

		if  == "" {
			 = 
		} else if  == "" {
			 = 
		} else {
			 =  + " " + 
		}
	}

	 := levelPrefix(.Level, .DisableLevelTruncation, .PadLevelText)
	switch {
	case .DisableTimestamp:
		_, _ = fmt.Fprintf(, "%s%s %-44s ", , , .Message)
	case !.FullTimestamp:
		_, _ = fmt.Fprintf(, "%s[%04d]%s %-44s ", , int(.Time.Sub(baseTimestamp)/time.Second), , .Message)
	default:
		 := .TimestampFormat
		if  == "" {
			 = defaultTimestampFormat
		}
		_, _ = fmt.Fprintf(, "%s[%s]%s %-44s ", , .Time.Format(), , .Message)
	}

	if !.DisableSorting {
		if .SortingFunc == nil {
			slices.Sort()
		} else {
			.SortingFunc()
		}
	}

	// Keys use the same color as the level-prefix.
	for ,  := range  {
		.WriteByte(' ')
		.WriteString(colorize(.Level, ))
		.WriteByte('=')
		.appendValue(, [])
	}

	.WriteByte('\n')
}

// appendKeyValue writes key=value. Keys are written verbatim (unquoted/unescaped);
// values are subject to quoting/escaping.
func ( *TextFormatter) ( *bytes.Buffer,  string,  any) {
	if .Len() > 0 {
		.WriteByte(' ')
	}
	.WriteString()
	.WriteByte('=')
	.appendValue(, )
}

func ( *TextFormatter) ( *bytes.Buffer,  any) {
	// Fast paths.
	switch v := .(type) {
	case string:
		.appendString(, )
		return
	case []byte:
		.appendBytes(, )
		return
	case bool:
		var  [8]byte
		.appendBytes(, strconv.AppendBool([:0], ))
		return
	case error:
		.appendError(, )
		return
	case fmt.Stringer:
		.appendStringer(, )
		return
	}

	// Handle common primitives.
	var  [64]byte
	var  []byte

	switch v := .(type) {
	case int:
		 = strconv.AppendInt([:0], int64(), 10)
	case int8:
		 = strconv.AppendInt([:0], int64(), 10)
	case int16:
		 = strconv.AppendInt([:0], int64(), 10)
	case int32:
		 = strconv.AppendInt([:0], int64(), 10)
	case int64:
		 = strconv.AppendInt([:0], , 10)

	case uint:
		 = strconv.AppendUint([:0], uint64(), 10)
	case uint8:
		 = strconv.AppendUint([:0], uint64(), 10)
	case uint16:
		 = strconv.AppendUint([:0], uint64(), 10)
	case uint32:
		 = strconv.AppendUint([:0], uint64(), 10)
	case uint64:
		 = strconv.AppendUint([:0], , 10)
	case uintptr:
		 = strconv.AppendUint([:0], uint64(), 10)

	case float32:
		 = strconv.AppendFloat([:0], float64(), 'g', -1, 32)
	case float64:
		 = strconv.AppendFloat([:0], , 'g', -1, 64)

	default:
		.appendString(, fmt.Sprint())
		return
	}

	.appendNumeric(, )
}

func ( *TextFormatter) ( *bytes.Buffer,  string) {
	 := .ForceQuote || (.QuoteEmptyFields && len() == 0) || (!.DisableQuote && needsQuoting())
	if ! {
		.WriteString()
		return
	}
	if len() == 0 {
		.WriteString(`""`)
		return
	}

	var  [128]byte
	.Write(strconv.AppendQuote([:0], ))
}

func ( *TextFormatter) ( *bytes.Buffer,  []byte) {
	 := .ForceQuote || (.QuoteEmptyFields && len() == 0) || (!.DisableQuote && needsQuotingBytes())
	if ! {
		.Write()
		return
	}
	if len() == 0 {
		.WriteString(`""`)
		return
	}

	var  [128]byte
	.Write(strconv.AppendQuote([:0], string()))
}

func ( *TextFormatter) ( *bytes.Buffer,  []byte) {
	if .ForceQuote {
		var  [128]byte
		.Write(strconv.AppendQuote([:0], string()))
		return
	}
	.Write()
}

func ( *TextFormatter) ( *bytes.Buffer,  error) {
	defer .recoverValue(, , "Error")

	.appendString(, .Error())
}

func ( *TextFormatter) ( *bytes.Buffer,  fmt.Stringer) {
	defer .recoverValue(, , "String")

	.appendString(, .String())
}

func ( *TextFormatter) ( *bytes.Buffer,  any,  string) {
	if  := recover();  != nil {
		 := reflect.ValueOf()
		if .Kind() == reflect.Pointer && .IsNil() {
			.appendString(, "<nil>")
		} else {
			.appendString(, fmt.Sprintf("%%!v(PANIC=%s method: %v)", , ))
		}
	}
}

// needsQuoting returns true if the string contains any byte that
// requires quoting. It returns false when every byte is "safe" according
// to isSafeByte.
func needsQuoting( string) bool {
	// use an index loop (avoid rune decoding).
	for  := range len() {
		 := []
		if !isSafeByte() {
			return true
		}
	}
	return false
}

// needsQuotingBytes returns true if the byte slice contains any byte that
// requires quoting. It returns false when every byte is "safe" according
// to isSafeByte.
func needsQuotingBytes( []byte) bool {
	for ,  := range  {
		if !isSafeByte() {
			return true
		}
	}
	return false
}

// isSafeByte returns true if the byte is allowed unquoted (ASCII and in the allowlist).
// It purposely uses byte arithmetic (no runes) for performance.
func isSafeByte( byte) bool {
	 :=  < 0x80 && (( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z') || ( >= '0' &&  <= '9'))
	if  {
		return true
	}
	switch  {
	case '-', '.', '_', '/', '@', '^', '+':
		return true
	default:
		return false
	}
}