package logrusimport ()var (// qualified package name, cached at first use logrusPackage string// Positions in the call stack when tracing to report the calling method. // // Start at the bottom of the stack before the package-name cache is primed. minimumCallerDepth = 1// Used for caller information initialisation callerInitOnce sync.Once)const ( maximumCallerDepth int = 25 knownLogrusFrames int = 4)// ErrorKey defines the key when adding errors using [WithError], [Logger.WithError].varErrorKey = "error"// Entry represents a single log event. It may be either an intermediate// entry (created via WithField(s), WithContext, etc.) or a final entry// that is emitted when one of the level methods (Trace, Debug, Info,// Warn, Error, Fatal, Panic) is called.//// An Entry always belongs to a Logger. A nil Logger is invalid and will// cause a panic when the entry is logged. Use [NewEntry] or Logger methods// to construct entries.//// Entries are safe to reuse for adding fields and may be passed around// to avoid field duplication. Each log operation operates on a copy// of the Entry’s data to avoid mutation during formatting.////nolint:recvcheck // Entry methods intentionally use both pointer and value receivers.typeEntrystruct {// Logger is the Logger that owns this entry and is responsible for // formatting, hooks, and output. It must not be nil. An Entry without // a Logger is invalid and will panic when logged. Logger *Logger// Data contains all user-defined fields attached to this entry. Data Fields// Time is the timestamp for the log event. If zero when the entry is // logged, it defaults to the current time. Time time.Time// Level is the severity of the log entry. It is set when the entry // is fired and reflects the level used for that log call. Level Level// Caller contains the calling method information. // // When [Logger.ReportCaller] is enabled, Caller is populated automatically at // log time if it is nil. Hooks and formatters may inspect Caller. // // Applications generally should not modify Caller unless they intentionally // want to provide custom caller information. Caller *runtime.Frame// Message is the log message supplied to one of the logging methods // (Trace, Debug, Info, Warn, Error, Fatal, or Panic). It is set when // the entry is logged. Message string// Buffer is a reusable buffer provided to the formatter. It is set // before formatting in the normal log path; when nil, formatters // allocate their own. Buffer *bytes.Buffer// Context carries user-provided context for hooks and formatters. Context context.Context// err contains internal field-formatting errors. err string}// NewEntry creates a new [Entry] associated with the provided Logger.// The logger must not be nil. Passing a nil logger results in a// panic when a logging method (e.g., [Entry.Info], [Entry.Error], etc.)// is called.func ( *Logger) *Entry {return &Entry{Logger: ,// Reserve default predefined fields and a little extra room.Data: make(Fields, defaultFields+3), }}// Dup creates a copy of the entry for further modification.//// Data is cloned to avoid mutating the original entry. Other fields// (Logger, Time, Context, etc.) are copied by value.func ( *Entry) () *Entry { := .dup() .Data = maps.Clone(.Data)return}// dup copies the entry fields shared by derived entries except Data, which// callers must copy or initialize as appropriate for their use.func ( *Entry) () *Entry {return &Entry{Logger: .Logger,Time: .Time,Caller: .Caller,Context: .Context,err: .err, }}// Bytes returns the bytes representation of this entry from the formatter.func ( *Entry) () ([]byte, error) {// Snapshot the formatter under the lock to protect against concurrent // SetFormatter calls, then release the lock before formatting. // This avoids a data race and prevents a deadlock if Format() triggers // reentrant logging (e.g., a field's MarshalJSON calls logrus). // // See: // // - https://github.com/sirupsen/logrus/issues/1440 // - https://github.com/sirupsen/logrus/issues/1448 .Logger.mu.Lock() := .Logger.Formatter .Logger.mu.Unlock()return .Format()}// String returns the string representation from the reader and ultimately the// formatter.func ( *Entry) () (string, error) { , := .Bytes()if != nil {return"", } := string()return , nil}// WithError adds an error as single field (using the key defined in [ErrorKey])// to the Entry.func ( *Entry) ( error) *Entry {return .WithField(ErrorKey, )}// WithContext adds a context to the Entry.func ( *Entry) ( context.Context) *Entry { := .dup() .Data = maps.Clone(.Data) .Context = return}// WithField adds a single field to the Entry.func ( *Entry) ( string, any) *Entry { := .dup() .Data = maps.Clone(.Data) .addField(, )return}// WithFields adds a map of fields to the Entry.func ( *Entry) ( Fields) *Entry { := .dup() .Data = make(Fields, len(.Data)+len())maps.Copy(.Data, .Data)for , := range { .addField(, ) }return}// WithTime overrides the time of the Entry.func ( *Entry) ( time.Time) *Entry { := .dup() .Data = maps.Clone(.Data) .Time = return}func ( *Entry) ( string, any) {if , := .(error); ! { := reflect.TypeOf()if != nil && (.Kind() == reflect.Func || .Kind() == reflect.Pointer && .Elem().Kind() == reflect.Func) {if .err != "" { .err += ", skipping unsupported field " + strconv.Quote() } else { .err = "skipping unsupported field " + strconv.Quote() }return } }if .Data == nil { .Data = make(Fields, 1) } .Data[] = }// getPackageName reduces a fully qualified function name to the package name// There really ought to be a better way...func getPackageName( string) string {for { := strings.LastIndex(, ".") := strings.LastIndex(, "/")if > { = [:] } else {break } }return}// getCaller retrieves the name of the first non-logrus calling functionfunc getCaller() *runtime.Frame {// cache this package's fully-qualified namecallerInitOnce.Do(func() { := make([]uintptr, maximumCallerDepth) _ = runtime.Callers(0, )// dynamic get the package name and the minimum caller depthfor := rangemaximumCallerDepth { := runtime.FuncForPC([]).Name()ifstrings.Contains(, "getCaller") {logrusPackage = getPackageName()break } }minimumCallerDepth = knownLogrusFrames })// Restrict the lookback frames to avoid runaway lookups := make([]uintptr, maximumCallerDepth) := runtime.Callers(minimumCallerDepth, ) := runtime.CallersFrames([:])for , := .Next(); ; , = .Next() { := getPackageName(.Function)// If the caller isn't part of this package, we're doneif != logrusPackage {return & } }// if we got here, we failed to find the caller's contextreturnnil}// HasCaller reports whether this Entry contains caller information.//// Caller may be set explicitly, or populated at log time when// [Logger.ReportCaller] is enabled.//// Deprecated: use [Entry.Caller] != nil instead.////go:fix inlinefunc ( Entry) () bool {return .Caller != nil}func ( *Entry) ( Level, bool, ...any) { .log(, , sprint(...))}func ( *Entry) ( Level, bool, string, ...any) { .log(, , fmt.Sprintf(, ...))}// logln uses Sprintln for multiple arguments to preserve Println-style// spacing between args, then trims the trailing newline.func ( *Entry) ( Level, bool, ...any) {iflen() <= 1 { .log(, , sprint(...))return } := fmt.Sprintln(...) = [:len()-1] // Trim the newline added by Sprintln; logging adds its own. .log(, , )}// log writes msg at level. If panicAfter is true, it panics with the fully// populated entry after hooks and output have completed.//// The explicit flag keeps panic behavior limited to Panic, Panicf, and// Panicln while avoiding a return value used only as the panic value.// See #1283 and commits f96066e and 5f8c666.func ( *Entry) ( Level, bool, string) { := .dup() .Data = maps.Clone(.Data)if .Time.IsZero() { .Time = time.Now() } .Level = .Message = := .Logger .mu.Lock() := .ReportCaller := .getBufferPool() .mu.Unlock()// Preserve explicitly set caller information.if && .Caller == nil { .Caller = getCaller() }// Select hooks based on the level for this log call. Hooks receive the // Entry and may mutate it, but that does not affect which hooks are // fired for this event. := .hooksForLevel() .fireHooks() := .Get()deferfunc() { .Buffer = nil .Reset() .Put() }() .Reset() .Buffer = .write() .Buffer = nil// Panic here so the panic value contains the fully populated entry without // requiring log to return it to the caller.if {panic() }}func ( *Entry) () ( BufferPool) {if .Logger.BufferPool != nil {return .Logger.BufferPool }returnbufferPool}func ( *Entry) ( []Hook) {for , := range {if := .Fire(); != nil { _, _ = fmt.Fprintln(os.Stderr, "Failed to fire hook:", )return } }}func ( *Entry) () {// Snapshot the formatter under the lock to protect against concurrent // SetFormatter calls, then release the lock before formatting. // This avoids a deadlock when Format() triggers reentrant logging (e.g., // a field's MarshalJSON calls logrus). See #1448, #1440. .Logger.mu.Lock() := .Logger.Formatter .Logger.mu.Unlock() , := .Format()if != nil { _, _ = fmt.Fprintln(os.Stderr, "Failed to format entry:", )return }// Re-acquire the lock to serialize writes to the underlying io.Writer. .Logger.mu.Lock()defer .Logger.mu.Unlock()if , := .Logger.Out.Write(); != nil { _, _ = fmt.Fprintln(os.Stderr, "Failed to write to log:", ) }}// Log logs a message at the specified level.//// Using Log with [PanicLevel] or [FatalLevel] intentionally does not// trigger a panic or exit. Log treats the level as logging severity only;// use [Entry.Panic] or [Entry.Fatal] when those side effects are desired.func ( *Entry) ( Level, ...any) {const = falseif .Logger.IsLevelEnabled() { .logArgs(, , ...) }}func ( *Entry) ( ...any) { .Log(TraceLevel, ...)}func ( *Entry) ( ...any) { .Log(DebugLevel, ...)}func ( *Entry) ( ...any) { .Info(...)}func ( *Entry) ( ...any) { .Log(InfoLevel, ...)}func ( *Entry) ( ...any) { .Log(WarnLevel, ...)}func ( *Entry) ( ...any) { .Warn(...)}func ( *Entry) ( ...any) { .Log(ErrorLevel, ...)}func ( *Entry) ( ...any) { .Log(FatalLevel, ...) .Logger.Exit(1)}func ( *Entry) ( ...any) {const = trueif .Logger.IsLevelEnabled(PanicLevel) { .logArgs(PanicLevel, , ...) }}// Entry Printf family functions// Logf logs a formatted message at the specified level.//// Using Logf with [PanicLevel] or [FatalLevel] intentionally does not// trigger a panic or exit. Logf treats the level as logging severity only;// use [Entry.Panicf] or [Entry.Fatalf] when those side effects are desired.func ( *Entry) ( Level, string, ...any) {const = falseif .Logger.IsLevelEnabled() { .logf(, , , ...) }}func ( *Entry) ( string, ...any) { .Logf(TraceLevel, , ...)}func ( *Entry) ( string, ...any) { .Logf(DebugLevel, , ...)}func ( *Entry) ( string, ...any) { .Logf(InfoLevel, , ...)}func ( *Entry) ( string, ...any) { .Infof(, ...)}func ( *Entry) ( string, ...any) { .Logf(WarnLevel, , ...)}func ( *Entry) ( string, ...any) { .Warnf(, ...)}func ( *Entry) ( string, ...any) { .Logf(ErrorLevel, , ...)}func ( *Entry) ( string, ...any) { .Logf(FatalLevel, , ...) .Logger.Exit(1)}func ( *Entry) ( string, ...any) {const = trueif .Logger.IsLevelEnabled(PanicLevel) { .logf(PanicLevel, , , ...) }}// Entry Println family functions// Logln logs a message at the specified level with Println-style spacing.//// Using Logln with [PanicLevel] or [FatalLevel] intentionally does not// trigger a panic or exit. Logln treats the level as logging severity only;// use [Entry.Panicln] or [Entry.Fatalln] when those side effects are desired.func ( *Entry) ( Level, ...any) {const = falseif .Logger.IsLevelEnabled() { .logln(, , ...) }}func ( *Entry) ( ...any) { .Logln(TraceLevel, ...)}func ( *Entry) ( ...any) { .Logln(DebugLevel, ...)}func ( *Entry) ( ...any) { .Logln(InfoLevel, ...)}func ( *Entry) ( ...any) { .Infoln(...)}func ( *Entry) ( ...any) { .Logln(WarnLevel, ...)}func ( *Entry) ( ...any) { .Warnln(...)}func ( *Entry) ( ...any) { .Logln(ErrorLevel, ...)}func ( *Entry) ( ...any) { .Logln(FatalLevel, ...) .Logger.Exit(1)}func ( *Entry) ( ...any) {const = trueif .Logger.IsLevelEnabled(PanicLevel) { .logln(PanicLevel, , ...) }}// sprint is fmt.Sprint with fast paths for zero or one string argument.func sprint( ...any) string {switchlen() {case0:return""case1:if , := [0].(string); {return } }returnfmt.Sprint(...)}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.