Showing preview only (224K chars total). Download the full file or copy to clipboard to get everything.
Repository: sirupsen/logrus
Branch: master
Commit: 9f0600962f75
Files: 58
Total size: 210.1 KB
Directory structure:
gitextract_3g0yan4k/
├── .github/
│ └── workflows/
│ └── ci.yaml
├── .gitignore
├── .golangci.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── alt_exit.go
├── alt_exit_test.go
├── appveyor.yml
├── buffer_pool.go
├── doc.go
├── entry.go
├── entry_bench_test.go
├── entry_test.go
├── example_basic_test.go
├── example_custom_caller_test.go
├── example_default_field_value_test.go
├── example_function_test.go
├── example_global_hook_test.go
├── example_hook_test.go
├── exported.go
├── formatter.go
├── formatter_bench_test.go
├── go.mod
├── go.sum
├── hook_test.go
├── hooks/
│ ├── slog/
│ │ ├── slog.go
│ │ └── slog_test.go
│ ├── syslog/
│ │ ├── README.md
│ │ ├── syslog.go
│ │ └── syslog_test.go
│ ├── test/
│ │ ├── test.go
│ │ └── test_test.go
│ └── writer/
│ ├── README.md
│ ├── writer.go
│ └── writer_test.go
├── hooks.go
├── internal/
│ └── testutils/
│ └── testutils.go
├── json_formatter.go
├── json_formatter_test.go
├── level.go
├── level_test.go
├── logger.go
├── logger_bench_test.go
├── logger_test.go
├── logrus.go
├── logrus_test.go
├── terminal_check_appengine.go
├── terminal_check_bsd.go
├── terminal_check_no_terminal.go
├── terminal_check_notappengine.go
├── terminal_check_solaris.go
├── terminal_check_unix.go
├── terminal_check_windows.go
├── text_formatter.go
├── text_formatter_test.go
├── writer.go
└── writer_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/ci.yaml
================================================
name: CI
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
pull-requests: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [push, pull_request]
env:
GOTOOLCHAIN: local
jobs:
lint:
name: Golang-CI Lint
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Install Go
uses: actions/setup-go@v6
with:
go-version: stable
- name: Install golangci-lint
uses: golangci/golangci-lint-action@v9
cross:
name: Cross
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Install Go
uses: actions/setup-go@v6
with:
go-version: stable
- name: Build
run: |
for target in $(go tool dist list); do
echo "Building for $target"
GOOS=${target%/*} GOARCH=${target#*/} go build ./...
done
test:
name: Unit test
timeout-minutes: 10
strategy:
matrix:
go-version: [stable, oldstable, 1.23.x]
platform: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
defaults:
run:
shell: bash
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Install Go
uses: actions/setup-go@v6
with:
go-version: ${{ matrix.go-version }}
- name: Test
run: go test -race -v ./...
================================================
FILE: .gitignore
================================================
logrus
vendor
.idea/
================================================
FILE: .golangci.yml
================================================
version: "2"
linters:
enable:
- asasalint
- asciicheck
- bidichk
- contextcheck
- durationcheck
- errchkjson
- errorlint
- exhaustive
- gocheckcompilerdirectives
- gochecksumtype
- gosec
- gosmopolitan
- loggercheck
- makezero
- musttag
- nilerr
- nilnesserr
- noctx
- reassign
- recvcheck
- testifylint
- unparam
exclusions:
presets:
- legacy
- std-error-handling
rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gosec
- musttag
- noctx # TODO: enable once we switch to Go 1.24+.
================================================
FILE: CHANGELOG.md
================================================
# 1.9.4
Fixes:
* Remove uses of deprecated `ioutil` package
Features:
* Add GNU/Hurd support
* Add WASI wasip1 support
Code quality:
* Update minimum supported Go version to 1.17
* Documentation updates
# 1.9.3
Fixes:
* Re-apply fix for potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)
* Fix panic in Writer
# 1.9.2
Fixes:
* Revert Writer DoS fix (#1376) due to regression
# 1.9.1
Fixes:
* Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)
# 1.9.0
Fixes:
* Multiple concurrency and race condition fixes
* Improve Windows terminal and ANSI handling
Code quality:
* Internal cleanups and modernization
# 1.8.3
Fixes:
* Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)
# 1.8.2
Features:
* Add support for the logger private buffer pool (#1253)
Fixes:
* Fix race condition for SetFormatter and SetReportCaller
* Fix data race in hooks test package
# 1.8.1
Code quality:
* move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer
* improve timestamp format documentation
Fixes:
* fix race condition on logger hooks
# 1.8.0
Correct versioning number replacing v1.7.1.
# 1.7.1
Beware this release has introduced a new public API and its semver is therefore incorrect.
Code quality:
* use go 1.15 in travis
* use magefile as task runner
Fixes:
* small fixes about new go 1.13 error formatting system
* Fix for long time race condiction with mutating data hooks
Features:
* build support for zos
# 1.7.0
Fixes:
* the dependency toward a windows terminal library has been removed
Features:
* a new buffer pool management API has been added
* a set of `<LogLevel>Fn()` functions have been added
# 1.6.0
Fixes:
* end of line cleanup
* revert the entry concurrency bug fix which leads to deadlock under some circumstances
* update dependency on go-windows-terminal-sequences to fix a crash with go 1.14
Features:
* add an option to the `TextFormatter` to completely disable fields quoting
# 1.5.0
Code quality:
* add golangci linter run on travis
Fixes:
* add mutex for hooks concurrent access on `Entry` data
* caller function field for go1.14
* fix build issue for gopherjs target
Feature:
* add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level
* add a `DisableHTMLEscape` option in the `JSONFormatter`
* add `ForceQuote` and `PadLevelText` options in the `TextFormatter`
# 1.4.2
* Fixes build break for plan9, nacl, solaris
# 1.4.1
This new release introduces:
* Enhance TextFormatter to not print caller information when they are empty (#944)
* Remove dependency on golang.org/x/crypto (#932, #943)
Fixes:
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
# 1.4.0
This new release introduces:
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
Fixes:
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
* Fix infinite recursion on unknown `Level.String()` (#907)
* Fix race condition in `getCaller` (#916).
# 1.3.0
This new release introduces:
* Log, Logf, Logln functions for Logger and Entry that take a Level
Fixes:
* Building prometheus node_exporter on AIX (#840)
* Race condition in TextFormatter (#468)
* Travis CI import path (#868)
* Remove coloured output on Windows (#862)
* Pointer to func as field in JSONFormatter (#870)
* Properly marshal Levels (#873)
# 1.2.0
This new release introduces:
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
* A new trace level named `Trace` whose level is below `Debug`
* A configurable exit function to be called upon a Fatal trace
* The `Level` object now implements `encoding.TextUnmarshaler` interface
# 1.1.1
This is a bug fix release.
* fix the build break on Solaris
* don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized
# 1.1.0
This new release introduces:
* several fixes:
* a fix for a race condition on entry formatting
* proper cleanup of previously used entries before putting them back in the pool
* the extra new line at the end of message in text formatter has been removed
* a new global public API to check if a level is activated: IsLevelEnabled
* the following methods have been added to the Logger object
* IsLevelEnabled
* SetFormatter
* SetOutput
* ReplaceHooks
* introduction of go module
* an indent configuration for the json formatter
* output colour support for windows
* the field sort function is now configurable for text formatter
* the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
# 1.0.6
This new release introduces:
* a new api WithTime which allows to easily force the time of the log entry
which is mostly useful for logger wrapper
* a fix reverting the immutability of the entry given as parameter to the hooks
a new configuration field of the json formatter in order to put all the fields
in a nested dictionary
* a new SetOutput method in the Logger
* a new configuration of the textformatter to configure the name of the default keys
* a new configuration of the text formatter to disable the level truncation
# 1.0.5
* Fix hooks race (#707)
* Fix panic deadlock (#695)
# 1.0.4
* Fix race when adding hooks (#612)
* Fix terminal check in AppEngine (#635)
# 1.0.3
* Replace example files with testable examples
# 1.0.2
* bug: quote non-string values in text formatter (#583)
* Make (*Logger) SetLevel a public method
# 1.0.1
* bug: fix escaping in text formatter (#575)
# 1.0.0
* Officially changed name to lower-case
* bug: colors on Windows 10 (#541)
* bug: fix race in accessing level (#512)
# 0.11.5
* feature: add writer and writerlevel to entry (#372)
# 0.11.4
* bug: fix undefined variable on solaris (#493)
# 0.11.3
* formatter: configure quoting of empty values (#484)
* formatter: configure quoting character (default is `"`) (#484)
* bug: fix not importing io correctly in non-linux environments (#481)
# 0.11.2
* bug: fix windows terminal detection (#476)
# 0.11.1
* bug: fix tty detection with custom out (#471)
# 0.11.0
* performance: Use bufferpool to allocate (#370)
* terminal: terminal detection for app-engine (#343)
* feature: exit handler (#375)
# 0.10.0
* feature: Add a test hook (#180)
* feature: `ParseLevel` is now case-insensitive (#326)
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
* performance: avoid re-allocations on `WithFields` (#335)
# 0.9.0
* logrus/text_formatter: don't emit empty msg
* logrus/hooks/airbrake: move out of main repository
* logrus/hooks/sentry: move out of main repository
* logrus/hooks/papertrail: move out of main repository
* logrus/hooks/bugsnag: move out of main repository
* logrus/core: run tests with `-race`
* logrus/core: detect TTY based on `stderr`
* logrus/core: support `WithError` on logger
* logrus/core: Solaris support
# 0.8.7
* logrus/core: fix possible race (#216)
* logrus/doc: small typo fixes and doc improvements
# 0.8.6
* hooks/raven: allow passing an initialized client
# 0.8.5
* logrus/core: revert #208
# 0.8.4
* formatter/text: fix data race (#218)
# 0.8.3
* logrus/core: fix entry log level (#208)
* logrus/core: improve performance of text formatter by 40%
* logrus/core: expose `LevelHooks` type
* logrus/core: add support for DragonflyBSD and NetBSD
* formatter/text: print structs more verbosely
# 0.8.2
* logrus: fix more Fatal family functions
# 0.8.1
* logrus: fix not exiting on `Fatalf` and `Fatalln`
# 0.8.0
* logrus: defaults to stderr instead of stdout
* hooks/sentry: add special field for `*http.Request`
* formatter/text: ignore Windows for colors
# 0.7.3
* formatter/\*: allow configuration of timestamp layout
# 0.7.2
* formatter/text: Add configuration option for time format (#158)
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014 Simon Eskildsen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [](https://pkg.go.dev/github.com/sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger.
**Logrus is in maintenance-mode.** We will not be introducing new features. It's
simply too hard to do in a way that won't break many people's projects, which is
the last thing you want from your Logging library (again...).
This does not mean Logrus is dead. Logrus will continue to be maintained for
security, (backwards compatible) bug fixes, and performance (where we are
limited by the interface).
I believe Logrus' biggest contribution is to have played a part in today's
widespread use of structured logging in Golang. There doesn't seem to be a
reason to do a major, breaking iteration into Logrus V2, since the fantastic Go
community has built those independently. Many fantastic alternatives have sprung
up. Logrus would look like those, had it been re-designed with what we know
about structured logging in Go today. Check out, for example,
[Zerolog][zerolog], [Zap][zap], and [Apex][apex].
[zerolog]: https://github.com/rs/zerolog
[zap]: https://github.com/uber-go/zap
[apex]: https://github.com/apex/log
**Seeing weird case-sensitive problems?** It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments
experienced problems with the upper-case variant, so the lower-case was decided.
Everything using `logrus` will need to use the lower-case:
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
To fix Glide, see [these
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
For an in-depth explanation of the casing issue, see [this
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):

With `logrus.SetFormatter(&logrus.JSONFormatter{})`, for easy parsing by logstash
or Splunk:
```text
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
{"level":"warning","msg":"The group's number increased tremendously!",
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
```
With the default `logrus.SetFormatter(&logrus.TextFormatter{})` when a TTY is not
attached, the output is compatible with the
[logfmt](https://pkg.go.dev/github.com/kr/logfmt) format:
```text
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
```
To ensure this behaviour even if a TTY is attached, set your formatter as follows:
```go
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
```
#### Logging Method Name
If you wish to add the calling method as a field, instruct the logger via:
```go
logrus.SetReportCaller(true)
```
This adds the caller as 'method' like so:
```json
{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
```
```text
time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
```
Note that this does add measurable overhead - the cost will depend on the version of Go, but is
between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
environment via benchmarks:
```bash
go test -bench=.*CallerTracing
```
#### Case-sensitivity
The organization's name was changed to lower-case--and this will not be changed
back. If you are getting import conflicts due to case sensitivity, please use
the lower-case import: `github.com/sirupsen/logrus`.
#### Example
The simplest way to use Logrus is simply the package-level exported logger:
```go
package main
import "github.com/sirupsen/logrus"
func main() {
logrus.WithFields(logrus.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
```
Note that it's completely api-compatible with the stdlib logger, so you can
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
and you'll now have the flexibility of Logrus. You can customize it all you
want:
```go
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
// A common pattern is to re-use fields between logging statements by re-using
// the logrus.Entry returned from WithFields()
contextLogger := log.WithFields(log.Fields{
"common": "this is a common field",
"other": "I also should be logged always",
})
contextLogger.Info("I'll be logged with common and other field")
contextLogger.Info("Me too")
}
```
For more advanced usage such as logging to multiple locations from the same
application, you can also create an instance of the `logrus` Logger:
```go
package main
import (
"os"
"github.com/sirupsen/logrus"
)
// Create a new instance of the logger. You can have any number of instances.
var logger = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
logger.Out = os.Stdout
// You could set this to any `io.Writer` such as a file
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// if err == nil {
// logger.Out = file
// } else {
// logger.Info("Failed to log to file, using default stderr")
// }
logger.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
```
#### Fields
Logrus encourages careful, structured logging through logging fields instead of
long, unparseable error messages. For example, instead of: `logrus.Fatalf("Failed
to send event %s to topic %s with key %d")`, you should log the much more
discoverable:
```go
logrus.WithFields(logrus.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
```
We've found this API forces you to think about logging in a way that produces
much more useful logging messages. We've been in countless situations where just
a single added field to a log statement that was already there would've saved us
hours. The `WithFields` call is optional.
In general, with Logrus using any of the `printf`-family functions should be
seen as a hint you should add a field, however, you can still use the
`printf`-family functions with Logrus.
#### Default Fields
Often it's helpful to have fields _always_ attached to log statements in an
application or parts of one. For example, you may want to always log the
`request_id` and `user_ip` in the context of a request. Instead of writing
`logger.WithFields(logrus.Fields{"request_id": request_id, "user_ip": user_ip})` on
every line, you can create a `logrus.Entry` to pass around instead:
```go
requestLogger := logger.WithFields(logrus.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") // will log request_id and user_ip
requestLogger.Warn("something not great happened")
```
#### Hooks
You can add hooks for logging levels. For example to send errors to an exception
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
multiple places simultaneously, e.g. syslog.
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
`init`:
```go
package main
import (
"log/syslog"
"github.com/sirupsen/logrus"
airbrake "gopkg.in/gemnasium/logrus-airbrake-hook.v2"
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
)
func init() {
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
logrus.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
logrus.Error("Unable to connect to local syslog daemon")
} else {
logrus.AddHook(hook)
}
}
```
Note: Syslog hooks also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
#### Level logging
Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
```go
logrus.Trace("Something very low level.")
logrus.Debug("Useful debugging information.")
logrus.Info("Something noteworthy happened!")
logrus.Warn("You should probably take a look at this.")
logrus.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
logrus.Fatal("Bye.")
// Calls panic() after logging
logrus.Panic("I'm bailing.")
```
You can set the logging level on a `Logger`, then it will only log entries with
that severity or anything above it:
```go
// Will log anything that is info or above (warn, error, fatal, panic). Default.
logrus.SetLevel(logrus.InfoLevel)
```
It may be useful to set `logrus.Level = logrus.DebugLevel` in a debug or verbose
environment if your application has that.
Note: If you want different log levels for global (`logrus.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging).
#### Entries
Besides the fields added with `WithField` or `WithFields` some fields are
automatically added to all logging events:
1. `time`. The timestamp when the entry was created.
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
the `AddFields` call. E.g. `Failed to send event.`
3. `level`. The logging level. E.g. `info`.
#### Environments
Logrus has no notion of environment.
If you wish for hooks and formatters to only be used in specific environments,
you should handle that yourself. For example, if your application has a global
variable `Environment`, which is a string representation of the environment you
could do:
```go
import (
"github.com/sirupsen/logrus"
)
func init() {
// do something here to set environment depending on an environment variable
// or command-line flag
if Environment == "production" {
logrus.SetFormatter(&logrus.JSONFormatter{})
} else {
// The TextFormatter is default, you don't actually have to do this.
logrus.SetFormatter(&logrus.TextFormatter{})
}
}
```
This configuration is how `logrus` was intended to be used, but JSON in
production is mostly only useful if you do log aggregation with tools like
Splunk or Logstash.
#### Formatters
The built-in logging formatters are:
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
without colors.
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
field to `true`. To force no colored output even if there is a TTY set the
`DisableColors` field to `true`. For Windows, see
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
* When colors are enabled, levels are truncated to 4 characters by default. To disable
truncation set the `DisableLevelTruncation` field to `true`.
* When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text.
* All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#TextFormatter).
* `logrus.JSONFormatter`. Logs fields as JSON.
* All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#JSONFormatter).
Third-party logging formatters:
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo.
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Save log to files.
* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.
* [`easy-logrus-formatter`](https://github.com/WeiZhixiong/easy-logrus-formatter). Provide a user-friendly formatter for logrus.
* [`redactrus`](https://github.com/ibreakthecloud/redactrus). Redacts sensitive information like password, apikeys, email, etc. from logs.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
`Fields` type (`map[string]any`) with all your fields as well as the
default ones (see Entries section above):
```go
type MyJSONFormatter struct{}
logrus.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err)
}
return append(serialized, '\n'), nil
}
```
#### Logger as an `io.Writer`
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
```go
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
```
Each line written to that writer will be printed the usual way, using formatters
and hooks. The level for those entries is `info`.
This means that we can override the standard library logger easily:
```go
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
```
#### Rotation
Log rotation is not provided with Logrus. Log rotation should be done by an
external program (like `logrotate(8)`) that can compress and delete old log
entries. It should not be a feature of the application-level logger.
#### Tools
| Tool | Description |
| ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
#### Testing
Logrus has a built-in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go
import(
"testing"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
)
func TestSomething(t*testing.T){
logger, hook := test.NewNullLogger()
logger.Error("Helloerror")
assert.Equal(t, 1, len(hook.Entries))
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
hook.Reset()
assert.Nil(t, hook.LastEntry())
}
```
#### Fatal handlers
Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before
logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shut down. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
```go
// ...
handler := func() {
// gracefully shut down something...
}
logrus.RegisterExitHandler(handler)
// ...
```
#### Thread safety
By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
Situations when locking is not needed include:
* You have no hooks registered, or hooks calling is already thread-safe.
* Writing to logger.Out is already thread-safe, for example:
1) logger.Out is protected by locks.
2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing)
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
================================================
FILE: alt_exit.go
================================================
package logrus
// The following code was sourced and modified from the
// https://github.com/tebeka/atexit package governed by the following license:
//
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import (
"fmt"
"os"
)
var handlers = []func(){}
func runHandler(handler func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
}
}()
handler()
}
func runHandlers() {
for _, handler := range handlers {
runHandler(handler)
}
}
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
func Exit(code int) {
runHandlers()
os.Exit(code)
}
// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler)
}
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func DeferExitHandler(handler func()) {
handlers = append([]func(){handler}, handlers...)
}
================================================
FILE: alt_exit_test.go
================================================
package logrus_test
import (
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/sirupsen/logrus"
)
func TestRegister(t *testing.T) {
if reexecTest(t, "register", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.RegisterExitHandler(func() { appendLine(outfile, "first") })
logrus.RegisterExitHandler(func() { appendLine(outfile, "second") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "out.txt")
cmd := reexecCommand(t, "register", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := "first\nsecond\n"
assertFileContent(t, outfile, want, out)
}
func TestDefer(t *testing.T) {
if reexecTest(t, "defer", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.DeferExitHandler(func() { appendLine(outfile, "first") })
logrus.DeferExitHandler(func() { appendLine(outfile, "second") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "out.txt")
cmd := reexecCommand(t, "defer", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := "second\nfirst\n"
assertFileContent(t, outfile, want, out)
}
func TestHandler(t *testing.T) {
const payload = "payload"
if reexecTest(t, "handler", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.RegisterExitHandler(func() {
_ = os.WriteFile(outfile, []byte(payload), 0o666)
})
logrus.RegisterExitHandler(func() { panic("bad handler") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "outfile.out")
cmd := reexecCommand(t, "handler", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := payload
assertFileContent(t, outfile, want, out)
}
func appendLine(path, s string) {
b, err := os.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
_, _ = os.Stderr.WriteString("appendLine: read " + path + ": " + err.Error() + "\n")
os.Exit(1)
}
b = append(b, []byte(s+"\n")...)
if err := os.WriteFile(path, b, 0o666); err != nil {
_, _ = os.Stderr.WriteString("appendLine: write " + path + ": " + err.Error() + "\n")
os.Exit(1)
}
}
func assertFileContent(t *testing.T, path, want string, childOut []byte) {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("can't read output file: %v (child out=%s)", err, childOut)
}
if got := string(b); got != want {
t.Fatalf("unexpected file content: got %q, want %q (child out=%s)", got, want, childOut)
}
}
const tokenPrefix = "reexectest-"
// argv0Token computes a short deterministic token for (t.Name(), name).
func argv0Token(t *testing.T, name string) string {
sum := sha256.Sum256([]byte(t.Name() + "\x00" + name))
return tokenPrefix + hex.EncodeToString(sum[:8]) // 16 hex chars
}
// reexecTest runs fn if this process is the child (argv0 == token).
// Returns true in the child (caller should return).
func reexecTest(t *testing.T, name string, f func(t *testing.T)) bool {
t.Helper()
if os.Args[0] != argv0Token(t, name) {
return false
}
// Scrub the "-test.run=<pattern>" that was injected by reexecCommand.
origArgs := os.Args
if len(os.Args) > 1 && strings.HasPrefix(os.Args[1], "-test.run=") {
os.Args = append(os.Args[:1], os.Args[2:]...)
defer func() { os.Args = origArgs }()
}
f(t)
return true
}
// reexecCommand builds a command that execs the current test binary (exe)
// with argv0 set to token and "-test.run=<pattern>" so the child runs only
// this test/subtest. extraArgs are appended after that; the parent can pass
// the outfile as extra arg, etc.
func reexecCommand(t *testing.T, name string, args ...string) *exec.Cmd {
t.Helper()
exe, err := os.Executable()
if err != nil {
t.Fatalf("os.Executable(): %v", err)
}
argv0 := argv0Token(t, name)
pattern := "^" + regexp.QuoteMeta(t.Name()) + "$"
cmd := exec.Command(exe)
cmd.Path = exe
cmd.Args = append([]string{argv0, "-test.run=" + pattern}, args...)
return cmd
}
================================================
FILE: appveyor.yml
================================================
# Minimal stub to satisfy AppVeyor CI
version: 1.0.{build}
platform: x64
shallow_clone: true
branches:
only:
- master
- main
build_script:
- echo "No-op build to satisfy AppVeyor CI"
================================================
FILE: buffer_pool.go
================================================
package logrus
import (
"bytes"
"sync"
)
var bufferPool BufferPool = &defaultPool{
pool: &sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
},
}
type BufferPool interface {
Put(*bytes.Buffer)
Get() *bytes.Buffer
}
type defaultPool struct {
pool *sync.Pool
}
func (p *defaultPool) Put(buf *bytes.Buffer) {
p.pool.Put(buf)
}
func (p *defaultPool) Get() *bytes.Buffer {
return p.pool.Get().(*bytes.Buffer)
}
// SetBufferPool allows to replace the default logrus buffer pool
// to better meets the specific needs of an application.
func SetBufferPool(bp BufferPool) {
bufferPool = bp
}
================================================
FILE: doc.go
================================================
/*
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
The simplest way to use Logrus is simply the package-level exported logger:
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
}).Info("A walrus appears")
}
Output:
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
For a full guide visit https://github.com/sirupsen/logrus
*/
package logrus
================================================
FILE: entry.go
================================================
package logrus
import (
"bytes"
"context"
"fmt"
"maps"
"os"
"reflect"
"runtime"
"strings"
"sync"
"time"
)
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].
var ErrorKey = "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.
type Entry struct {
// 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 caller
// reporting is enabled.
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 will result in a
// panic when a logging method (e.g., Info, Error, etc.) is called.
func NewEntry(logger *Logger) *Entry {
return &Entry{
Logger: 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.
//
// The Data map is cloned so that changes to fields on the returned
// entry do not mutate the original. The Logger and other metadata
// are copied by value.
func (entry *Entry) Dup() *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: entry.Time,
Context: entry.Context,
err: entry.err,
}
}
// Bytes returns the bytes representation of this entry from the formatter.
func (entry *Entry) Bytes() ([]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
entry.Logger.mu.Lock()
formatter := entry.Logger.Formatter
entry.Logger.mu.Unlock()
return formatter.Format(entry)
}
// String returns the string representation from the reader and ultimately the
// formatter.
func (entry *Entry) String() (string, error) {
serialized, err := entry.Bytes()
if err != nil {
return "", err
}
str := string(serialized)
return str, nil
}
// WithError adds an error as single field (using the key defined in [ErrorKey])
// to the Entry.
func (entry *Entry) WithError(err error) *Entry {
// Avoid reflection work in WithFields; we know the type is an error;
// copy the entry data and set the ErrorKey directly.
data := make(Fields, len(entry.Data)+1)
maps.Copy(data, entry.Data)
data[ErrorKey] = err
return &Entry{
Logger: entry.Logger,
Data: data,
Time: entry.Time,
Context: entry.Context,
err: entry.err,
}
}
// WithContext adds a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: entry.Time,
Context: ctx,
err: entry.err,
}
}
// WithField adds a single field to the Entry.
func (entry *Entry) WithField(key string, value any) *Entry {
return entry.WithFields(Fields{key: value})
}
// WithFields adds a map of fields to the Entry.
func (entry *Entry) WithFields(fields Fields) *Entry {
data := make(Fields, len(entry.Data)+len(fields))
maps.Copy(data, entry.Data)
fieldErr := entry.err
for k, v := range fields {
isErrField := false
if t := reflect.TypeOf(v); t != nil {
switch {
case t.Kind() == reflect.Func, t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Func:
isErrField = true
}
}
if isErrField {
tmp := fmt.Sprintf("can not add field %q", k)
if fieldErr != "" {
fieldErr += ", " + tmp
} else {
fieldErr = tmp
}
} else {
data[k] = v
}
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
}
// WithTime overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry {
return &Entry{
Logger: entry.Logger,
Data: maps.Clone(entry.Data),
Time: t,
Context: entry.Context,
err: entry.err,
}
}
// getPackageName reduces a fully qualified function name to the package name
// There really ought to be a better way...
func getPackageName(f string) string {
for {
lastPeriod := strings.LastIndex(f, ".")
lastSlash := strings.LastIndex(f, "/")
if lastPeriod > lastSlash {
f = f[:lastPeriod]
} else {
break
}
}
return f
}
// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
// dynamic get the package name and the minimum caller depth
for i := range maximumCallerDepth {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "getCaller") {
logrusPackage = getPackageName(funcName)
break
}
}
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
// If the caller isn't part of this package, we're done
if pkg != logrusPackage {
return &f
}
}
// if we got here, we failed to find the caller's context
return nil
}
// HasCaller reports whether this Entry contains caller information.
//
// Caller is attached at log time if [Logger.ReportCaller] was enabled.
// In most cases, it is preferable to check whether [Entry.Caller] is nil
// directly.
func (entry Entry) HasCaller() bool {
return entry.Caller != nil
}
func (entry *Entry) log(level Level, msg string) {
newEntry := entry.Dup()
logger := newEntry.Logger
if newEntry.Time.IsZero() {
newEntry.Time = time.Now()
}
newEntry.Level = level
newEntry.Message = msg
logger.mu.Lock()
reportCaller := logger.ReportCaller
bufPool := newEntry.getBufferPool()
logger.mu.Unlock()
if reportCaller {
newEntry.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.
hooks := logger.hooksForLevel(level)
newEntry.fireHooks(hooks)
buffer := bufPool.Get()
defer func() {
newEntry.Buffer = nil
buffer.Reset()
bufPool.Put(buffer)
}()
buffer.Reset()
newEntry.Buffer = buffer
newEntry.write()
newEntry.Buffer = nil
// To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here.
if level <= PanicLevel {
panic(newEntry)
}
}
func (entry *Entry) getBufferPool() (pool BufferPool) {
if entry.Logger.BufferPool != nil {
return entry.Logger.BufferPool
}
return bufferPool
}
func (entry *Entry) fireHooks(hooks []Hook) {
for _, hook := range hooks {
if err := hook.Fire(entry); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to fire hook:", err)
return
}
}
}
func (entry *Entry) write() {
// 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.
entry.Logger.mu.Lock()
formatter := entry.Logger.Formatter
entry.Logger.mu.Unlock()
serialized, err := formatter.Format(entry)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to format entry:", err)
return
}
// Re-acquire the lock to serialize writes to the underlying io.Writer.
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
if _, err := entry.Logger.Out.Write(serialized); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to write to log:", err)
}
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Entry.Panic or Entry.Fatal should be used instead.
func (entry *Entry) Log(level Level, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}
func (entry *Entry) Trace(args ...any) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...any) {
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...any) {
entry.Info(args...)
}
func (entry *Entry) Info(args ...any) {
entry.Log(InfoLevel, args...)
}
func (entry *Entry) Warn(args ...any) {
entry.Log(WarnLevel, args...)
}
func (entry *Entry) Warning(args ...any) {
entry.Warn(args...)
}
func (entry *Entry) Error(args ...any) {
entry.Log(ErrorLevel, args...)
}
func (entry *Entry) Fatal(args ...any) {
entry.Log(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panic(args ...any) {
entry.Log(PanicLevel, args...)
}
// Entry Printf family functions
func (entry *Entry) Logf(level Level, format string, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Tracef(format string, args ...any) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...any) {
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...any) {
entry.Logf(InfoLevel, format, args...)
}
func (entry *Entry) Printf(format string, args ...any) {
entry.Infof(format, args...)
}
func (entry *Entry) Warnf(format string, args ...any) {
entry.Logf(WarnLevel, format, args...)
}
func (entry *Entry) Warningf(format string, args ...any) {
entry.Warnf(format, args...)
}
func (entry *Entry) Errorf(format string, args ...any) {
entry.Logf(ErrorLevel, format, args...)
}
func (entry *Entry) Fatalf(format string, args ...any) {
entry.Logf(FatalLevel, format, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...any) {
entry.Logf(PanicLevel, format, args...)
}
// Entry Println family functions
func (entry *Entry) Logln(level Level, args ...any) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, entry.sprintlnn(args...))
}
}
func (entry *Entry) Traceln(args ...any) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...any) {
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...any) {
entry.Logln(InfoLevel, args...)
}
func (entry *Entry) Println(args ...any) {
entry.Infoln(args...)
}
func (entry *Entry) Warnln(args ...any) {
entry.Logln(WarnLevel, args...)
}
func (entry *Entry) Warningln(args ...any) {
entry.Warnln(args...)
}
func (entry *Entry) Errorln(args ...any) {
entry.Logln(ErrorLevel, args...)
}
func (entry *Entry) Fatalln(args ...any) {
entry.Logln(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicln(args ...any) {
entry.Logln(PanicLevel, args...)
}
// sprintlnn => Sprint no newline. This is to get the behavior of how
// fmt.Sprintln where spaces are always added between operands, regardless of
// their type. Instead of vendoring the Sprintln implementation to spare a
// string allocation, we do the simplest thing.
func (entry *Entry) sprintlnn(args ...any) string {
msg := fmt.Sprintln(args...)
return msg[:len(msg)-1]
}
================================================
FILE: entry_bench_test.go
================================================
package logrus_test
import (
"errors"
"io"
"testing"
"github.com/sirupsen/logrus"
)
func BenchmarkEntry_WithError(b *testing.B) {
base := &logrus.Entry{Data: logrus.Fields{"a": 1}}
errBoom := errors.New("boom")
b.ReportAllocs()
b.ResetTimer()
for range b.N {
_ = base.WithError(errBoom)
}
}
func BenchmarkEntry_WithField_Chain(b *testing.B) {
base := &logrus.Entry{Data: logrus.Fields{"a": 1}}
errBoom := errors.New("boom")
b.ReportAllocs()
b.ResetTimer()
for range b.N {
e := base
e = e.WithField("k0", 0)
e = e.WithField("k1", 1)
e = e.WithField("k2", 2)
e = e.WithField("k3", 3)
e = e.WithError(errBoom)
_ = e
}
}
func BenchmarkEntry_WithFields(b *testing.B) {
fn := func() {}
fnPtr := &fn
tests := []struct {
name string
base logrus.Fields
fields logrus.Fields
}{
{
name: "valid_fields_only",
base: logrus.Fields{"a": 1, "b": "two"},
fields: logrus.Fields{"c": 3, "d": "four"},
},
{
name: "contains_func",
base: logrus.Fields{"a": 1},
fields: logrus.Fields{"bad": fn},
},
{
name: "contains_func_ptr",
base: logrus.Fields{"a": 1},
fields: logrus.Fields{"bad": fnPtr},
},
{
name: "mixed_valid_invalid",
base: logrus.Fields{"a": 1, "b": 2},
fields: logrus.Fields{"c": 3, "bad": fn, "d": 4},
},
{
name: "larger_map",
base: logrus.Fields{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10},
fields: logrus.Fields{"k": 11, "l": 12, "m": 13, "n": 14, "o": 15},
},
}
for _, tc := range tests {
b.Run(tc.name, func(b *testing.B) {
b.ReportAllocs()
e := &logrus.Entry{Data: tc.base}
b.ResetTimer()
for range b.N {
_ = e.WithFields(tc.fields)
}
})
}
}
func benchmarkEntryInfo(b *testing.B, reportCaller bool) {
// JSONFormatter is used intentionally to measure realistic end-to-end
// ReportCaller overhead (Entry.log + caller field formatting),
// not getCaller() in isolation.
logger := logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{})
logger.SetReportCaller(reportCaller)
logger.SetLevel(logrus.InfoLevel) // ensure Info is enabled
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
// getCaller has a package-level sync.Once; exclude initialization from the benchmark.
entry.Info("warmup")
b.ReportAllocs()
b.ResetTimer()
for range b.N {
entry.Info("test message")
}
}
func BenchmarkEntry_ReportCaller_NoCaller(b *testing.B) { benchmarkEntryInfo(b, false) }
func BenchmarkEntry_ReportCaller_WithCaller(b *testing.B) { benchmarkEntryInfo(b, true) }
//go:noinline
func caller4(entry *logrus.Entry) { caller3(entry) }
//go:noinline
func caller3(entry *logrus.Entry) { caller2(entry) }
//go:noinline
func caller2(entry *logrus.Entry) { caller1(entry) }
//go:noinline
func caller1(entry *logrus.Entry) { entry.Info("test message") }
// benchmarkEntryReportCallerDepth4 simulates a wrapper call site.
// It does not increase getCaller() scan depth (which stops at the first
// non-logrus frame), but ensures ReportCaller overhead is stable with
// wrapper layers.
func benchmarkEntryReportCallerDepth4(b *testing.B, reportCaller bool) {
// JSONFormatter is used intentionally to measure realistic end-to-end
// ReportCaller overhead (Entry.log + caller field formatting),
// not getCaller() in isolation.
logger := logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{})
logger.SetReportCaller(reportCaller)
logger.SetLevel(logrus.InfoLevel)
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
// getCaller has a package-level sync.Once; exclude initialization from the benchmark.
entry.Info("warmup")
b.ReportAllocs()
b.ResetTimer()
for range b.N {
caller4(entry)
}
}
func BenchmarkEntry_ReportCaller_NoCaller_Depth4(b *testing.B) {
benchmarkEntryReportCallerDepth4(b, false)
}
func BenchmarkEntry_ReportCaller_WithCaller_Depth4(b *testing.B) {
benchmarkEntryReportCallerDepth4(b, true)
}
================================================
FILE: entry_test.go
================================================
package logrus_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"sync"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type contextKeyType string
func TestEntryWithError(t *testing.T) {
expErr := fmt.Errorf("kaboom at layer %d", 4711)
assert.Equal(t, expErr, logrus.WithError(expErr).Data["error"])
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
assert.Equal(t, expErr, entry.WithError(expErr).Data["error"])
tmpKey := logrus.ErrorKey
logrus.ErrorKey = "err" //nolint:reassign // ignore "reassigning variable ErrorKey in other package logrus (reassign)"
t.Cleanup(func() {
logrus.ErrorKey = tmpKey //nolint:reassign // ignore "reassigning variable ErrorKey in other package logrus (reassign)"
})
assert.Equal(t, expErr, entry.WithError(expErr).Data["err"])
}
func TestEntryWithContext(t *testing.T) {
assert := assert.New(t)
var contextKey contextKeyType = "foo"
ctx := context.WithValue(context.Background(), contextKey, "bar")
assert.Equal(ctx, logrus.WithContext(ctx).Context)
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
assert.Equal(ctx, entry.WithContext(ctx).Context)
}
func TestEntryWithContextCopiesData(t *testing.T) {
assert := assert.New(t)
// Initialize a parent Entry object with a key/value set in its Data map
logger := logrus.New()
logger.SetOutput(io.Discard)
parentEntry := logrus.NewEntry(logger).WithField("parentKey", "parentValue")
// Create two children Entry objects from the parent in different contexts
var contextKey1 contextKeyType = "foo"
ctx1 := context.WithValue(context.Background(), contextKey1, "bar")
childEntry1 := parentEntry.WithContext(ctx1)
assert.Equal(ctx1, childEntry1.Context)
var contextKey2 contextKeyType = "bar"
ctx2 := context.WithValue(context.Background(), contextKey2, "baz")
childEntry2 := parentEntry.WithContext(ctx2)
assert.Equal(ctx2, childEntry2.Context)
assert.NotEqual(ctx1, ctx2)
// Ensure that data set in the parent Entry are preserved to both children
assert.Equal("parentValue", childEntry1.Data["parentKey"])
assert.Equal("parentValue", childEntry2.Data["parentKey"])
// Modify data stored in the child entry
childEntry1.Data["childKey"] = "childValue"
// Verify that data is successfully stored in the child it was set on
val, exists := childEntry1.Data["childKey"]
assert.True(exists)
assert.Equal("childValue", val)
// Verify that the data change to child 1 has not affected its sibling
val, exists = childEntry2.Data["childKey"]
assert.False(exists)
assert.Empty(val)
// Verify that the data change to child 1 has not affected its parent
val, exists = parentEntry.Data["childKey"]
assert.False(exists)
assert.Empty(val)
}
func TestEntryWithTimeCopiesData(t *testing.T) {
assert := assert.New(t)
// Initialize a parent Entry object with a key/value set in its Data map
logger := logrus.New()
logger.SetOutput(io.Discard)
parentEntry := logrus.NewEntry(logger).WithField("parentKey", "parentValue")
// Create two children Entry objects from the parent with two different times
childEntry1 := parentEntry.WithTime(time.Now().AddDate(0, 0, 1))
childEntry2 := parentEntry.WithTime(time.Now().AddDate(0, 0, 2))
// Ensure that data set in the parent Entry are preserved to both children
assert.Equal("parentValue", childEntry1.Data["parentKey"])
assert.Equal("parentValue", childEntry2.Data["parentKey"])
// Modify data stored in the child entry
childEntry1.Data["childKey"] = "childValue"
// Verify that data is successfully stored in the child it was set on
val, exists := childEntry1.Data["childKey"]
assert.True(exists)
assert.Equal("childValue", val)
// Verify that the data change to child 1 has not affected its sibling
val, exists = childEntry2.Data["childKey"]
assert.False(exists)
assert.Empty(val)
// Verify that the data change to child 1 has not affected its parent
val, exists = parentEntry.Data["childKey"]
assert.False(exists)
assert.Empty(val)
}
func TestEntryPanicln(t *testing.T) {
errBoom := fmt.Errorf("boom time")
defer func() {
p := recover()
assert.NotNil(t, p)
switch pVal := p.(type) {
case *logrus.Entry:
assert.Equal(t, "kaboom", pVal.Message)
assert.Equal(t, errBoom, pVal.Data["err"])
default:
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
}
}()
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
entry.WithField("err", errBoom).Panicln("kaboom")
}
func TestEntryPanicf(t *testing.T) {
errBoom := fmt.Errorf("boom again")
defer func() {
p := recover()
assert.NotNil(t, p)
switch pVal := p.(type) {
case *logrus.Entry:
assert.Equal(t, "kaboom true", pVal.Message)
assert.Equal(t, errBoom, pVal.Data["err"])
default:
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
}
}()
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
entry.WithField("err", errBoom).Panicf("kaboom %v", true)
}
func TestEntryPanic(t *testing.T) {
errBoom := fmt.Errorf("boom again")
defer func() {
p := recover()
assert.NotNil(t, p)
switch pVal := p.(type) {
case *logrus.Entry:
assert.Equal(t, "kaboom", pVal.Message)
assert.Equal(t, errBoom, pVal.Data["err"])
default:
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
}
}()
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
entry.WithField("err", errBoom).Panic("kaboom")
}
const (
badMessage = "this is going to panic"
panicMessage = "this is broken"
)
type panickyHook struct{}
func (p *panickyHook) Levels() []logrus.Level {
return []logrus.Level{logrus.InfoLevel}
}
func (p *panickyHook) Fire(entry *logrus.Entry) error {
if entry.Message == badMessage {
panic(panicMessage)
}
return nil
}
func TestEntryHooksPanic(t *testing.T) {
logger := logrus.New()
logger.SetOutput(io.Discard)
logger.SetLevel(logrus.InfoLevel)
logger.AddHook(&panickyHook{})
defer func() {
p := recover()
assert.NotNil(t, p)
assert.Equal(t, panicMessage, p)
entry := logrus.NewEntry(logger)
entry.Info("another message")
}()
entry := logrus.NewEntry(logger)
entry.Info(badMessage)
}
func TestEntryWithIncorrectField(t *testing.T) {
logger := logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{})
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
fn := func() {}
eWithFunc := entry.WithFields(logrus.Fields{"func": fn})
eWithFuncPtr := entry.WithFields(logrus.Fields{"funcPtr": &fn})
assert.Equal(t, `can not add field "func"`, getErr(t, eWithFunc))
assert.Equal(t, `can not add field "funcPtr"`, getErr(t, eWithFuncPtr))
eWithFunc = eWithFunc.WithField("not_a_func", "it is a string")
eWithFuncPtr = eWithFuncPtr.WithField("not_a_func", "it is a string")
assert.Equal(t, `can not add field "func"`, getErr(t, eWithFunc))
assert.Equal(t, `can not add field "funcPtr"`, getErr(t, eWithFuncPtr))
eWithFunc = eWithFunc.WithTime(time.Now())
eWithFuncPtr = eWithFuncPtr.WithTime(time.Now())
assert.Equal(t, `can not add field "func"`, getErr(t, eWithFunc))
assert.Equal(t, `can not add field "funcPtr"`, getErr(t, eWithFuncPtr))
}
func getErr(t *testing.T, e *logrus.Entry) string {
t.Helper()
out, err := e.String()
require.NoError(t, err)
var m map[string]any
require.NoError(t, json.Unmarshal([]byte(out), &m))
got, _ := m[logrus.FieldKeyLogrusError].(string)
return got
}
func TestEntryLogfLevel(t *testing.T) {
var buffer bytes.Buffer
logger := logrus.New()
logger.SetOutput(&buffer)
logger.SetLevel(logrus.InfoLevel)
entry := logrus.NewEntry(logger)
entry.Logf(logrus.DebugLevel, "%s", "debug")
assert.NotContains(t, buffer.String(), "debug")
entry.Logf(logrus.WarnLevel, "%s", "warn")
assert.Contains(t, buffer.String(), "warn")
}
func TestEntryLoggerMutationRace(t *testing.T) {
tests := []struct {
doc string
mutate func(*logrus.Logger)
}{
{doc: "AddHook", mutate: func(l *logrus.Logger) { l.AddHook(noopHook{}) }},
{doc: "SetBufferPool", mutate: func(l *logrus.Logger) { l.SetBufferPool(nopBufferPool{}) }},
{doc: "SetFormatter", mutate: func(l *logrus.Logger) { l.SetFormatter(&logrus.TextFormatter{}) }},
{doc: "SetLevel", mutate: func(l *logrus.Logger) { l.SetLevel(logrus.InfoLevel) }},
{doc: "SetOutput", mutate: func(l *logrus.Logger) { l.SetOutput(io.Discard) }},
{doc: "SetReportCaller", mutate: func(l *logrus.Logger) { l.SetReportCaller(true) }},
{doc: "ReplaceHooks_withHookPresent", mutate: func(l *logrus.Logger) {
// Replace with a fresh map each time to maximize mutation.
h := make(logrus.LevelHooks)
for _, lvl := range logrus.AllLevels {
h[lvl] = []logrus.Hook{noopHook{}}
}
l.ReplaceHooks(h)
}},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
runEntryLoggerRace(t, tc.mutate)
})
}
}
type noopHook struct{}
func (noopHook) Levels() []logrus.Level { return logrus.AllLevels }
func (noopHook) Fire(*logrus.Entry) error { return nil }
type nopBufferPool struct{}
func (nopBufferPool) Get() *bytes.Buffer { return new(bytes.Buffer) }
func (nopBufferPool) Put(*bytes.Buffer) {}
func runEntryLoggerRace(t *testing.T, mutate func(logger *logrus.Logger)) {
t.Helper()
logger := logrus.New()
logger.SetOutput(io.Discard)
entry := logrus.NewEntry(logger)
const n = 100
var wg sync.WaitGroup
wg.Add(4)
go func() {
defer wg.Done()
for range n {
_, _ = entry.Bytes()
}
}()
go func() {
defer wg.Done()
for range n {
entry.Info("should not race")
}
}()
go func() {
defer wg.Done()
for range n {
mutate(logger)
}
}()
go func() {
defer wg.Done()
for range n {
entry.Info("should not race")
}
}()
wg.Wait()
}
// reentrantValue is a type whose MarshalJSON method triggers another log call,
// which would deadlock if the logger mutex is held during formatting.
type reentrantValue struct {
logger *logrus.Logger
}
func (r reentrantValue) MarshalJSON() ([]byte, error) {
r.logger.Info("reentrant log from MarshalJSON")
return []byte(`"reentrant"`), nil
}
// TestEntryReentrantLoggingDeadlock verifies that logging from within a field's
// MarshalJSON (or similar serialization callback) does not deadlock.
// This is a regression test for https://github.com/sirupsen/logrus/issues/1448.
func TestEntryReentrantLoggingDeadlock(t *testing.T) {
var buf bytes.Buffer
logger := logrus.New()
logger.SetOutput(&buf)
logger.SetFormatter(&logrus.JSONFormatter{})
done := make(chan struct{})
go func() {
defer close(done)
logger.WithFields(logrus.Fields{
"key": reentrantValue{logger: logger},
}).Info("outer log message")
}()
select {
case <-done:
// Success: the log call completed without deadlocking.
output := buf.String()
assert.Contains(t, output, "outer log message")
assert.Contains(t, output, "reentrant log from MarshalJSON")
assert.Contains(t, output, `"key":"reentrant"`)
case <-time.After(5 * time.Second):
t.Fatal("deadlock detected: reentrant logging from MarshalJSON blocked for 5 seconds")
}
}
================================================
FILE: example_basic_test.go
================================================
package logrus_test
import (
"os"
"github.com/sirupsen/logrus"
)
func Example_basic() {
log := logrus.New()
log.Formatter = new(logrus.JSONFormatter)
log.Formatter = new(logrus.TextFormatter) // default
log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors
log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
log.Level = logrus.TraceLevel
log.Out = os.Stdout
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
// if err == nil {
// log.Out = file
// } else {
// log.Info("Failed to log to file, using default stderr")
// }
defer func() {
err := recover()
if err != nil {
entry := err.(*logrus.Entry)
log.WithFields(logrus.Fields{
"omg": true,
"err_animal": entry.Data["animal"],
"err_size": entry.Data["size"],
"err_level": entry.Level,
"err_message": entry.Message,
"number": 100,
}).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code
}
}()
log.WithFields(logrus.Fields{
"animal": "walrus",
"number": 0,
}).Trace("Went to the beach")
log.WithFields(logrus.Fields{
"animal": "walrus",
"number": 8,
}).Debug("Started observing beach")
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(logrus.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(logrus.Fields{
"temperature": -4,
}).Debug("Temperature changes")
log.WithFields(logrus.Fields{
"animal": "orca",
"size": 9009,
}).Panic("It's over 9000!")
// Output:
// level=trace msg="Went to the beach" animal=walrus number=0
// level=debug msg="Started observing beach" animal=walrus number=8
// level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
// level=warning msg="The group's number increased tremendously!" number=122 omg=true
// level=debug msg="Temperature changes" temperature=-4
// level=panic msg="It's over 9000!" animal=orca size=9009
// level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
}
================================================
FILE: example_custom_caller_test.go
================================================
package logrus_test
import (
"os"
"path"
"runtime"
"strings"
"github.com/sirupsen/logrus"
)
func ExampleJSONFormatter_CallerPrettyfier() {
l := logrus.New()
l.SetReportCaller(true)
l.Out = os.Stdout
l.Formatter = &logrus.JSONFormatter{
DisableTimestamp: true,
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
s := strings.Split(f.Function, ".")
funcname := s[len(s)-1]
_, filename := path.Split(f.File)
return funcname, filename
},
}
l.Info("example of custom format caller")
// Output:
// {"file":"example_custom_caller_test.go","func":"ExampleJSONFormatter_CallerPrettyfier","level":"info","msg":"example of custom format caller"}
}
================================================
FILE: example_default_field_value_test.go
================================================
package logrus_test
import (
"os"
"github.com/sirupsen/logrus"
)
type DefaultFieldHook struct {
GetValue func() string
}
func (h *DefaultFieldHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *DefaultFieldHook) Fire(e *logrus.Entry) error {
e.Data["aDefaultField"] = h.GetValue()
return nil
}
func ExampleDefaultFieldHook() {
l := logrus.New()
l.Out = os.Stdout
l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}
l.AddHook(&DefaultFieldHook{GetValue: func() string { return "with its default value" }})
l.Info("first log")
// Output:
// level=info msg="first log" aDefaultField="with its default value"
}
================================================
FILE: example_function_test.go
================================================
package logrus_test
import (
"io"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func TestLogger_LogFn(t *testing.T) {
log := logrus.New()
log.SetOutput(io.Discard)
log.SetFormatter(&logrus.JSONFormatter{})
log.SetLevel(logrus.WarnLevel)
notCalled := 0
log.InfoFn(func() []any {
notCalled++
return []any{
"Hello",
}
})
assert.Equal(t, 0, notCalled)
called := 0
log.ErrorFn(func() []any {
called++
return []any{
"Oopsi",
}
})
assert.Equal(t, 1, called)
}
================================================
FILE: example_global_hook_test.go
================================================
package logrus_test
import (
"os"
"github.com/sirupsen/logrus"
)
var mystring string
type GlobalHook struct{}
func (h *GlobalHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *GlobalHook) Fire(e *logrus.Entry) error {
e.Data["mystring"] = mystring
return nil
}
func ExampleGlobalHook() {
l := logrus.New()
l.Out = os.Stdout
l.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}
l.AddHook(&GlobalHook{})
mystring = "first value"
l.Info("first log")
mystring = "another value"
l.Info("second log")
// Output:
// level=info msg="first log" mystring="first value"
// level=info msg="second log" mystring="another value"
}
================================================
FILE: example_hook_test.go
================================================
//go:build !windows
package logrus_test
import (
"log/syslog"
"os"
"github.com/sirupsen/logrus"
slhooks "github.com/sirupsen/logrus/hooks/syslog"
)
// An example on how to use a hook
func Example_hook() {
log := logrus.New()
log.Formatter = new(logrus.TextFormatter) // default
log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors
log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
if sl, err := slhooks.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, ""); err == nil {
log.Hooks.Add(sl)
}
log.Out = os.Stdout
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(logrus.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(logrus.Fields{
"omg": true,
"number": 100,
}).Error("The ice breaks!")
// Output:
// level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
// level=warning msg="The group's number increased tremendously!" number=122 omg=true
// level=error msg="The ice breaks!" number=100 omg=true
}
================================================
FILE: exported.go
================================================
package logrus
import (
"context"
"io"
"time"
)
// std is the package-level standard logger, similar to the default logger
// in the stdlib [log] package.
var std = New()
func StandardLogger() *Logger {
return std
}
// SetOutput sets the standard logger output.
func SetOutput(out io.Writer) {
std.SetOutput(out)
}
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter Formatter) {
std.SetFormatter(formatter)
}
// SetReportCaller sets whether the standard logger will include the calling
// method as a field.
func SetReportCaller(include bool) {
std.SetReportCaller(include)
}
// SetLevel sets the standard logger level.
func SetLevel(level Level) {
std.SetLevel(level)
}
// GetLevel returns the standard logger level.
func GetLevel() Level {
return std.GetLevel()
}
// IsLevelEnabled checks if logging for the given level is enabled for the standard logger.
func IsLevelEnabled(level Level) bool {
return std.IsLevelEnabled(level)
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook Hook) {
std.AddHook(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithError(err error) *Entry {
return std.WithField(ErrorKey, err)
}
// WithContext creates an entry from the standard logger and adds a context to it.
func WithContext(ctx context.Context) *Entry {
return std.WithContext(ctx)
}
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithField(key string, value any) *Entry {
return std.WithField(key, value)
}
// WithFields creates an entry from the standard logger and adds multiple
// fields to it. This is simply a helper for `WithField`, invoking it
// once for each field.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithFields(fields Fields) *Entry {
return std.WithFields(fields)
}
// WithTime creates an entry from the standard logger and overrides the time of
// logs generated with it.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithTime(t time.Time) *Entry {
return std.WithTime(t)
}
// Trace logs a message at level Trace on the standard logger.
func Trace(args ...any) {
std.Trace(args...)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...any) {
std.Debug(args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...any) {
std.Print(args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...any) {
std.Info(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...any) {
std.Warn(args...)
}
// Warning logs a message at level Warn on the standard logger.
func Warning(args ...any) {
std.Warning(args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...any) {
std.Error(args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...any) {
std.Panic(args...)
}
// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatal(args ...any) {
std.Fatal(args...)
}
// TraceFn logs a message from a func at level Trace on the standard logger.
func TraceFn(fn LogFunction) {
std.TraceFn(fn)
}
// DebugFn logs a message from a func at level Debug on the standard logger.
func DebugFn(fn LogFunction) {
std.DebugFn(fn)
}
// PrintFn logs a message from a func at level Info on the standard logger.
func PrintFn(fn LogFunction) {
std.PrintFn(fn)
}
// InfoFn logs a message from a func at level Info on the standard logger.
func InfoFn(fn LogFunction) {
std.InfoFn(fn)
}
// WarnFn logs a message from a func at level Warn on the standard logger.
func WarnFn(fn LogFunction) {
std.WarnFn(fn)
}
// WarningFn logs a message from a func at level Warn on the standard logger.
func WarningFn(fn LogFunction) {
std.WarningFn(fn)
}
// ErrorFn logs a message from a func at level Error on the standard logger.
func ErrorFn(fn LogFunction) {
std.ErrorFn(fn)
}
// PanicFn logs a message from a func at level Panic on the standard logger.
func PanicFn(fn LogFunction) {
std.PanicFn(fn)
}
// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.
func FatalFn(fn LogFunction) {
std.FatalFn(fn)
}
// Tracef logs a message at level Trace on the standard logger.
func Tracef(format string, args ...any) {
std.Tracef(format, args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...any) {
std.Debugf(format, args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...any) {
std.Printf(format, args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...any) {
std.Infof(format, args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...any) {
std.Warnf(format, args...)
}
// Warningf logs a message at level Warn on the standard logger.
func Warningf(format string, args ...any) {
std.Warningf(format, args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...any) {
std.Errorf(format, args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...any) {
std.Panicf(format, args...)
}
// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalf(format string, args ...any) {
std.Fatalf(format, args...)
}
// Traceln logs a message at level Trace on the standard logger.
func Traceln(args ...any) {
std.Traceln(args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...any) {
std.Debugln(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...any) {
std.Println(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...any) {
std.Infoln(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...any) {
std.Warnln(args...)
}
// Warningln logs a message at level Warn on the standard logger.
func Warningln(args ...any) {
std.Warningln(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...any) {
std.Errorln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...any) {
std.Panicln(args...)
}
// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalln(args ...any) {
std.Fatalln(args...)
}
================================================
FILE: formatter.go
================================================
package logrus
import "time"
const (
// defaultTimestampFormat is the layout used to format entry timestamps
// when a formatter has not specified a custom TimestampFormat.
// It follows time.RFC3339 and is applied unless timestamps are disabled.
defaultTimestampFormat = time.RFC3339
// defaultFields is the number of commonly included predefined log entry fields
// (msg, level, time). It is used as a capacity hint when constructing
// intermediate collections during formatting (for example, the fixed key list).
//
// It does not include the optional "logrus_error", "func", or "file" fields.
defaultFields = 3
)
// Default key names for the default fields
const (
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
FieldKeyLogrusError = "logrus_error"
FieldKeyFunc = "func"
FieldKeyFile = "file"
)
// The Formatter interface is used to implement a custom Formatter. It takes an
// `Entry`. It exposes all the fields, including the default ones:
//
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
// * `entry.Data["time"]`. The timestamp.
// * `entry.Data["level"]. The level the entry was logged at.
//
// Any additional fields added with `WithField` or `WithFields` are also in
// `entry.Data`. Format is expected to return an array of bytes which are then
// logged to `logger.Out`.
type Formatter interface {
Format(*Entry) ([]byte, error)
}
// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when
// dumping it. If this code wasn't there doing:
//
// logrus.WithField("level", 1).Info("hello")
//
// Would just silently drop the user provided level. Instead with this code
// it'll logged as:
//
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
//
// It's not exported because it's still using Data in an opinionated way. It's to
// avoid code duplication between the two default formatters.
func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) {
timeKey := fieldMap.resolve(FieldKeyTime)
if t, ok := data[timeKey]; ok {
data["fields."+timeKey] = t
delete(data, timeKey)
}
msgKey := fieldMap.resolve(FieldKeyMsg)
if m, ok := data[msgKey]; ok {
data["fields."+msgKey] = m
delete(data, msgKey)
}
levelKey := fieldMap.resolve(FieldKeyLevel)
if l, ok := data[levelKey]; ok {
data["fields."+levelKey] = l
delete(data, levelKey)
}
logrusErrKey := fieldMap.resolve(FieldKeyLogrusError)
if l, ok := data[logrusErrKey]; ok {
data["fields."+logrusErrKey] = l
delete(data, logrusErrKey)
}
// If reportCaller is not set, 'func' will not conflict.
if reportCaller {
funcKey := fieldMap.resolve(FieldKeyFunc)
if l, ok := data[funcKey]; ok {
data["fields."+funcKey] = l
}
fileKey := fieldMap.resolve(FieldKeyFile)
if l, ok := data[fileKey]; ok {
data["fields."+fileKey] = l
}
}
}
================================================
FILE: formatter_bench_test.go
================================================
package logrus_test
import (
"fmt"
"testing"
"time"
"github.com/sirupsen/logrus"
)
type benchStringer string
func (s benchStringer) String() string { return string(s) }
var numericFields = logrus.Fields{
"i": int(42),
"i64": int64(-1234567890),
"u": uint(99),
"u64": uint64(18446744073709551615),
"f32": float32(3.1415927),
"f64": float64(-1.2345e6),
}
var boolFields = logrus.Fields{
"t": true,
"f": false,
"x": true,
"y": false,
"yes": true,
"no": false,
}
var stringerFields = logrus.Fields{
"s1": benchStringer("alpha"),
"s2": benchStringer("beta"),
"s3": benchStringer("gamma-delta"), // includes '-' (still unquoted)
"s4": benchStringer("needs quote"), // includes space -> quoted path
"s5": benchStringer(`needs "quote"`),
"s6": benchStringer(`needs 'quote'`),
}
// smallFields is a small size data set for benchmarking
var smallFields = logrus.Fields{
"foo": "bar",
"baz": "qux",
"one": "two",
"three": "four",
}
// largeFields is a large size data set for benchmarking
var largeFields = logrus.Fields{
"foo": "bar",
"baz": "qux",
"one": "two",
"three": "four",
"five": "six",
"seven": "eight",
"nine": "ten",
"eleven": "twelve",
"thirteen": "fourteen",
"fifteen": "sixteen",
"seventeen": "eighteen",
"nineteen": "twenty",
"a": "b",
"c": "d",
"e": "f",
"g": "h",
"i": "j",
"k": "l",
"m": "n",
"o": "p",
"q": "r",
"s": "t",
"u": "v",
"w": "x",
"y": "z",
"this": "will",
"make": "thirty",
"entries": "yeah",
}
var errorFields = logrus.Fields{
"foo": fmt.Errorf("bar"),
"baz": fmt.Errorf("qux"),
}
func BenchmarkZeroTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{})
}
func BenchmarkOneStringTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{"foo": "bar"})
}
func BenchmarkOneNumericTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{"i": int(42)})
}
func BenchmarkOneBoolTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{"t": true})
}
func BenchmarkNumericTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, numericFields)
}
func BenchmarkBoolTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, boolFields)
}
func BenchmarkStringerTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, stringerFields)
}
func BenchmarkErrorTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, errorFields)
}
func BenchmarkSmallTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, smallFields)
}
func BenchmarkLargeTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{DisableColors: true}, largeFields)
}
func BenchmarkSmallColoredTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{ForceColors: true}, smallFields)
}
func BenchmarkLargeColoredTextFormatter(b *testing.B) {
doBenchmark(b, &logrus.TextFormatter{ForceColors: true}, largeFields)
}
func BenchmarkSmallJSONFormatter(b *testing.B) {
doBenchmark(b, &logrus.JSONFormatter{}, smallFields)
}
func BenchmarkLargeJSONFormatter(b *testing.B) {
doBenchmark(b, &logrus.JSONFormatter{}, largeFields)
}
var sink []byte
func doBenchmark(b *testing.B, formatter logrus.Formatter, fields logrus.Fields) {
logger := logrus.New()
entry := &logrus.Entry{
Time: time.Time{},
Level: logrus.InfoLevel,
Message: "message",
Data: fields,
Logger: logger,
}
// Warm once to determine output size and validate.
d, err := formatter.Format(entry)
if err != nil {
b.Fatal(err)
}
b.SetBytes(int64(len(d)))
b.ReportAllocs()
b.ResetTimer()
for range b.N {
d, err = formatter.Format(entry)
if err != nil {
b.Fatal(err)
}
}
sink = d
}
================================================
FILE: go.mod
================================================
module github.com/sirupsen/logrus
go 1.23
require (
github.com/stretchr/testify v1.10.0
golang.org/x/sys v0.13.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
================================================
FILE: go.sum
================================================
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: hook_test.go
================================================
package logrus_test
import (
"fmt"
"io"
"maps"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
. "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
. "github.com/sirupsen/logrus/internal/testutils"
)
// RecordingFormatter is a test helper that implements Formatter and
// records information about the last formatted Entry.
//
// On every call to Format, it increments Calls and stores a shallow copy
// of entry.Data in EntryData, overwriting any previous value. The formatted
// output is the raw entry.Message as bytes.
type RecordingFormatter struct {
Calls atomic.Int64
EntryData Fields
}
func (f *RecordingFormatter) Format(entry *Entry) ([]byte, error) {
f.Calls.Add(1)
f.EntryData = maps.Clone(entry.Data)
return []byte(entry.Message), nil
}
type TestHook struct {
Fired bool
}
func (hook *TestHook) Fire(entry *Entry) error {
hook.Fired = true
return nil
}
func (hook *TestHook) Levels() []Level {
return []Level{
TraceLevel,
DebugLevel,
InfoLevel,
WarnLevel,
ErrorLevel,
FatalLevel,
PanicLevel,
}
}
func TestHookFires(t *testing.T) {
hook := new(TestHook)
LogAndAssertJSON(t, func(log *Logger) {
log.Hooks.Add(hook)
assert.False(t, hook.Fired)
log.Print("test")
}, func(fields Fields) {
assert.True(t, hook.Fired)
})
}
type ModifyHook struct {
Calls atomic.Int64
}
func (hook *ModifyHook) Fire(entry *Entry) error {
hook.Calls.Add(1)
entry.Data["wow"] = "whale"
return nil
}
func (hook *ModifyHook) Levels() []Level {
return []Level{
TraceLevel,
DebugLevel,
InfoLevel,
WarnLevel,
ErrorLevel,
FatalLevel,
PanicLevel,
}
}
func TestHookCanModifyEntry(t *testing.T) {
hook := new(ModifyHook)
LogAndAssertJSON(t, func(log *Logger) {
log.Hooks.Add(hook)
log.WithField("wow", "elephant").Print("test")
}, func(fields Fields) {
assert.Equal(t, "whale", fields["wow"])
})
}
func TestCanFireMultipleHooks(t *testing.T) {
hook1 := new(ModifyHook)
hook2 := new(TestHook)
LogAndAssertJSON(t, func(log *Logger) {
log.Hooks.Add(hook1)
log.Hooks.Add(hook2)
log.WithField("wow", "elephant").Print("test")
}, func(fields Fields) {
assert.Equal(t, "whale", fields["wow"])
assert.True(t, hook2.Fired)
})
}
type SingleLevelModifyHook struct {
ModifyHook
}
func (h *SingleLevelModifyHook) Levels() []Level {
return []Level{InfoLevel}
}
// TestHookEntryIsPristine tests that each log gets a pristine copy of Entry,
// and changes from modifying hooks are not persisted.
//
// Regression test for https://github.com/sirupsen/logrus/issues/795
func TestHookEntryIsPristine(t *testing.T) {
formatter := &RecordingFormatter{}
hook := &SingleLevelModifyHook{}
l := New()
l.SetOutput(io.Discard)
l.SetFormatter(formatter)
l.AddHook(hook)
// Initial message should have a pristine copy of Entry.
l.Error("first")
assert.Equal(t, int64(0), hook.Calls.Load())
assert.Equal(t, int64(1), formatter.Calls.Load())
require.Empty(t, formatter.EntryData)
// Info message modifies data through SingleLevelModifyHook
l.Info("second")
assert.Equal(t, int64(1), hook.Calls.Load())
assert.Equal(t, int64(2), formatter.Calls.Load())
require.Equal(t, Fields{"wow": "whale"}, formatter.EntryData)
// Should have a pristine copy of Entry.
l.Error("third")
assert.Equal(t, int64(1), hook.Calls.Load())
assert.Equal(t, int64(3), formatter.Calls.Load())
require.Empty(t, formatter.EntryData)
}
type ErrorHook struct {
Fired bool
}
func (hook *ErrorHook) Fire(entry *Entry) error {
hook.Fired = true
return nil
}
func (hook *ErrorHook) Levels() []Level {
return []Level{
ErrorLevel,
}
}
func TestErrorHookShouldntFireOnInfo(t *testing.T) {
hook := new(ErrorHook)
LogAndAssertJSON(t, func(log *Logger) {
log.Hooks.Add(hook)
log.Info("test")
}, func(fields Fields) {
assert.False(t, hook.Fired)
})
}
func TestErrorHookShouldFireOnError(t *testing.T) {
hook := new(ErrorHook)
LogAndAssertJSON(t, func(log *Logger) {
log.Hooks.Add(hook)
log.Error("test")
}, func(fields Fields) {
assert.True(t, hook.Fired)
})
}
func TestAddHookRace(t *testing.T) {
var wg sync.WaitGroup
wg.Add(2)
hook := new(ErrorHook)
LogAndAssertJSON(t, func(log *Logger) {
go func() {
defer wg.Done()
log.AddHook(hook)
}()
go func() {
defer wg.Done()
log.Error("test")
}()
wg.Wait()
}, func(fields Fields) {
// the line may have been logged
// before the hook was added, so we can't
// actually assert on the hook
})
}
func TestAddHookRace2(t *testing.T) {
// Test modifies the standard-logger; restore it afterward.
stdLogger := StandardLogger()
oldOut := stdLogger.Out
oldHooks := stdLogger.ReplaceHooks(make(LevelHooks))
t.Cleanup(func() {
stdLogger.SetOutput(oldOut)
stdLogger.ReplaceHooks(oldHooks)
})
stdLogger.SetOutput(io.Discard)
for i := range 3 {
testname := fmt.Sprintf("Test %d", i)
t.Run(testname, func(t *testing.T) {
t.Parallel()
_ = test.NewGlobal()
Info(testname)
})
}
}
type HookCallFunc struct {
F func()
}
func (h *HookCallFunc) Levels() []Level {
return AllLevels
}
func (h *HookCallFunc) Fire(e *Entry) error {
h.F()
return nil
}
func TestHookFireOrder(t *testing.T) {
checkers := []string{}
h := LevelHooks{}
h.Add(&HookCallFunc{F: func() { checkers = append(checkers, "first hook") }})
h.Add(&HookCallFunc{F: func() { checkers = append(checkers, "second hook") }})
h.Add(&HookCallFunc{F: func() { checkers = append(checkers, "third hook") }})
if err := h.Fire(InfoLevel, &Entry{}); err != nil {
t.Error("unexpected error:", err)
}
require.Equal(t, []string{"first hook", "second hook", "third hook"}, checkers)
}
================================================
FILE: hooks/slog/slog.go
================================================
package slog
import (
"context"
"log/slog"
"github.com/sirupsen/logrus"
)
// LevelMapper maps a [logrus.Level] to a [slog.Leveler].
//
// To change the default level mapping, for instance to allow mapping to custom
// or dynamic slog levels in your application, set [SlogHook.LevelMapper]
// to your own implementation of this function.
type LevelMapper func(logrus.Level) slog.Leveler
// SlogHook sends logs to slog.
type SlogHook struct {
logger *slog.Logger
LevelMapper LevelMapper
}
var _ logrus.Hook = (*SlogHook)(nil)
// NewSlogHook creates a hook that sends logs to an existing slog Logger.
// This hook is intended to be used during transition from Logrus to slog,
// or as a shim between different parts of your application or different
// libraries that depend on different loggers.
//
// The provided logger must not be nil. NewSlogHook panics if logger is nil.
//
// Example usage:
//
// logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
// hook := NewSlogHook(logger)
func NewSlogHook(logger *slog.Logger) *SlogHook {
if logger == nil {
panic("cannot create hook from nil logger")
}
return &SlogHook{
logger: logger,
}
}
func (h *SlogHook) toSlogLevel(level logrus.Level) slog.Leveler {
if h.LevelMapper != nil {
return h.LevelMapper(level)
}
switch level {
case logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel:
return slog.LevelError
case logrus.WarnLevel:
return slog.LevelWarn
case logrus.InfoLevel:
return slog.LevelInfo
case logrus.DebugLevel, logrus.TraceLevel:
return slog.LevelDebug
default:
// Treat all unknown levels as errors
return slog.LevelError
}
}
// Levels always returns all levels, since slog allows controlling level
// enabling based on context.
func (h *SlogHook) Levels() []logrus.Level {
return logrus.AllLevels
}
// Fire forwards the provided logrus Entry to the underlying slog.Logger's
// Handler, mapping it to a slog.Record. Time and caller information are
// preserved when available, and Entry.Data is converted to attributes.
// If Entry.Context is nil, context.Background() is used.
func (h *SlogHook) Fire(entry *logrus.Entry) error {
ctx := entry.Context
if ctx == nil {
ctx = context.Background()
}
lvl := h.toSlogLevel(entry.Level).Level()
handler := h.logger.Handler()
if !handler.Enabled(ctx, lvl) {
return nil
}
attrs := make([]slog.Attr, 0, len(entry.Data))
for k, v := range entry.Data {
attrs = append(attrs, slog.Any(k, v))
}
var pc uintptr
if entry.Caller != nil {
pc = entry.Caller.PC
}
r := slog.NewRecord(entry.Time, lvl, entry.Message, pc)
r.AddAttrs(attrs...)
return handler.Handle(ctx, r)
}
================================================
FILE: hooks/slog/slog_test.go
================================================
package slog_test
import (
"bytes"
"context"
"errors"
"io"
"log/slog"
"os"
"regexp"
"strings"
"testing"
"github.com/sirupsen/logrus"
lslog "github.com/sirupsen/logrus/hooks/slog"
)
func TestSlogHook(t *testing.T) {
tests := []struct {
name string
mapper lslog.LevelMapper
fn func(*logrus.Logger)
want []string
}{
{
name: "defaults",
fn: func(log *logrus.Logger) {
log.Info("info")
},
want: []string{
"level=INFO msg=info",
},
},
{
name: "with fields",
fn: func(log *logrus.Logger) {
log.WithFields(logrus.Fields{
"chicken": "cluck",
}).Error("error")
},
want: []string{
"level=ERROR msg=error chicken=cluck",
},
},
{
name: "level mapper",
mapper: func(logrus.Level) slog.Leveler {
return slog.LevelInfo
},
fn: func(log *logrus.Logger) {
log.WithFields(logrus.Fields{
"chicken": "cluck",
}).Error("error")
},
want: []string{
"level=INFO msg=error chicken=cluck",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
buf := &bytes.Buffer{}
slogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{
// Remove timestamps from logs, for easier comparison
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
log := logrus.New()
log.Out = io.Discard
hook := lslog.NewSlogHook(slogLogger)
hook.LevelMapper = tt.mapper
log.AddHook(hook)
tt.fn(log)
got := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(got) != len(tt.want) {
t.Errorf("Got %d log lines, expected %d", len(got), len(tt.want))
return
}
for i, line := range got {
if line != tt.want[i] {
t.Errorf("line %d differs from expectation.\n Got: %s\nWant: %s", i, line, tt.want[i])
}
}
})
}
}
type errorHandler struct{}
var _ slog.Handler = (*errorHandler)(nil)
func (h *errorHandler) Enabled(context.Context, slog.Level) bool {
return true
}
func (h *errorHandler) Handle(context.Context, slog.Record) error {
return errors.New("boom")
}
func (h *errorHandler) WithAttrs([]slog.Attr) slog.Handler {
return h
}
func (h *errorHandler) WithGroup(string) slog.Handler {
return h
}
func TestSlogHook_error_propagates(t *testing.T) {
stderr := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create pipe: %v", err)
}
os.Stderr = w
t.Cleanup(func() {
_ = r.Close()
})
slogLogger := slog.New(&errorHandler{})
log := logrus.New()
log.SetOutput(io.Discard)
log.AddHook(lslog.NewSlogHook(slogLogger))
log.WithField("key", "value").Error("test error")
// Restore stderr before closing the pipe writer to avoid leaving os.Stderr
// pointing at a closed file descriptor.
os.Stderr = stderr
_ = w.Close()
gotStderr, _ := io.ReadAll(r)
if !bytes.Contains(gotStderr, []byte("boom")) {
t.Errorf("expected stderr to contain 'boom', got: %s", string(gotStderr))
}
}
func TestSlogHook_source(t *testing.T) {
buf := &bytes.Buffer{}
slogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
AddSource: true,
}))
log := logrus.New()
log.Out = io.Discard
log.ReportCaller = true
log.AddHook(lslog.NewSlogHook(slogLogger))
log.Info("info with source")
got := strings.TrimSpace(buf.String())
wantRE := regexp.MustCompile(`source=.*hooks[\\/]+slog[\\/]+slog_test\.go:\d+`)
if !wantRE.MatchString(got) {
t.Errorf("expected log to contain source attribute matching %q, got: %s", wantRE.String(), got)
}
}
================================================
FILE: hooks/syslog/README.md
================================================
# Syslog Hooks for Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>
## Usage
```go
package main
import (
"log/syslog"
"github.com/sirupsen/logrus"
lsyslog "github.com/sirupsen/logrus/hooks/syslog"
)
func main() {
log := logrus.New()
hook, err := lsyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
}
}
```
If you want to connect to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). Just assign empty string to the first two parameters of `NewSyslogHook`. It should look like the following.
```go
package main
import (
"log/syslog"
"github.com/sirupsen/logrus"
lsyslog "github.com/sirupsen/logrus/hooks/syslog"
)
func main() {
log := logrus.New()
hook, err := lsyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
}
}
```
### Different log levels for local and remote logging
By default `NewSyslogHook()` sends logs through the hook for all log levels. If you want to have
different log levels between local logging and syslog logging (i.e., respect the `priority` argument
passed to `NewSyslogHook()`), you need to define a custom hook type that satisfies the `logrus.Hook`
interface by embedding `*lsyslog.SyslogHook` and overriding `Levels()` to return only the log levels
you're interested in.
The following example shows how to log at **DEBUG** level for local logging and **WARN** level for
syslog logging:
```go
package main
import (
"log/syslog"
log "github.com/sirupsen/logrus"
lsyslog "github.com/sirupsen/logrus/hooks/syslog"
)
type customHook struct {
*lsyslog.SyslogHook
}
func (h *customHook) Levels() []log.Level {
return []log.Level{log.WarnLevel}
}
func main() {
log.SetLevel(log.DebugLevel)
hook, err := lsyslog.NewSyslogHook("tcp", "localhost:5140", syslog.LOG_WARNING, "myTag")
if err != nil {
panic(err)
}
log.AddHook(&customHook{hook})
// ...
}
```
================================================
FILE: hooks/syslog/syslog.go
================================================
//go:build !windows && !nacl && !plan9
package syslog
import (
"fmt"
"log/syslog"
"os"
"github.com/sirupsen/logrus"
)
// SyslogHook to send logs via syslog.
type SyslogHook struct {
Writer *syslog.Writer
SyslogNetwork string
SyslogRaddr string
}
var _ logrus.Hook = (*SyslogHook)(nil)
// NewSyslogHook creates a hook to be added to an instance of logger.
//
// This is called with:
//
// hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")
// if err == nil {
// log.Hooks.Add(hook)
// }
func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
w, err := syslog.Dial(network, raddr, priority, tag)
return &SyslogHook{w, network, raddr}, err
}
func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
line, err := entry.String()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}
switch entry.Level {
case logrus.PanicLevel:
return hook.Writer.Crit(line)
case logrus.FatalLevel:
return hook.Writer.Crit(line)
case logrus.ErrorLevel:
return hook.Writer.Err(line)
case logrus.WarnLevel:
return hook.Writer.Warning(line)
case logrus.InfoLevel:
return hook.Writer.Info(line)
case logrus.DebugLevel, logrus.TraceLevel:
return hook.Writer.Debug(line)
default:
return nil
}
}
func (hook *SyslogHook) Levels() []logrus.Level {
return logrus.AllLevels
}
================================================
FILE: hooks/syslog/syslog_test.go
================================================
//go:build !windows && !nacl && !plan9
package syslog_test
import (
"io"
"log/syslog"
"testing"
"github.com/sirupsen/logrus"
lsyslog "github.com/sirupsen/logrus/hooks/syslog"
)
func TestLocalhostAddAndPrint(t *testing.T) {
log := logrus.New()
log.SetOutput(io.Discard)
hook, err := lsyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
t.Errorf("Unable to connect to local syslog.")
}
log.Hooks.Add(hook)
for _, level := range hook.Levels() {
if len(log.Hooks[level]) != 1 {
t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level]))
}
}
log.Info("Congratulations!")
}
================================================
FILE: hooks/test/test.go
================================================
// Package test is used for testing logrus.
// It provides a simple hooks which register logged messages.
package test
import (
"io"
"sync"
"github.com/sirupsen/logrus"
)
// Hook is a hook designed for dealing with logs in test scenarios.
type Hook struct {
// Entries is an array of all entries that have been received by this hook.
// For safe access, use the AllEntries() method, rather than reading this
// value directly.
Entries []logrus.Entry
mu sync.RWMutex
}
var _ logrus.Hook = (*Hook)(nil)
// NewGlobal installs a test hook for the global logger.
func NewGlobal() *Hook {
hook := new(Hook)
logrus.AddHook(hook)
return hook
}
// NewLocal installs a test hook for a given local logger.
func NewLocal(logger *logrus.Logger) *Hook {
hook := new(Hook)
logger.AddHook(hook)
return hook
}
// NewNullLogger creates a discarding logger and installs the test hook.
func NewNullLogger() (*logrus.Logger, *Hook) {
logger := logrus.New()
logger.Out = io.Discard
return logger, NewLocal(logger)
}
func (t *Hook) Fire(e *logrus.Entry) error {
t.mu.Lock()
defer t.mu.Unlock()
t.Entries = append(t.Entries, *e)
return nil
}
func (t *Hook) Levels() []logrus.Level {
return logrus.AllLevels
}
// LastEntry returns the last entry that was logged or nil.
func (t *Hook) LastEntry() *logrus.Entry {
t.mu.RLock()
defer t.mu.RUnlock()
i := len(t.Entries) - 1
if i < 0 {
return nil
}
return &t.Entries[i]
}
// AllEntries returns all entries that were logged.
func (t *Hook) AllEntries() []*logrus.Entry {
t.mu.RLock()
defer t.mu.RUnlock()
// Make a copy so the returned value won't race with future log requests
entries := make([]*logrus.Entry, len(t.Entries))
for i := 0; i < len(t.Entries); i++ {
// Make a copy, for safety
entries[i] = &t.Entries[i]
}
return entries
}
// Reset removes all Entries from this test hook.
func (t *Hook) Reset() {
t.mu.Lock()
defer t.mu.Unlock()
t.Entries = make([]logrus.Entry, 0)
}
================================================
FILE: hooks/test/test_test.go
================================================
package test_test
import (
"io"
"math/rand"
"sync"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
)
func TestAllHooks(t *testing.T) {
// Test modifies the standard-logger; restore it afterward.
stdLogger := logrus.StandardLogger()
oldOut := stdLogger.Out
oldHooks := stdLogger.ReplaceHooks(make(logrus.LevelHooks))
t.Cleanup(func() {
stdLogger.SetOutput(oldOut)
stdLogger.ReplaceHooks(oldHooks)
})
assert := assert.New(t)
logger, hook := test.NewNullLogger()
assert.Nil(hook.LastEntry())
assert.Empty(hook.Entries)
logger.Error("Hello error")
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal("Hello error", hook.LastEntry().Message)
assert.Len(hook.Entries, 1)
logger.Warn("Hello warning")
assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
assert.Equal("Hello warning", hook.LastEntry().Message)
assert.Len(hook.Entries, 2)
hook.Reset()
assert.Nil(hook.LastEntry())
assert.Empty(hook.Entries)
hook = test.NewGlobal()
logrus.SetOutput(io.Discard)
logrus.Error("Hello error")
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal("Hello error", hook.LastEntry().Message)
assert.Len(hook.Entries, 1)
}
func TestLoggingWithHooksRace(t *testing.T) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
unlocker := r.Intn(100)
assert := assert.New(t)
logger, hook := test.NewNullLogger()
var wgOne, wgAll sync.WaitGroup
wgOne.Add(1)
wgAll.Add(100)
for i := range 100 {
go func(i int) {
logger.Info("info")
wgAll.Done()
if i == unlocker {
wgOne.Done()
}
}(i)
}
wgOne.Wait()
assert.Equal(logrus.InfoLevel, hook.LastEntry().Level)
assert.Equal("info", hook.LastEntry().Message)
wgAll.Wait()
entries := hook.AllEntries()
assert.Len(entries, 100)
}
// nolint:staticcheck // linter assumes logger.Fatal exits, resulting in false SA4006 warnings.
func TestFatalWithAlternateExit(t *testing.T) {
assert := assert.New(t)
logger, hook := test.NewNullLogger()
logger.ExitFunc = func(code int) {}
logger.Fatal("something went very wrong")
assert.Equal(logrus.FatalLevel, hook.LastEntry().Level)
assert.Equal("something went very wrong", hook.LastEntry().Message)
assert.Len(hook.Entries, 1)
}
func TestNewLocal(t *testing.T) {
assert := assert.New(t)
logger := logrus.New()
logger.SetOutput(io.Discard)
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(10)
for range 10 {
go func() {
logger.Info("info")
wg.Done()
}()
}
hook := test.NewLocal(logger)
assert.NotNil(hook)
}
================================================
FILE: hooks/writer/README.md
================================================
# Writer Hooks for Logrus
Send logs of given levels to any object with `io.Writer` interface.
## Usage
If you want for example send high level logs to `Stderr` and
logs of normal execution to `Stdout`, you could do it like this:
```go
package main
import (
"io/ioutil"
"os"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/writer"
)
func main() {
log.SetOutput(ioutil.Discard) // Send all logs to nowhere by default
log.AddHook(&writer.Hook{ // Send logs with level higher than warning to stderr
Writer: os.Stderr,
LogLevels: []log.Level{
log.PanicLevel,
log.FatalLevel,
log.ErrorLevel,
log.WarnLevel,
},
})
log.AddHook(&writer.Hook{ // Send info and debug logs to stdout
Writer: os.Stdout,
LogLevels: []log.Level{
log.InfoLevel,
log.DebugLevel,
},
})
log.Info("This will go to stdout")
log.Warn("This will go to stderr")
}
```
================================================
FILE: hooks/writer/writer.go
================================================
package writer
import (
"io"
"github.com/sirupsen/logrus"
)
// Hook is a hook that writes logs of specified LogLevels to specified Writer
type Hook struct {
Writer io.Writer
LogLevels []logrus.Level
}
var _ logrus.Hook = (*Hook)(nil)
// Fire will be called when some logging function is called with current hook
// It will format log entry to string and write it to appropriate writer
func (hook *Hook) Fire(entry *logrus.Entry) error {
line, err := entry.Bytes()
if err != nil {
return err
}
_, err = hook.Writer.Write(line)
return err
}
// Levels define on which log levels this hook would trigger
func (hook *Hook) Levels() []logrus.Level {
return hook.LogLevels
}
================================================
FILE: hooks/writer/writer_test.go
================================================
package writer_test
import (
"bytes"
"io"
"testing"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/writer"
"github.com/stretchr/testify/assert"
)
func TestDifferentLevelsGoToDifferentWriters(t *testing.T) {
var a, b bytes.Buffer
log := logrus.New()
log.SetFormatter(&logrus.TextFormatter{
DisableTimestamp: true,
DisableColors: true,
})
log.SetOutput(io.Discard) // Send all logs to nowhere by default
log.AddHook(&writer.Hook{
Writer: &a,
LogLevels: []logrus.Level{
logrus.WarnLevel,
},
})
log.AddHook(&writer.Hook{ // Send info and debug logs to stdout
Writer: &b,
LogLevels: []logrus.Level{
logrus.InfoLevel,
},
})
log.Warn("send to a")
log.Info("send to b")
assert.Equal(t, "level=warning msg=\"send to a\"\n", a.String())
assert.Equal(t, "level=info msg=\"send to b\"\n", b.String())
}
================================================
FILE: hooks.go
================================================
package logrus
// Hook describes hooks to be fired when logging on the logging levels returned from
// [Hook.Levels] on your implementation of the interface. Note that this is not
// fired in a goroutine or a channel with workers, you should handle such
// functionality yourself if your call is non-blocking, and you don't wish for
// the logging calls for levels returned from `Levels()` to block.
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
// LevelHooks is an internal type for storing the hooks on a logger instance.
type LevelHooks map[Level][]Hook
// Add a hook to an instance of logger. This is called with
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
func (hooks LevelHooks) Add(hook Hook) {
for _, level := range hook.Levels() {
hooks[level] = append(hooks[level], hook)
}
}
// Fire all the hooks for the passed level. Used by `entry.log` to fire
// appropriate hooks for a log entry.
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
for _, hook := range hooks[level] {
if err := hook.Fire(entry); err != nil {
return err
}
}
return nil
}
================================================
FILE: internal/testutils/testutils.go
================================================
package testutils
import (
"bytes"
"encoding/json"
"strconv"
"strings"
"testing"
. "github.com/sirupsen/logrus" //nolint:staticcheck
"github.com/stretchr/testify/require"
)
func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
var buffer bytes.Buffer
var fields Fields
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
log(logger)
err := json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err)
assertions(fields)
}
func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
var buffer bytes.Buffer
logger := New()
logger.Out = &buffer
logger.Formatter = &TextFormatter{
DisableColors: true,
}
log(logger)
fields := make(map[string]string)
for _, kv := range strings.Split(strings.TrimRight(buffer.String(), "\n"), " ") {
if !strings.Contains(kv, "=") {
continue
}
kvArr := strings.Split(kv, "=")
key := strings.TrimSpace(kvArr[0])
val := kvArr[1]
if kvArr[1][0] == '"' {
var err error
val, err = strconv.Unquote(val)
require.NoError(t, err)
}
fields[key] = val
}
assertions(fields)
}
================================================
FILE: json_formatter.go
================================================
package logrus
import (
"bytes"
"encoding/json"
"fmt"
"runtime"
"strconv"
)
type fieldKey string
// FieldMap allows customization of the key names for default fields.
type FieldMap map[fieldKey]string
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
// JSONFormatter formats logs into parsable json
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
// 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
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
// DisableHTMLEscape allows disabling html escaping in output
DisableHTMLEscape bool
// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
DataKey string
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message",
// FieldKeyFunc: "@caller",
// },
// }
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the json data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from json fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
// PrettyPrint will indent all json logs
PrettyPrint bool
}
// Format renders a single log entry
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
caller := entry.Caller
data := make(Fields, len(entry.Data)+defaultFields)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
if f.DataKey != "" && len(entry.Data) > 0 {
newData := make(Fields, defaultFields+1)
newData[f.DataKey] = data
data = newData
}
hasCaller := caller != nil
prefixFieldClashes(data, f.FieldMap, hasCaller)
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if entry.err != "" {
data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err
}
if !f.DisableTimestamp {
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
}
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
if caller != nil {
var funcVal, fileVal string
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(caller)
} else {
funcVal = caller.Function
fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10)
}
if funcVal != "" {
data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal
}
if fileVal != "" {
data[f.FieldMap.resolve(FieldKeyFile)] = fileVal
}
}
b := entry.Buffer
if b == nil {
b = new(bytes.Buffer)
}
encoder := json.NewEncoder(b)
encoder.SetEscapeHTML(!f.DisableHTMLEscape)
if f.PrettyPrint {
encoder.SetIndent("", " ")
}
if err := encoder.Encode(data); err != nil {
return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err)
}
return b.Bytes(), nil
}
================================================
FILE: json_formatter_test.go
================================================
package logrus_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"runtime"
"strings"
"testing"
"github.com/sirupsen/logrus"
)
func TestErrorNotLost(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("error", errors.New("wild walrus")))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["error"] != "wild walrus" {
t.Fatal("Error field not set")
}
}
func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("omg", errors.New("wild walrus")))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["omg"] != "wild walrus" {
t.Fatal("Error field not set")
}
}
func TestFieldClashWithTime(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("time", "right now!"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["fields.time"] != "right now!" {
t.Fatal("fields.time not set to original time field")
}
if entry["time"] != "0001-01-01T00:00:00Z" {
t.Fatal("time field not set to current time, was: ", entry["time"])
}
}
func TestFieldClashWithMsg(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("msg", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["fields.msg"] != "something" {
t.Fatal("fields.msg not set to original msg field")
}
}
func TestFieldClashWithLevel(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["fields.level"] != "something" {
t.Fatal("fields.level not set to original level field")
}
}
func TestFieldClashWithRemappedFields(t *testing.T) {
formatter := &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "@timestamp",
logrus.FieldKeyLevel: "@level",
logrus.FieldKeyMsg: "@message",
},
}
b, err := formatter.Format(logrus.WithFields(logrus.Fields{
"@timestamp": "@timestamp",
"@level": "@level",
"@message": "@message",
"timestamp": "timestamp",
"level": "level",
"msg": "msg",
}))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
for _, field := range []string{"timestamp", "level", "msg"} {
if entry[field] != field {
t.Errorf("Expected field %v to be untouched; got %v", field, entry[field])
}
remappedKey := fmt.Sprintf("fields.%s", field)
if remapped, ok := entry[remappedKey]; ok {
t.Errorf("Expected %s to be empty; got %v", remappedKey, remapped)
}
}
for _, field := range []string{"@timestamp", "@level", "@message"} {
if entry[field] == field {
t.Errorf("Expected field %v to be mapped to an Entry value", field)
}
remappedKey := fmt.Sprintf("fields.%s", field)
if remapped, ok := entry[remappedKey]; ok {
if remapped != field {
t.Errorf("Expected field %v to be copied to %s; got %v", field, remappedKey, remapped)
}
} else {
t.Errorf("Expected field %v to be copied to %s; was absent", field, remappedKey)
}
}
}
func TestFieldsInNestedDictionary(t *testing.T) {
formatter := &logrus.JSONFormatter{
DataKey: "args",
}
logEntry := logrus.WithFields(logrus.Fields{
"level": "level",
"test": "test",
})
logEntry.Level = logrus.InfoLevel
b, err := formatter.Format(logEntry)
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
args := entry["args"].(map[string]any)
for _, field := range []string{"test", "level"} {
if value, present := args[field]; !present || value != field {
t.Errorf("Expected field %v to be present under 'args'; untouched", field)
}
}
for _, field := range []string{"test", "fields.level"} {
if _, present := entry[field]; present {
t.Errorf("Expected field %v not to be present at top level", field)
}
}
// with nested object, "level" shouldn't clash
if entry["level"] != "info" {
t.Errorf("Expected 'level' field to contain 'info'")
}
}
func TestJSONEntryFieldValueError(t *testing.T) {
t.Run("good value", func(t *testing.T) {
var buf bytes.Buffer
l := logrus.New()
l.SetOutput(&buf)
l.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})
l.WithField("ok", "ok").Info("test")
var data map[string]any
err := json.Unmarshal(buf.Bytes(), &data)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if _, ok := data[logrus.FieldKeyLogrusError]; ok {
t.Errorf(`Unexpected "logrus_error" field in log entry: %v`, data)
}
if v, ok := data["ok"]; !ok || v != "ok" {
t.Errorf(`Expected log entry to contain "ok"="ok": %v`, data)
}
})
// If we dropped an unsupported field, the FieldKeyLogrusError should
// contain a message that we did.
t.Run("bad and good value", func(t *testing.T) {
var buf bytes.Buffer
l := logrus.New()
l.SetOutput(&buf)
l.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})
l.WithField("func", func() {}).WithField("ok", "ok").Info("test")
var data map[string]any
if err := json.Unmarshal(buf.Bytes(), &data); err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if v, ok := data[logrus.FieldKeyLogrusError]; !ok || v == "" {
t.Errorf(`Expected log entry to contain a "logrus_error" field: %v`, data)
}
if _, ok := data["func"]; ok {
t.Errorf(`Expected "func" field to be removed from log entry: %v`, data)
}
if v, ok := data["ok"]; !ok || v != "ok" {
t.Errorf(`Expected log entry to contain "ok=ok": %v`, data)
}
})
// This is testing the current behavior; error is preserved, even if an
// unsupported value was dropped and replaced with a supported value for
// the same field.
t.Run("replace bad value", func(t *testing.T) {
var buf bytes.Buffer
l := logrus.New()
l.SetOutput(&buf)
l.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})
l.WithField("func", func() {}).WithField("ok", "ok").WithField("func", "not-a-func").Info("test")
var data map[string]any
if err := json.Unmarshal(buf.Bytes(), &data); err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if v, ok := data[logrus.FieldKeyLogrusError]; !ok || v == "" {
t.Errorf(`Expected log entry to contain a "logrus_error" field: %v`, data)
}
if v, ok := data["func"]; !ok || v != "not-a-func" {
t.Errorf(`Expected log entry to contain "func=not-a-func": %v`, data)
}
if v, ok := data["ok"]; !ok || v != "ok" {
t.Errorf(`Expected log entry to contain "ok=ok": %v`, data)
}
})
}
func TestJSONEntryEndsWithNewline(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
if b[len(b)-1] != '\n' {
t.Fatal("Expected JSON log entry to end with a newline")
}
}
func TestJSONMessageKey(t *testing.T) {
formatter := &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyMsg: "message",
},
}
b, err := formatter.Format(&logrus.Entry{Message: "oh hai"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, `"message":"oh hai"`) {
t.Fatal("Expected JSON to format message key")
}
}
func TestJSONLevelKey(t *testing.T) {
formatter := &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyLevel: "somelevel",
},
}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "somelevel") {
t.Fatal("Expected JSON to format level key")
}
}
func TestJSONTimeKey(t *testing.T) {
formatter := &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "timeywimey",
},
}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "timeywimey") {
t.Fatal("Expected JSON to format time key")
}
}
func TestFieldDoesNotClashWithCaller(t *testing.T) {
logrus.SetReportCaller(false)
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("func", "howdy pardner"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["func"] != "howdy pardner" {
t.Fatal("func field replaced when ReportCaller=false")
}
}
func TestFieldClashWithCaller(t *testing.T) {
logrus.SetReportCaller(true)
t.Cleanup(func() {
logrus.SetReportCaller(false) // return to default value
})
formatter := &logrus.JSONFormatter{}
e := logrus.WithField("func", "howdy pardner")
e.Caller = &runtime.Frame{Function: "somefunc"}
b, err := formatter.Format(e)
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
entry := make(map[string]any)
err = json.Unmarshal(b, &entry)
if err != nil {
t.Fatal("Unable to unmarshal formatted entry: ", err)
}
if entry["fields.func"] != "howdy pardner" {
t.Fatalf("fields.func not set to original func field when ReportCaller=true (got '%s')",
entry["fields.func"])
}
if entry["func"] != "somefunc" {
t.Fatalf("func not set as expected when ReportCaller=true (got '%s')",
entry["func"])
}
}
func TestJSONDisableTimestamp(t *testing.T) {
formatter := &logrus.JSONFormatter{
DisableTimestamp: true,
}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if strings.Contains(s, logrus.FieldKeyTime) {
t.Error("Did not prevent timestamp", s)
}
}
func TestJSONEnableTimestamp(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(logrus.WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, logrus.FieldKeyTime) {
t.Error("Timestamp not present", s)
}
}
func TestJSONDisableHTMLEscape(t *testing.T) {
formatter := &logrus.JSONFormatter{DisableHTMLEscape: true}
b, err := formatter.Format(&logrus.Entry{Message: "& < >"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "& < >") {
t.Error("Message should not be HTML escaped", s)
}
}
func TestJSONEnableHTMLEscape(t *testing.T) {
formatter := &logrus.JSONFormatter{}
b, err := formatter.Format(&logrus.Entry{Message: "& < >"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, `\u0026 \u003c \u003e`) {
t.Error("Message should be HTML escaped", s)
}
}
================================================
FILE: level.go
================================================
package logrus
import (
"strings"
"sync"
)
const (
ansiReset = "\x1b[0m" // reset attributes
ansiRed = "\x1b[31m" // red
ansiYellow = "\x1b[33m" // yellow
ansiCyan = "\x1b[36m" // cyan
ansiWhite = "\x1b[37m" // white (light gray)
)
type lvlPrefix struct {
full string
truncated string
padded string
}
func colorize(level Level, s string) string {
color := ansiCyan
switch level {
case DebugLevel, TraceLevel:
color = ansiWhite
case WarnLevel:
color = ansiYellow
case ErrorLevel, FatalLevel, PanicLevel:
color = ansiRed
case InfoLevel:
color = ansiCyan
}
return color + s + ansiReset
}
func formatLevel(level Level, disableTrunc, pad bool, maxLen int) string {
upper := strings.ToUpper(level.String())
if pad && maxLen > len(upper) {
upper += strings.Repeat(" ", maxLen-len(upper))
}
if !pad && !disableTrunc && len(upper) > 4 {
upper = upper[:4]
}
return colorize(level, upper)
}
var levelPrefixOnce = sync.OnceValues(func() (map[Level]lvlPrefix, lvlPrefix) {
var maxLevel Level
maxLen := 0
for _, lvl := range AllLevels {
if lvl > maxLevel {
maxLevel = lvl
}
if l := len(lvl.String()); l > maxLen {
maxLen = l
}
}
prefix := make(map[Level]lvlPrefix, len(AllLevels))
for _, lvl := range AllLevels {
prefix[lvl] = lvlPrefix{
full: formatLevel(lvl, true, false, maxLen),
truncated: formatLevel(lvl, false, false, maxLen),
padded: formatLevel(lvl, true, true, maxLen),
}
}
unknownLevel := maxLevel + 1
unknown := lvlPrefix{
full: formatLevel(unknownLevel, true, false, maxLen),
truncated: formatLevel(unknownLevel, false, false, maxLen),
padded: formatLevel(unknownLevel, true, true, maxLen),
}
return prefix, unknown
})
func levelPrefix(level Level, disableTrunc, pad bool) string {
prefix, unknown := levelPrefixOnce()
p, ok := prefix[level]
if !ok {
p = unknown
}
switch {
case pad:
return p.padded
case !disableTrunc:
return p.truncated
default:
return p.full
}
}
================================================
FILE: level_test.go
================================================
package logrus_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)
func TestLevelJsonEncoding(t *testing.T) {
type X struct {
Level logrus.Level
}
var x X
x.Level = logrus.WarnLevel
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
require.NoError(t, enc.Encode(x))
dec := json.NewDecoder(&buf)
var y X
require.NoError(t, dec.Decode(&y))
}
func TestLevelUnmarshalText(t *testing.T) {
var u logrus.Level
for _, level := range logrus.AllLevels {
t.Run(level.String(), func(t *testing.T) {
require.NoError(t, u.UnmarshalText([]byte(level.String())))
require.Equal(t, level, u)
})
}
t.Run("invalid", func(t *testing.T) {
require.Error(t, u.UnmarshalText([]byte("invalid")))
})
}
func TestLevelMarshalText(t *testing.T) {
levelStrings := []string{
"panic",
"fatal",
"error",
"warning",
"info",
"debug",
"trace",
}
for idx, val := range logrus.AllLevels {
level := val
t.Run(level.String(), func(t *testing.T) {
var cmp logrus.Level
b, err := level.MarshalText()
require.NoError(t, err)
require.Equal(t, levelStrings[idx], string(b))
err = cmp.UnmarshalText(b)
require.NoError(t, err)
require.Equal(t, level, cmp)
})
}
}
================================================
FILE: logger.go
================================================
package logrus
import (
"context"
"io"
"os"
"sync"
"sync/atomic"
"time"
)
// LogFunction For big messages, it can be more efficient to pass a function
// and only call it if the log level is actually enables rather than
// generating the log message and then checking if the level is enabled
type LogFunction func() []any
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventurous, such as logging to Kafka.
Out io.Writer
// Hooks for the logger instance. These allow firing events based on logging
// levels and log entries. For example, to send errors to an error tracking
// service, log to StatsD or dump the core on fatal errors.
Hooks LevelHooks
// All log entries pass through the formatter before logged to Out. The
// included formatters are `TextFormatter` and `JSONFormatter` for which
// TextFormatter is the default. In development (when a TTY is attached) it
// logs with colors, but to a file it wouldn't. You can easily implement your
// own that implements the `Formatter` interface, see the `README` or included
// formatters for examples.
Formatter Formatter
// Flag for whether to log caller info (off by default)
ReportCaller bool
// The logging level the logger should log at. This is typically (and defaults
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
// logged.
Level Level
// Used to sync writing to the log. Locking is enabled by Default
mu MutexWrap
// Reusable empty entry
entryPool sync.Pool
// Function to exit the application, defaults to `os.Exit()`
ExitFunc func(int)
// The buffer pool used to format the log. If it is nil, the default global
// buffer pool will be used.
BufferPool BufferPool
}
type MutexWrap struct {
lock sync.Mutex
disabled bool
}
func (mw *MutexWrap) Lock() {
if !mw.disabled {
mw.lock.Lock()
}
}
func (mw *MutexWrap) Unlock() {
if !mw.disabled {
mw.lock.Unlock()
}
}
func (mw *MutexWrap) Disable() {
mw.disabled = true
}
// New Creates a new logger. Configuration should be set by changing [Formatter],
// Out and Hooks directly on the default Logger instance. You can also just
// instantiate your own:
//
// var log = &logrus.Logger{
// Out: os.Stderr,
// Formatter: new(logrus.TextFormatter),
// Hooks: make(logrus.LevelHooks),
// Level: logrus.DebugLevel,
// }
//
// It's recommended to make this a global instance called `log`.
func New() *Logger {
return &Logger{
Out: os.Stderr,
Formatter: new(TextFormatter),
Hooks: make(LevelHooks),
Level: InfoLevel,
ExitFunc: os.Exit,
ReportCaller: false,
}
}
func (logger *Logger) newEntry() *Entry {
entry, ok := logger.entryPool.Get().(*Entry)
if ok {
return entry
}
return NewEntry(logger)
}
func (logger *Logger) releaseEntry(entry *Entry) {
entry.Data = map[string]any{}
logger.entryPool.Put(entry)
}
// WithField allocates a new entry and adds a field to it.
// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func (logger *Logger) WithField(key string, value any) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithField(key, value)
}
// WithFields adds a struct of fields to the log entry. It calls [Entry.WithField]
// for each Field.
func (logger *Logger) WithFields(fields Fields) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithFields(fields)
}
// WithError adds an error as single field to the log entry. It calls
// [Entry.WithError] for the given error.
func (logger *Logger) WithError(err error) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithError(err)
}
// WithContext add a context to the log entry.
func (logger *Logger) WithContext(ctx context.Context) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithContext(ctx)
}
// WithTime overrides the time of the log entry.
func (logger *Logger) WithTime(t time.Time) *Entry {
entry := logger.newEntry()
defer logger.releaseEntry(entry)
return entry.WithTime(t)
}
func (logger *Logger) Logf(level Level, format string, args ...any) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logf(level, format, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Tracef(format string, args ...any) {
logger.Logf(TraceLevel, format, args...)
}
func (logger *Logger) Debugf(format string, args ...any) {
logger.Logf(DebugLevel, format, args...)
}
func (logger *Logger) Infof(format string, args ...any) {
logger.Logf(InfoLevel, format, args...)
}
func (logger *Logger) Printf(format string, args ...any) {
entry := logger.newEntry()
entry.Printf(format, args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnf(format string, args ...any) {
logger.Logf(WarnLevel, format, args...)
}
func (logger *Logger) Warningf(format string, args ...any) {
logger.Warnf(format, args...)
}
func (logger *Logger) Errorf(format string, args ...any) {
logger.Logf(ErrorLevel, format, args...)
}
func (logger *Logger) Fatalf(format string, args ...any) {
logger.Logf(FatalLevel, format, args...)
logger.Exit(1)
}
func (logger *Logger) Panicf(format string, args ...any) {
logger.Logf(PanicLevel, format, args...)
}
// Log will log a message at the level given as parameter.
// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.
// For this behaviour Logger.Panic or Logger.Fatal should be used instead.
func (logger *Logger) Log(level Level, args ...any) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) LogFn(level Level, fn LogFunction) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Log(level, fn()...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Trace(args ...any) {
logger.Log(TraceLevel, args...)
}
func (logger *Logger) Debug(args ...any) {
logger.Log(DebugLevel, args...)
}
func (logger *Logger) Info(args ...any) {
logger.Log(InfoLevel, args...)
}
func (logger *Logger) Print(args ...any) {
entry := logger.newEntry()
entry.Print(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warn(args ...any) {
logger.Log(WarnLevel, args...)
}
func (logger *Logger) Warning(args ...any) {
logger.Warn(args...)
}
func (logger *Logger) Error(args ...any) {
logger.Log(ErrorLevel, args...)
}
func (logger *Logger) Fatal(args ...any) {
logger.Log(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panic(args ...any) {
logger.Log(PanicLevel, args...)
}
func (logger *Logger) TraceFn(fn LogFunction) {
logger.LogFn(TraceLevel, fn)
}
func (logger *Logger) DebugFn(fn LogFunction) {
logger.LogFn(DebugLevel, fn)
}
func (logger *Logger) InfoFn(fn LogFunction) {
logger.LogFn(InfoLevel, fn)
}
func (logger *Logger) PrintFn(fn LogFunction) {
entry := logger.newEntry()
entry.Print(fn()...)
logger.releaseEntry(entry)
}
func (logger *Logger) WarnFn(fn LogFunction) {
logger.LogFn(WarnLevel, fn)
}
func (logger *Logger) WarningFn(fn LogFunction) {
logger.WarnFn(fn)
}
func (logger *Logger) ErrorFn(fn LogFunction) {
logger.LogFn(ErrorLevel, fn)
}
func (logger *Logger) FatalFn(fn LogFunction) {
logger.LogFn(FatalLevel, fn)
logger.Exit(1)
}
func (logger *Logger) PanicFn(fn LogFunction) {
logger.LogFn(PanicLevel, fn)
}
func (logger *Logger) Logln(level Level, args ...any) {
if logger.IsLevelEnabled(level) {
entry := logger.newEntry()
entry.Logln(level, args...)
logger.releaseEntry(entry)
}
}
func (logger *Logger) Traceln(args ...any) {
logger.Logln(TraceLevel, args...)
}
func (logger *Logger) Debugln(args ...any) {
logger.Logln(DebugLevel, args...)
}
func (logger *Logger) Infoln(args ...any) {
logger.Logln(InfoLevel, args...)
}
func (logger *Logger) Println(args ...any) {
entry := logger.newEntry()
entry.Println(args...)
logger.releaseEntry(entry)
}
func (logger *Logger) Warnln(args ...any) {
logger.Logln(WarnLevel, args...)
}
func (logger *Logger) Warningln(args ...any) {
logger.Warnln(args...)
}
func (logger *Logger) Errorln(args ...any) {
logger.Logln(ErrorLevel, args...)
}
func (logger *Logger) Fatalln(args ...any) {
logger.Logln(FatalLevel, args...)
logger.Exit(1)
}
func (logger *Logger) Panicln(args ...any) {
logger.Logln(PanicLevel, args...)
}
func (logger *Logger) Exit(code int) {
runHandlers()
if logger.ExitFunc == nil {
logger.ExitFunc = os.Exit
}
logger.ExitFunc(code)
}
// SetNoLock disables the lock for situations where a file is opened with
// appending mode, and safe for concurrent writes to the file (within 4k
// message on Linux). In these cases user can choose to disable the lock.
func (logger *Logger) SetNoLock() {
logger.mu.Disable()
}
func (logger *Logger) level() Level {
return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
}
// SetLevel sets the logger level.
func (logger *Logger) SetLevel(level Level) {
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
}
// GetLevel returns the logger level.
func (logger *Logger) GetLevel() Level {
return logger.level()
}
// AddHook adds a hook to the logger hooks.
func (logger *Logger) AddHook(hook Hook) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Hooks.Add(hook)
}
// hooksForLevel returns a snapshot of the hooks registered for the given level.
// The returned slice is a shallow copy and may be used without holding logger.mu.
func (logger *Logger) hooksForLevel(level Level) []Hook {
logger.mu.Lock()
hooks := logger.Hooks[level]
if len(hooks) == 0 {
logger.mu.Unlock()
return nil
}
out := make([]Hook, len(hooks))
copy(out, hooks)
logger.mu.Unlock()
return out
}
// IsLevelEnabled checks if logging for the given level is enabled.
func (logger *Logger) IsLevelEnabled(level Level) bool {
return logger.level() >= level
}
// SetFormatter sets the logger formatter.
func (logger *Logger) SetFormatter(formatter Formatter) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Formatter = formatter
}
// SetOutput sets the logger output.
func (logger *Logger) SetOutput(output io.Writer) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Out = output
}
func (logger *Logger) SetReportCaller(reportCaller bool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.ReportCaller = reportCaller
}
// ReplaceHooks replaces the logger hooks and returns the old ones
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
logger.mu.Lock()
defer logger.mu.Unlock()
oldHooks := logger.Hooks
logger.Hooks = hooks
return oldHooks
}
// SetBufferPool sets the logger buffer pool.
func (logger *Logger) SetBufferPool(pool BufferPool) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.BufferPool = pool
}
================================================
FILE: logger_bench_test.go
================================================
package logrus_test
import (
"io"
"os"
"testing"
"github.com/sirupsen/logrus"
)
func BenchmarkDummyLogger(b *testing.B) {
nullf, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0o666)
if err != nil {
b.Fatalf("%v", err)
}
defer nullf.Close()
doLoggerBenchmark(b, nullf, &logrus.TextFormatter{DisableColors: true}, smallFields)
}
func BenchmarkDummyLoggerNoLock(b *testing.B) {
nullf, err := os.OpenFile(os.DevNull, os.O_WRONLY|os.O_APPEND, 0o666)
if err != nil {
b.Fatalf("%v", err)
}
defer nullf.Close()
doLoggerBenchmarkNoLock(b, nullf, &logrus.TextFormatter{DisableColors: true}, smallFields)
}
func doLoggerBenchmark(b *testing.B, out *os.File, formatter logrus.Formatter, fields logrus.Fields) {
logger := logrus.Logger{
Out: out,
Level: logrus.InfoLevel,
Formatter: formatter,
}
b.RunParallel(func(pb *testing.PB) {
entry := logger.WithFields(fields) // new entry per goroutine
for pb.Next() {
entry.Info("aaa")
}
})
}
func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter logrus.Formatter, fields logrus.Fields) {
logger := logrus.Logger{
Out: out,
Level: logrus.InfoLevel,
Formatter: formatter,
}
logger.SetNoLock()
b.RunParallel(func(pb *testing.PB) {
entry := logger.WithFields(fields) // new entry per goroutine
for pb.Next() {
entry.Info("aaa")
}
})
}
func BenchmarkLoggerJSONFormatter(b *testing.B) {
doLoggerBenchmarkWithFormatter(b, &logrus.JSONFormatter{})
}
func BenchmarkLoggerTextFormatter(b *testing.B) {
doLoggerBenchmarkWithFormatter(b, &logrus.TextFormatter{})
}
func doLoggerBenchmarkWithFormatter(b *testing.B, f logrus.Formatter) {
b.SetParallelism(100)
log := logrus.New()
log.Formatter = f
log.Out = io.Discard
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
log.
WithField("foo1", "bar1").
WithField("foo2", "bar2").
Info("this is a dummy log")
}
})
}
================================================
FILE: logger_test.go
================================================
package logrus_test
import (
"bytes"
"io"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func TestWarningAndWarninglnFormatting(t *testing.T) {
var buf bytes.Buffer
l := &logrus.Logger{
Out: &buf,
Formatter: &logrus.TextFormatter{
DisableColors: true,
DisableTimestamp: true,
DisableLevelTruncation: true,
},
Hooks: make(logrus.LevelHooks),
Level: logrus.DebugLevel,
}
l.Warning("hello", "world")
expected := "level=warning msg=helloworld\n"
assert.Equal(t, expected, buf.String())
buf.Reset()
l.Warningln("hello", "world")
expected = "level=warning msg=\"hello world\"\n"
assert.Equal(t, expected, buf.String())
}
type testBufferPool struct {
buffers []*bytes.Buffer
get int
}
func (p *testBufferPool) Get() *bytes.Buffer {
p.get++
return new(bytes.Buffer)
}
func (p *testBufferPool) Put(buf *bytes.Buffer) {
p.buffers = append(p.buffers, buf)
}
func TestLogger_SetBufferPool(t *testing.T) {
l := logrus.New()
l.SetOutput(io.Discard)
pool := new(testBufferPool)
l.SetBufferPool(pool)
l.Info("test")
assert.Equal(t, 1, pool.get, "Logger.SetBufferPool(): The BufferPool.Get() must be called")
assert.Len(t, pool.buffers, 1, "Logger.SetBufferPool(): The BufferPool.Put() must be called")
}
================================================
FILE: logrus.go
================================================
package logrus
import (
"bytes"
"fmt"
"log"
)
// Fields type, used to pass to [WithFields].
type Fields map[string]any
// Level type
//
//nolint:recvcheck // the methods of "Entry" use pointer receiver and non-pointer receiver.
type Level uint32
// Convert the Level to a string. E.g. [PanicLevel] becomes "panic".
func (level Level) String() string {
switch level {
case TraceLevel:
return "trace"
case DebugLevel:
return "debug"
case InfoLevel:
return "info"
case WarnLevel:
return "warning"
case ErrorLevel:
return "error"
case FatalLevel:
return "fatal"
case PanicLevel:
return "panic"
default:
return "unknown"
}
}
// ParseLevel takes a string level and returns the Logrus log level constant.
func ParseLevel(lvl string) (Level, error) {
return parseLevel([]byte(lvl))
}
func parseLevel(b []byte) (Level, error) {
switch {
case bytes.EqualFold(b, []byte("panic")):
return PanicLevel, nil
case bytes.EqualFold(b, []byte("fatal")):
return FatalLevel, nil
case bytes.EqualFold(b, []byte("error")):
return ErrorLevel, nil
case bytes.EqualFold(b, []byte("warn")),
bytes.EqualFold(b, []byte("warning")):
return WarnLevel, nil
case bytes.EqualFold(b, []byte("info")):
return InfoLevel, nil
case bytes.EqualFold(b, []byte("debug")):
return DebugLevel, nil
case bytes.EqualFold(b, []byte("trace")):
return TraceLevel, nil
default:
return 0, fmt.Errorf("not a valid logrus Level: %q", b)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (level *Level) UnmarshalText(text []byte) error {
l, err := parseLevel(text)
if err != nil {
return err
}
*level = l
return nil
}
func (level Level) MarshalText() ([]byte, error) {
switch level {
case TraceLevel, DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel:
return []byte(level.String()), nil
default:
return nil, fmt.Errorf("not a valid logrus level %d", level)
}
}
// AllLevels exposing all logging levels.
var AllLevels = []Level{
PanicLevel,
FatalLevel,
ErrorLevel,
WarnLevel,
InfoLevel,
DebugLevel,
TraceLevel,
}
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
// Won't compile if StdLogger can't be realized by a log.Logger
var (
_ StdLogger = &log.Logger{}
_ StdLogger = &Entry{}
_ StdLogger = &Logger{}
)
// StdLogger is what your logrus-enabled library should take, that way
// it'll accept a stdlib logger ([log.Logger]) and a logrus logger.
// There's no standard interface, so this is the closest we get, unfortunately.
type StdLogger interface {
Print(...any)
Printf(string, ...any)
Println(...any)
Fatal(...any)
Fatalf(string, ...any)
Fatalln(...any)
Panic(...any)
Panicf(string, ...any)
Panicln(...any)
}
// FieldLogger extends the [StdLogger] interface, generalizing
// the [Entry] and [Logger] types.
type FieldLogger interface {
WithField(key string, value any) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
Debugf(format string, args ...any)
Infof(format string, args ...any)
Printf(format string, args ...any)
Warnf(format string, args ...any)
Warningf(format string, args ...any)
Errorf(format string, args ...any)
Fatalf(format string, args ...any)
Panicf(format string, args ...any)
Debug(args ...any)
Info(args ...any)
Print(args ...any)
Warn(args ...any)
Warning(args ...any)
Error(args ...any)
Fatal(args ...any)
Panic(args ...any)
Debugln(args ...any)
Infoln(args ...any)
Println(args ...any)
Warnln(args ...any)
Warningln(args ...any)
Errorln(args ...any)
Fatalln(args ...any)
Panicln(args ...any)
// IsDebugEnabled() bool
// IsInfoEnabled() bool
// IsWarnEnabled() bool
// IsErrorEnabled() bool
// IsFatalEnabled() bool
// IsPanicEnabled() bool
}
// Ext1FieldLogger (the first extension to [FieldLogger]) is superfluous, it is
// here for consistency. Do not use. Use [FieldLogger], [Logger] or [Entry]
// instead.
type Ext1FieldLogger interface {
FieldLogger
Tracef(format string, args ...any)
Trace(args ...any)
Traceln(args ...any)
}
================================================
FILE: logrus_test.go
================================================
package logrus_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
. "github.com/sirupsen/logrus"
. "github.com/sirupsen/logrus/internal/testutils"
)
// TestReportCaller verifies that when ReportCaller is set, the 'func' field
// is added, and when it is unset it is not set or modified
// Verify that functions within the Logrus package aren't considered when
// discovering the caller.
func TestReportCallerWhenConfigured(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.ReportCaller = false
log.Print("testNoCaller")
}, func(fields Fields) {
assert.Equal(t, "testNoCaller", fields["msg"])
assert.Equal(t, "info", fields["level"])
assert.Nil(t, fields["func"])
})
LogAndAssertJSON(t, func(log *Logger) {
log.ReportCaller = true
log.Print("testWithCaller")
}, func(fields Fields) {
assert.Equal(t, "testWithCaller", fields["msg"])
assert.Equal(t, "info", fields["level"])
assert.Equal(t,
"github.com/sirupsen/logrus_test.TestReportCallerWhenConfigured.func3", fields[FieldKeyFunc])
})
LogAndAssertJSON(t, func(log *Logger) {
log.ReportCaller = true
log.Formatter.(*JSONFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {
return "somekindoffunc", "thisisafilename"
}
log.Print("testWithCallerPrettyfier")
}, func(fields Fields) {
assert.Equal(t, "somekindoffunc", fields[FieldKeyFunc])
assert.Equal(t, "thisisafilename", fields[FieldKeyFile])
})
LogAndAssertText(t, func(log *Logger) {
log.ReportCaller = true
log.Formatter.(*TextFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {
return "somekindoffunc", "thisisafilename"
}
log.Print("testWithCallerPrettyfier")
}, func(fields map[string]string) {
assert.Equal(t, "somekindoffunc", fields[FieldKeyFunc])
assert.Equal(t, "thisisafilename", fields[FieldKeyFile])
})
}
func logSomething(t *testing.T, message string) Fields {
var buffer bytes.Buffer
var fields Fields
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
logger.ReportCaller = true
entry := logger.WithFields(Fields{
"foo": "bar",
})
entry.Info(message)
err := json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err)
return fields
}
// TestReportCallerHelperDirect - verify reference when logging from a regular function
func TestReportCallerHelperDirect(t *testing.T) {
fields := logSomething(t, "direct")
assert.Equal(t, "direct", fields["msg"])
assert.Equal(t, "info", fields["level"])
assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])
}
// TestReportCallerHelperDirect - verify reference when logging from a function called via pointer
func TestReportCallerHelperViaPointer(t *testing.T) {
fptr := logSomething
fields := fptr(t, "via pointer")
assert.Equal(t, "via pointer", fields["msg"])
assert.Equal(t, "info", fields["level"])
assert.Regexp(t, "github.com/.*/logrus_test.logSomething", fields["func"])
}
func TestPrint(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Print("test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
assert.Equal(t, "info", fields["level"])
})
}
func TestInfo(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Info("test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
assert.Equal(t, "info", fields["level"])
})
}
func TestWarn(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Warn("test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
assert.Equal(t, "warning", fields["level"])
})
}
func TestLog(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Log(WarnLevel, "test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
assert.Equal(t, "warning", fields["level"])
})
}
func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Infoln("test", "test")
}, func(fields Fields) {
assert.Equal(t, "test test", fields["msg"])
})
}
func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Infoln("test", 10)
}, func(fields Fields) {
assert.Equal(t, "test 10", fields["msg"])
})
}
func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Infoln(10, 10)
}, func(fields Fields) {
assert.Equal(t, "10 10", fields["msg"])
})
}
func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Infoln(10, 10)
}, func(fields Fields) {
assert.Equal(t, "10 10", fields["msg"])
})
}
func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Info("test", 10)
}, func(fields Fields) {
assert.Equal(t, "test10", fields["msg"])
})
}
func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.Info("test", "test")
}, func(fields Fields) {
assert.Equal(t, "testtest", fields["msg"])
})
}
func TestWithFieldsShouldAllowAssignments(t *testing.T) {
var buffer bytes.Buffer
var fields Fields
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
localLog := logger.WithFields(Fields{
"key1": "value1",
})
localLog.WithField("key2", "value2").Info("test")
err := json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err)
assert.Equal(t, "value2", fields["key2"])
assert.Equal(t, "value1", fields["key1"])
buffer = bytes.Buffer{}
fields = Fields{}
localLog.Info("test")
err = json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err)
_, ok := fields["key2"]
assert.False(t, ok)
assert.Equal(t, "value1", fields["key1"])
}
func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.WithField("msg", "hello").Info("test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
})
}
func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.WithField("msg", "hello").Info("test")
}, func(fields Fields) {
assert.Equal(t, "test", fields["msg"])
assert.Equal(t, "hello", fields["fields.msg"])
})
}
func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.WithField("time", "hello").Info("test")
}, func(fields Fields) {
assert.Equal(t, "hello", fields["fields.time"])
})
}
func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
LogAndAssertJSON(t, func(log *Logger) {
log.WithField("level", 1).Info("test")
}, func(fields Fields) {
assert.Equal(t, "info", fields["level"])
assert.InDelta(t, 1.0, fields["fields.level"], 0.0001) // JSON has floats only
})
}
func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
LogAndAssertText(t, func(log *Logger) {
ll := log.WithField("herp", "derp")
ll.Info("hello")
ll.Info("bye")
}, func(fields map[string]string) {
for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
if _, ok := fields[fieldName]; ok {
t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
}
}
})
}
func TestWithTimeShouldOverrideTime(t *testing.T) {
now := time.Now().Add(24 * time.Hour)
LogAndAssertJSON(t, func(log *Logger) {
log.WithTime(now).Info("foobar")
}, func(fields Fields) {
assert.Equal(t, fields["time"], now.Format(time.RFC3339))
})
}
func TestWithTimeShouldNotOverrideFields(t *testing.T) {
now := time.Now().Add(24 * time.Hour)
LogAndAssertJSON(t, func(log *Logger) {
log.WithField("herp", "derp").WithTime(now).Info("blah")
}, func(fields Fields) {
assert.Equal(t, now.Format(time.RFC3339), fields["time"])
assert.Equal(t, "derp", fields["herp"])
})
}
func TestWithFieldShouldNotOverrideTime(t *testing.T) {
now := time.Now().Add(24 * time.Hour)
LogAndAssertJSON(t, func(log *Logger) {
log.WithTime(now).WithField("herp", "derp").Info("blah")
}, func(fields Fields) {
assert.Equal(t, now.Format(time.RFC3339), fields["time"])
assert.Equal(t, "derp", fields["herp"])
})
}
func TestTimeOverrideMultipleLogs(t *testing.T) {
var buffer bytes.Buffer
var firstFields, secondFields Fields
logger := New()
logger.Out = &buffer
formatter := new(JSONFormatter)
formatter.TimestampFormat = time.StampMilli
logger.Formatter = formatter
llog := logger.WithField("herp", "derp")
llog.Info("foo")
err := json.Unmarshal(buffer.Bytes(), &firstFields)
require.NoError(t, err, "should have decoded first message")
buffer.Reset()
time.Sleep(10 * time.Millisecond)
llog.Info("bar")
err = json.Unmarshal(buffer.Bytes(), &secondFields)
require.NoError(t, err, "should have decoded second message")
assert.NotEqual(t, firstFields["time"], secondFields["time"], "timestamps should not be equal")
}
func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
var buffer bytes.Buffer
var fields Fields
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
llog := logger.WithField("context", "eating raw fish")
llog.Info("looks delicious")
err := json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err, "should have decoded first message")
assert.Len(t, fields, 4, "should only have msg/time/level/context fields")
assert.Equal(t, "looks delicious", fields["msg"])
assert.Equal(t, "eating raw fish", fields["context"])
buffer.Reset()
llog.Warn("omg it is!")
err = json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err, "should have decoded second message")
assert.Len(t, fields, 4, "should only have msg/time/level/context fields")
assert.Equal(t, "omg it is!", fields["msg"])
assert.Equal(t, "eating raw fish", fields["context"])
assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
}
func TestNestedLoggingReportsCorrectCaller(t *testing.T) {
var buffer bytes.Buffer
var fields Fields
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
logger.ReportCaller = true
llog := logger.WithField("context", "eating raw fish")
llog.Info("looks delicious")
_, _, line, _ := runtime.Caller(0)
err := json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err, "should have decoded first message")
assert.Len(t, fields, 6, "should have msg/time/level/func/context fields")
assert.Equal(t, "looks delicious", fields["msg"])
assert.Equal(t, "eating raw fish", fields["context"])
assert.Equal(t,
"github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])
cwd, err := os.Getwd()
require.NoError(t, err)
assert.Equal(t, filepath.ToSlash(fmt.Sprintf("%s/logrus_test.go:%d", cwd, line-1)), filepath.ToSlash(fields["file"].(string)))
buffer.Reset()
logger.WithFields(Fields{
"Clyde": "Stubblefield",
}).WithFields(Fields{
"Jab'o": "Starks",
}).WithFields(Fields{
"uri": "https://www.youtube.com/watch?v=V5DTznu-9v0",
}).WithFields(Fields{
"func": "y drummer",
}).WithFields(Fields{
"James": "Brown",
}).Print("The hardest workin' man in show business")
_, _, line, _ = runtime.Caller(0)
err = json.Unmarshal(buffer.Bytes(), &fields)
require.NoError(t, err, "should have decoded second message")
assert.Len(t, fields, 11, "should have all builtin fields plus foo,bar,baz,...")
assert.Equal(t, "Stubblefield", fields["Clyde"])
assert.Equal(t, "Starks", fields["Jab'o"])
assert.Equal(t, "https://www.youtube.com/watch?v=V5DTznu-9v0", fields["uri"])
assert.Equal(t, "y drummer", fields["fields.func"])
assert.Equal(t, "Brown", fields["James"])
assert.Equal(t, "The hardest workin' man in show business", fields["msg"])
assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
assert.Equal(t,
"github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller", fields["func"])
require.NoError(t, err)
assert.Equal(t, filepath.ToSlash(fmt.Sprintf("%s/logrus_test.go:%d", cwd, line-1)), filepath.ToSlash(fields["file"].(string)))
logger.ReportCaller = false // return to default value
}
func logLoop(iterations int, reportCaller bool) {
var buffer bytes.Buffer
logger := New()
logger.Out = &buffer
logger.Formatter = new(JSONFormatter)
logger.ReportCaller = reportCaller
for i := range iterations {
logger.Infof("round %d of %d", i, iterations)
}
}
// Assertions for upper bounds to reporting overhead
func TestCallerReportingOverhead(t *testing.T) {
iterations := 5000
before := time.Now()
logLoop(iterations, false)
during := time.Now()
logLoop(iterations, true)
after := time.Now()
elapsedNotReporting := during.Sub(before).Nanoseconds()
elapsedReporting := after.Sub(during).Nanoseconds()
maxDelta := 1 * time.Second
assert.WithinDuration(t, during, before, maxDelta,
"%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",
iterations, maxDelta.Seconds(), elapsedNotReporting)
assert.WithinDuration(t, after, during, maxDelta,
"%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)",
iterations, maxDelta.Seconds(), elapsedReporting)
}
func TestConvertLevelToString(t *testing.T) {
assert.Equal(t, "trace", TraceLevel.String())
assert.Equal(t, "debug", DebugLevel.String())
assert.Equal(t, "info", InfoLevel.String())
assert.Equal(t, "warning", WarnLevel.String())
assert.Equal(t, "error", ErrorLevel.String())
assert.Equal(t, "fatal", FatalLevel.String())
assert.Equal(t, "panic", PanicLevel.String())
}
func TestParseLevel(t *testing.T) {
l, err := ParseLevel("panic")
require.NoError(t, err)
assert.Equal(t, PanicLevel, l)
l, err = ParseLevel("PANIC")
require.NoError(t, err)
assert.Equal(t, PanicLevel, l)
l, err = ParseLevel("fatal")
require.NoError(t, err)
assert.Equal(t, FatalLevel, l)
l, err = ParseLevel("FATAL")
require.NoError(t, err)
assert.Equal(t, FatalLevel, l)
l, err = ParseLevel("error")
require.NoError(t, err)
assert.Equal(t, ErrorLevel, l)
l, err = ParseLevel("ERROR")
require.NoError(t, err)
assert.Equal(t, ErrorLevel, l)
l, err = ParseLevel("warn")
require.NoError(t, err)
assert.Equal(t, WarnLevel, l)
l, err = ParseLevel("WARN")
require.NoError(t, err)
assert.Equal(t, WarnLevel, l)
l, err = ParseLevel("warning")
require.NoError(t, err)
assert.Equal(t, WarnLevel, l)
l, err = ParseLevel("WARNING")
require.NoError(t, err)
assert.Equal(t, WarnLevel, l)
l, err = ParseLevel("info")
require.NoError(t, err)
assert.Equal(t, InfoLevel, l)
l, err = ParseLevel("INFO")
require.NoError(t, err)
assert.Equal(t, InfoLevel, l)
l, err = ParseLevel("debug")
require.NoError(t, err)
assert.Equal(t, DebugLevel, l)
l, err = ParseLevel("DEBUG")
require.NoError(t, err)
assert.Equal(t, DebugLevel, l)
l, err = ParseLevel("trace")
require.NoError(t, err)
assert.Equal(t, TraceLevel, l)
l, err = ParseLevel("TRACE")
require.NoError(t, err)
assert.Equal(t, TraceLevel, l)
_, err = ParseLevel("invalid")
assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
}
func TestLevelString(t *testing.T) {
var loggerlevel Level = 32000
_ = loggerlevel.String()
}
func TestGetSetLevelRace(t *testing.T) {
wg := sync.WaitGroup{}
for i := range 100 {
wg.Add(1)
go func(i int) {
defer wg.Done()
if i%2 == 0 {
SetLevel(InfoLevel)
} else {
GetLevel()
}
}(i)
}
wg.Wait()
}
func TestLoggingRace(t *testing.T) {
logger := New()
logger.SetOutput(io.Discard)
var wg sync.WaitGroup
wg.Add(100)
for range 100 {
go func() {
logger.Info("info")
wg.Done()
}()
}
wg.Wait()
}
func TestLoggingRaceWithHooksOnEntry(t *testing.T) {
logger := New()
logger.SetOutput(io.Discard)
hook := new(ModifyHook)
logger.AddHook(hook)
entry := logger.WithField("context", "clue")
var (
wg sync.WaitGroup
mtx sync.Mutex
start bool
)
cond := sync.NewCond(&mtx)
wg.Add(100)
for range 50 {
go func() {
cond.L.Lock()
for !start {
cond.Wait()
}
cond.L.Unlock()
for range 100 {
entry.Info("info")
}
wg.Done()
}()
}
for range 50 {
go func() {
cond.L.Lock()
for !start {
cond.Wait()
}
cond.L.Unlock()
for range 100 {
entry.WithField("another field", "with some data").Info("info")
}
wg.Done()
}()
}
cond.L.Lock()
start = true
cond.L.Unlock()
cond.Broadcast()
wg.Wait()
}
func TestReplaceHooks(t *testing.T) {
old, cur := &TestHook{}, &TestHook{}
logger := New()
logger.SetOutput(io.Discard)
logger.AddHook(old)
hooks := make(LevelHooks)
hooks.Add(cur)
replaced := logger.ReplaceHooks(hooks)
logger.Info("test")
assert.False(t, old.Fired)
assert.True(t, cur.Fired)
logger.ReplaceHooks(replaced)
logger.Info("test")
assert.True(t, old.Fired)
}
// Compile test
func TestLogrusInterfaces(t *testing.T) {
var buffer bytes.Buffer
// This verifies FieldLogger and Ext1FieldLogger work as designed.
// Please don't use them. Use Logger and Entry directly.
fn := func(xl Ext1FieldLogger) {
var l FieldLogger = xl
b := l.WithField("key", "value")
b.Debug("Test")
}
// test logger
logger := New()
logger.Out = &buffer
fn(logger)
// test Entry
e := logger.WithField("another", "value")
fn(e)
}
// Implements io.Writer using channels for synchronization, so we can wait on
// the Entry.Writer goroutine to write in a non-racey way. This does assume that
// there is a single call to Logger.Out for each message.
type channelWriter chan []byte
func (cw channelWriter) Write(p []byte) (int, error) {
cw <- p
return len(p), nil
}
func TestEntryWriter(t *testing.T) {
cw := channelWriter(make(chan []byte, 1))
log := New()
log.Out = cw
log.Formatter = new(JSONFormatter)
_, err := log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n"))
if err != nil {
t.Error("unexecpted error", err)
}
bs := <-cw
var fields Fields
err = json.Unmarshal(bs, &fields)
require.NoError(t, err)
assert.Equal(t, "bar", fields["foo"])
assert.Equal(t, "warning", fields["level"])
}
func TestLogLevelEnabled(t *testing.T) {
log := New()
log.SetLevel(PanicLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.False(t, log.IsLevelEnabled(FatalLevel))
assert.False(t, log.IsLevelEnabled(ErrorLevel))
assert.False(t, log.IsLevelEnabled(WarnLevel))
assert.False(t, log.IsLevelEnabled(InfoLevel))
assert.False(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(FatalLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.False(t, log.IsLevelEnabled(ErrorLevel))
assert.False(t, log.IsLevelEnabled(WarnLevel))
assert.False(t, log.IsLevelEnabled(InfoLevel))
assert.False(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(ErrorLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.True(t, log.IsLevelEnabled(ErrorLevel))
assert.False(t, log.IsLevelEnabled(WarnLevel))
assert.False(t, log.IsLevelEnabled(InfoLevel))
assert.False(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(WarnLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.True(t, log.IsLevelEnabled(ErrorLevel))
assert.True(t, log.IsLevelEnabled(WarnLevel))
assert.False(t, log.IsLevelEnabled(InfoLevel))
assert.False(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(InfoLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.True(t, log.IsLevelEnabled(ErrorLevel))
assert.True(t, log.IsLevelEnabled(WarnLevel))
assert.True(t, log.IsLevelEnabled(InfoLevel))
assert.False(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(DebugLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.True(t, log.IsLevelEnabled(ErrorLevel))
assert.True(t, log.IsLevelEnabled(WarnLevel))
assert.True(t, log.IsLevelEnabled(InfoLevel))
assert.True(t, log.IsLevelEnabled(DebugLevel))
assert.False(t, log.IsLevelEnabled(TraceLevel))
log.SetLevel(TraceLevel)
assert.True(t, log.IsLevelEnabled(PanicLevel))
assert.True(t, log.IsLevelEnabled(FatalLevel))
assert.True(t, log.IsLevelEnabled(ErrorLevel))
assert.True(t, log.IsLevelEnabled(WarnLevel))
assert.True(t, log.IsLevelEnabled(InfoLevel))
assert.True(t, log.IsLevelEnabled(DebugLevel))
assert.True(t, log.IsLevelEnabled(TraceLevel))
}
func TestReportCallerOnTextFormatter(t *testing.T) {
l := New()
l.SetOutput(io.Discard)
l.Formatter.(*TextFormatter).ForceColors = true
l.Formatter.(*TextFormatter).DisableColors = false
l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
l.Formatter.(*TextFormatter).ForceColors = false
l.Formatter.(*TextFormatter).DisableColors = true
l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
}
func TestSetReportCallerRace(t *testing.T) {
l := New()
l.Out = io.Discard
l.SetReportCaller(true)
var wg sync.WaitGroup
wg.Add(100)
for range 100 {
go func() {
l.Error("Some Error")
wg.Done()
}()
}
wg.Wait()
}
================================================
FILE: terminal_check_appengine.go
================================================
//go:build appengine
package logrus
func checkIfTerminal(_ any) bool {
return true
}
================================================
FILE: terminal_check_bsd.go
================================================
//go:build darwin || dragonfly || freebsd || netbsd || openbsd || hurd
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TIOCGETA
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}
================================================
FILE: terminal_check_no_terminal.go
================================================
//go:build js || nacl || plan9 || wasi || wasip1
package logrus
func checkIfTerminal(_ any) bool {
return false
}
================================================
FILE: terminal_check_notappengine.go
================================================
//go:build !appengine && !js && !windows && !nacl && !plan9 && !wasi && !wasip1
package logrus
import (
"io"
"os"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
fd := v.Fd()
if fd > uintptr(^uint(0)>>1) {
return false
}
return isTerminal(int(fd))
default:
return false
}
}
================================================
FILE: terminal_check_solaris.go
================================================
//go:build solaris
package logrus
import (
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermio(fd, unix.TCGETA)
return err == nil
}
================================================
FILE: terminal_check_unix.go
================================================
//go:build linux || aix || zos
package logrus
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TCGETS
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}
================================================
FILE: terminal_check_windows.go
================================================
//go:build windows && !appengine
package logrus
import (
"io"
"os"
"golang.org/x/sys/windows"
)
func checkIfTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
handle := windows.Handle(v.Fd())
var mode uint32
if err := windows.GetConsoleMode(handle, &mode); err != nil {
return false
}
mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
if err := windows.SetConsoleMode(handle, mode); err != nil {
return false
}
return true
}
return false
}
================================================
FILE: text_formatter.go
================================================
package logrus
import (
"bytes"
"fmt"
"maps"
"os"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"time"
)
var baseTimestamp = time.Now()
// TextFormatter formats logs into text.
//
// Output is logfmt-like: key=value pairs separated by spaces. 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 (f *TextFormatter) isTerminal(entry *Entry) bool {
if entry == nil || entry.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
}
f.terminalInitOnce.Do(func() {
entry.Logger.mu.Lock()
out := entry.Logger.Out
entry.Logger.mu.Unlock()
f.terminal = checkIfTerminal(out)
})
return f.terminal
}
func (f *TextFormatter) isColored(isTerminal bool) bool {
if f.DisableColors {
return false
}
colored := f.ForceColors || (isTerminal && (runtime.GOOS != "windows"))
if !f.EnvironmentOverrideColors {
return colored
}
if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok {
return force != "0"
}
if os.Getenv("CLICOLOR") == "0" {
return false
}
return colored
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data))
maps.Copy(data, entry.Data)
isColored := f.isColored(f.isTerminal(entry))
caller := entry.Caller
hasCaller := caller != nil
prefixFieldClashes(data, f.FieldMap, hasCaller)
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
b := entry.Buffer
if b == nil {
b = new(bytes.Buffer)
}
if isColored {
f.printColored(b, entry, keys, data)
} else {
f.printPlain(b, entry, keys, data)
}
return b.Bytes(), nil
}
func (f *TextFormatter) printPlain(b *bytes.Buffer, entry *Entry, keys []string, data Fields) {
caller := entry.Caller
hasCaller := caller != nil
fixedKeys := make([]string, 0, len(keys)+defaultFields)
if !f.DisableTimestamp {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
}
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
if entry.Message != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
}
if entry.err != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
}
var funcVal, fileVal string
if caller != nil {
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(caller)
} else {
funcVal = caller.Function
fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10)
}
if funcVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
}
if fileVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
}
}
if !f.DisableSorting {
if f.SortingFunc == nil {
// Default sorting does not sort the "fixed keys";
// see https://github.com/sirupsen/logrus/commit/73bc94e60c753099e8bae902f81fbd6e7dd95f26
slices.Sort(keys)
fixedKeys = append(fixedKeys, keys...)
} else {
fixedKeys = append(fixedKeys, keys...)
f.SortingFunc(fixedKeys)
}
} else {
fixedKeys = append(fixedKeys, keys...)
}
for _, key := range fixedKeys {
var value any
switch {
case key == f.FieldMap.resolve(FieldKeyTime):
if f.TimestampFormat == "" {
value = entry.Time.Format(defaultTimestampFormat)
} else {
value = entry.Time.Format(f.TimestampFormat)
}
case key == f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String()
case key == f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message
case key == f.FieldMap.resolve(FieldKeyLogrusError):
value = entry.err
case key == f.FieldMap.resolve(FieldKeyFunc) && hasCaller:
value = funcVal
case key == f.FieldMap.resolve(FieldKeyFile) && hasCaller:
value = fileVal
default:
value = data[key]
}
f.appendKeyValue(b, key, value)
}
b.WriteByte('\n')
}
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data 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
entry.Message = strings.TrimSuffix(entry.Message, "\n")
var callerText string
if caller := entry.Caller; caller != nil {
var funcVal, fileVal string
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(caller)
} else {
if caller.Function != "" {
funcVal = caller.Function + "()"
}
fileVal = caller.File + ":" + strconv.FormatInt(int64(caller.Line), 10)
}
if fileVal == "" {
callerText = funcVal
} else if funcVal == "" {
callerText = fileVal
} else {
callerText = fileVal + " " + funcVal
}
}
levelText := levelPrefix(entry.Level, f.DisableLevelTruncation, f.PadLevelText)
switch {
case f.DisableTimestamp:
_, _ = fmt.Fprintf(b, "%s%s %-44s ", levelText, callerText, entry.Message)
case !f.FullTimestamp:
_, _ = fmt.Fprintf(b, "%s[%04d]%s %-44s ", levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), callerText, entry.Message)
default:
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
_, _ = fmt.Fprintf(b, "%s[%s]%s %-44s ", levelText, entry.Time.Format(timestampFormat), callerText, entry.Message)
}
if !f.DisableSorting {
if f.SortingFunc == nil {
slices.Sort(keys)
} else {
f.SortingFunc(keys)
}
}
// Keys use the same color as the level-prefix.
for _, k := range keys {
b.WriteByte(' ')
b.WriteString(colorize(entry.Level, k))
b.WriteByte('=')
f.appendValue(b, data[k])
}
b.WriteByte('\n')
}
// appendKeyValue writes key=value. Keys are written verbatim (unquoted/unescaped);
// values are subject to quoting/escaping.
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value any) {
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(key)
b.WriteByte('=')
f.appendValue(b, value)
}
func (f *TextFormatter) appendValue(b *bytes.Buffer, value any) {
// Fast paths.
switch v := value.(type) {
case string:
f.appendString(b, v)
return
case []byte:
f.appendBytes(b, v)
return
case bool:
var raw [8]byte
f.appendBytes(b, strconv.AppendBool(raw[:0], v))
return
case error:
f.appendString(b, v.Error())
return
case fmt.Stringer:
f.appendString(b, v.String())
return
}
// Handle common primitives.
var raw [64]byte
var num []byte
switch v := value.(type) {
case int:
num = strconv.AppendInt(raw[:0], int64(v), 10)
case int8:
num = strconv.AppendInt(raw[:0], int64(v), 10)
case int16:
num = strconv.AppendInt(raw[:0], int64(v), 10)
case int32:
num = strconv.AppendInt(raw[:0], int64(v), 10)
case int64:
num = strconv.AppendInt(raw[:0], v, 10)
case uint:
num = strconv.AppendUint(raw[:0], uint64(v), 10)
case uint8:
num = strconv.AppendUint(raw[:0], uint64(v), 10)
case uint16:
num = strconv.AppendUint(raw[:0], uint64(v), 10)
case uint32:
num = strconv.AppendUint(raw[:0], uint64(v), 10)
case uint64:
num = strconv.AppendUint(raw[:0], v, 10)
case uintptr:
num = strconv.AppendUint(raw[:0], uint64(v), 10)
case float32:
num = strconv.AppendFloat(raw[:0], float64(v), 'g', -1, 32)
case float64:
num = strconv.AppendFloat(raw[:0], v, 'g', -1, 64)
default:
f.appendString(b, fmt.Sprint(value))
return
}
f.appendNumeric(b, num)
}
func (f *TextFormatter) appendString(b *bytes.Buffer, s string) {
quote := f.ForceQuote || (f.QuoteEmptyFields && len(s) == 0) || (!f.DisableQuote && needsQuoting(s))
if !quote {
b.WriteString(s)
return
}
if len(s) == 0 {
b.WriteString(`""`)
return
}
var tmp [128]byte
b.Write(strconv.AppendQuote(tmp[:0], s))
}
func (f *TextFormatter) appendBytes(b *bytes.Buffer, bs []byte) {
quote := f.ForceQuote || (f.QuoteEmptyFields && len(bs) == 0) || (!f.DisableQuote && needsQuotingBytes(bs))
if !quote {
b.Write(bs)
return
}
if len(bs) == 0 {
b.WriteString(`""`)
return
}
var tmp [128]byte
b.Write(strconv.AppendQuote(tmp[:0], string(bs)))
}
func (f *TextFormatter) appendNumeric(b *bytes.Buffer, out []byte) {
if f.ForceQuote {
var tmp [128]byte
b.Write(strconv.AppendQuote(tmp[:0], string(out)))
return
}
b.Write(out)
}
// 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(s string) bool {
// use an index loop (avoid rune decoding).
for i := range len(s) {
c := s[i]
if !isSafeByte(c) {
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(bs []byte) bool {
for _, c := range bs {
if !isSafeByte(c) {
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(ch byte) bool {
ok := ch < 0x80 && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
if ok {
return true
}
switch ch {
case '-', '.', '_', '/', '@', '^', '+':
return true
default:
return false
}
}
================================================
FILE: text_formatter_test.go
================================================
package logrus
import (
"bytes"
"errors"
"fmt"
"os"
"runtime"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFormatting(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
testCases := []struct {
value string
expected string
}{
{`foo`, "time=\"0001-01-01T00:00:00Z\" level=panic test=foo\n"},
}
for _, tc := range testCases {
b, _ := tf.Format(WithField("test", tc.value))
if string(b) != tc.expected {
t.Errorf("formatting expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}
func TestQuoting(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
checkQuoting := func(q bool, value any) {
b, _ := tf.Format(WithField("test", value))
_, after, _ := bytes.Cut(b, ([]byte)("test="))
cont := bytes.Contains(after, []byte("\""))
if cont != q {
if q {
t.Errorf("quoting expected for: %#v", value)
} else {
t.Errorf("quoting not expected for: %#v", value)
}
}
}
checkQuoting(false, "")
checkQuoting(false, "abcd")
checkQuoting(false, "v1.0")
checkQuoting(false, "1234567890")
checkQuoting(false, "/foobar")
checkQuoting(false, "foo_bar")
checkQuoting(false, "foo@bar")
checkQuoting(false, "foobar^")
checkQuoting(false, "+/-_^@f.oobar")
checkQuoting(true, "foo\n\rbar")
checkQuoting(true, "foobar$")
checkQuoting(true, "&foobar")
checkQuoting(true, "x y")
checkQuoting(true, "x,y")
// New/explicit: bool fast path (never needs quoting unless forced).
checkQuoting(false, true)
checkQuoting(false, false)
// New/explicit: numeric fast path (never needs quoting unless forced).
checkQuoting(false, 0)
checkQuoting(false, int64(-123))
checkQuoting(false, uint64(123))
checkQuoting(false, float64(3.14))
// New/explicit: []byte fast path.
checkQuoting(false, []byte("abcd"))
checkQuoting(true, []byte("x y"))
// Error path (string fast path via Error()).
checkQuoting(false, errors.New("invalid"))
checkQuoting(true, errors.New("invalid argument"))
// Test for quoting empty fields.
tf.QuoteEmptyFields = true
checkQuoting(true, "")
checkQuoting(false, "abcd")
checkQuoting(true, "foo\n\rbar")
checkQuoting(true, errors.New("invalid argument"))
// New/explicit: QuoteEmptyFields shouldn't affect non-empty primitives.
checkQuoting(false, 0)
checkQuoting(false, true)
checkQuoting(false, []byte("abcd"))
// Test forcing quotes.
tf.ForceQuote = true
checkQuoting(true, "")
checkQuoting(true, "abcd")
checkQuoting(true, "foo\n\rbar")
checkQuoting(true, errors.New("invalid argument"))
// New/explicit: ForceQuote should quote numeric/bool/[]byte too.
checkQuoting(true, 0)
checkQuoting(true, true)
checkQuoting(true, []byte("abcd"))
// Test forcing quotes when also disabling them.
tf.DisableQuote = true
checkQuoting(true, "")
checkQuoting(true, "abcd")
checkQuoting(true, "foo\n\rbar")
checkQuoting(true, errors.New("invalid argument"))
// Test disabling quotes
tf.ForceQuote = false
tf.QuoteEmptyFields = false
checkQuoting(false, "")
checkQuoting(false, "abcd")
checkQuoting(false, "foo\n\rbar")
checkQuoting(false, errors.New("invalid argument"))
// New/explicit: DisableQuote should keep primitives unquoted.
checkQuoting(false, 0)
checkQuoting(false, true)
checkQuoting(false, []byte("x y"))
}
func TestEscaping(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
testCases := []struct {
value string
expected string
}{
{`ba"r`, `ba\"r`},
{`ba'r`, `ba'r`},
}
for _, tc := range testCases {
b, _ := tf.Format(WithField("test", tc.value))
if !bytes.Contains(b, []byte(tc.expected)) {
t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}
func Te
gitextract_3g0yan4k/ ├── .github/ │ └── workflows/ │ └── ci.yaml ├── .gitignore ├── .golangci.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── alt_exit.go ├── alt_exit_test.go ├── appveyor.yml ├── buffer_pool.go ├── doc.go ├── entry.go ├── entry_bench_test.go ├── entry_test.go ├── example_basic_test.go ├── example_custom_caller_test.go ├── example_default_field_value_test.go ├── example_function_test.go ├── example_global_hook_test.go ├── example_hook_test.go ├── exported.go ├── formatter.go ├── formatter_bench_test.go ├── go.mod ├── go.sum ├── hook_test.go ├── hooks/ │ ├── slog/ │ │ ├── slog.go │ │ └── slog_test.go │ ├── syslog/ │ │ ├── README.md │ │ ├── syslog.go │ │ └── syslog_test.go │ ├── test/ │ │ ├── test.go │ │ └── test_test.go │ └── writer/ │ ├── README.md │ ├── writer.go │ └── writer_test.go ├── hooks.go ├── internal/ │ └── testutils/ │ └── testutils.go ├── json_formatter.go ├── json_formatter_test.go ├── level.go ├── level_test.go ├── logger.go ├── logger_bench_test.go ├── logger_test.go ├── logrus.go ├── logrus_test.go ├── terminal_check_appengine.go ├── terminal_check_bsd.go ├── terminal_check_no_terminal.go ├── terminal_check_notappengine.go ├── terminal_check_solaris.go ├── terminal_check_unix.go ├── terminal_check_windows.go ├── text_formatter.go ├── text_formatter_test.go ├── writer.go └── writer_test.go
SYMBOL INDEX (490 symbols across 46 files)
FILE: alt_exit.go
function runHandler (line 32) | func runHandler(handler func()) {
function runHandlers (line 42) | func runHandlers() {
function Exit (line 49) | func Exit(code int) {
function RegisterExitHandler (line 62) | func RegisterExitHandler(handler func()) {
function DeferExitHandler (line 74) | func DeferExitHandler(handler func()) {
FILE: alt_exit_test.go
function TestRegister (line 17) | func TestRegister(t *testing.T) {
function TestDefer (line 41) | func TestDefer(t *testing.T) {
function TestHandler (line 65) | func TestHandler(t *testing.T) {
function appendLine (line 94) | func appendLine(path, s string) {
function assertFileContent (line 107) | func assertFileContent(t *testing.T, path, want string, childOut []byte) {
constant tokenPrefix (line 120) | tokenPrefix = "reexectest-"
function argv0Token (line 123) | func argv0Token(t *testing.T, name string) string {
function reexecTest (line 130) | func reexecTest(t *testing.T, name string, f func(t *testing.T)) bool {
function reexecCommand (line 152) | func reexecCommand(t *testing.T, name string, args ...string) *exec.Cmd {
FILE: buffer_pool.go
type BufferPool (line 16) | type BufferPool interface
type defaultPool (line 21) | type defaultPool struct
method Put (line 25) | func (p *defaultPool) Put(buf *bytes.Buffer) {
method Get (line 29) | func (p *defaultPool) Get() *bytes.Buffer {
function SetBufferPool (line 35) | func SetBufferPool(bp BufferPool) {
FILE: entry.go
constant maximumCallerDepth (line 31) | maximumCallerDepth int = 25
constant knownLogrusFrames (line 32) | knownLogrusFrames int = 4
type Entry (line 52) | type Entry struct
method Dup (line 106) | func (entry *Entry) Dup() *Entry {
method Bytes (line 117) | func (entry *Entry) Bytes() ([]byte, error) {
method String (line 136) | func (entry *Entry) String() (string, error) {
method WithError (line 147) | func (entry *Entry) WithError(err error) *Entry {
method WithContext (line 164) | func (entry *Entry) WithContext(ctx context.Context) *Entry {
method WithField (line 175) | func (entry *Entry) WithField(key string, value any) *Entry {
method WithFields (line 180) | func (entry *Entry) WithFields(fields Fields) *Entry {
method WithTime (line 207) | func (entry *Entry) WithTime(t time.Time) *Entry {
method HasCaller (line 275) | func (entry Entry) HasCaller() bool {
method log (line 279) | func (entry *Entry) log(level Level, msg string) {
method getBufferPool (line 324) | func (entry *Entry) getBufferPool() (pool BufferPool) {
method fireHooks (line 331) | func (entry *Entry) fireHooks(hooks []Hook) {
method write (line 340) | func (entry *Entry) write() {
method Log (line 366) | func (entry *Entry) Log(level Level, args ...any) {
method Trace (line 372) | func (entry *Entry) Trace(args ...any) {
method Debug (line 376) | func (entry *Entry) Debug(args ...any) {
method Print (line 380) | func (entry *Entry) Print(args ...any) {
method Info (line 384) | func (entry *Entry) Info(args ...any) {
method Warn (line 388) | func (entry *Entry) Warn(args ...any) {
method Warning (line 392) | func (entry *Entry) Warning(args ...any) {
method Error (line 396) | func (entry *Entry) Error(args ...any) {
method Fatal (line 400) | func (entry *Entry) Fatal(args ...any) {
method Panic (line 405) | func (entry *Entry) Panic(args ...any) {
method Logf (line 411) | func (entry *Entry) Logf(level Level, format string, args ...any) {
method Tracef (line 417) | func (entry *Entry) Tracef(format string, args ...any) {
method Debugf (line 421) | func (entry *Entry) Debugf(format string, args ...any) {
method Infof (line 425) | func (entry *Entry) Infof(format string, args ...any) {
method Printf (line 429) | func (entry *Entry) Printf(format string, args ...any) {
method Warnf (line 433) | func (entry *Entry) Warnf(format string, args ...any) {
method Warningf (line 437) | func (entry *Entry) Warningf(format string, args ...any) {
method Errorf (line 441) | func (entry *Entry) Errorf(format string, args ...any) {
method Fatalf (line 445) | func (entry *Entry) Fatalf(format string, args ...any) {
method Panicf (line 450) | func (entry *Entry) Panicf(format string, args ...any) {
method Logln (line 456) | func (entry *Entry) Logln(level Level, args ...any) {
method Traceln (line 462) | func (entry *Entry) Traceln(args ...any) {
method Debugln (line 466) | func (entry *Entry) Debugln(args ...any) {
method Infoln (line 470) | func (entry *Entry) Infoln(args ...any) {
method Println (line 474) | func (entry *Entry) Println(args ...any) {
method Warnln (line 478) | func (entry *Entry) Warnln(args ...any) {
method Warningln (line 482) | func (entry *Entry) Warningln(args ...any) {
method Errorln (line 486) | func (entry *Entry) Errorln(args ...any) {
method Fatalln (line 490) | func (entry *Entry) Fatalln(args ...any) {
method Panicln (line 495) | func (entry *Entry) Panicln(args ...any) {
method sprintlnn (line 503) | func (entry *Entry) sprintlnn(args ...any) string {
function NewEntry (line 93) | func NewEntry(logger *Logger) *Entry {
function getPackageName (line 219) | func getPackageName(f string) string {
function getCaller (line 234) | func getCaller() *runtime.Frame {
FILE: entry_bench_test.go
function BenchmarkEntry_WithError (line 11) | func BenchmarkEntry_WithError(b *testing.B) {
function BenchmarkEntry_WithField_Chain (line 22) | func BenchmarkEntry_WithField_Chain(b *testing.B) {
function BenchmarkEntry_WithFields (line 40) | func BenchmarkEntry_WithFields(b *testing.B) {
function benchmarkEntryInfo (line 88) | func benchmarkEntryInfo(b *testing.B, reportCaller bool) {
function BenchmarkEntry_ReportCaller_NoCaller (line 110) | func BenchmarkEntry_ReportCaller_NoCaller(b *testing.B) { benchmarkEnt...
function BenchmarkEntry_ReportCaller_WithCaller (line 111) | func BenchmarkEntry_ReportCaller_WithCaller(b *testing.B) { benchmarkEnt...
function caller4 (line 114) | func caller4(entry *logrus.Entry) { caller3(entry) }
function caller3 (line 117) | func caller3(entry *logrus.Entry) { caller2(entry) }
function caller2 (line 120) | func caller2(entry *logrus.Entry) { caller1(entry) }
function caller1 (line 123) | func caller1(entry *logrus.Entry) { entry.Info("test message") }
function benchmarkEntryReportCallerDepth4 (line 129) | func benchmarkEntryReportCallerDepth4(b *testing.B, reportCaller bool) {
function BenchmarkEntry_ReportCaller_NoCaller_Depth4 (line 151) | func BenchmarkEntry_ReportCaller_NoCaller_Depth4(b *testing.B) {
function BenchmarkEntry_ReportCaller_WithCaller_Depth4 (line 155) | func BenchmarkEntry_ReportCaller_WithCaller_Depth4(b *testing.B) {
FILE: entry_test.go
type contextKeyType (line 18) | type contextKeyType
function TestEntryWithError (line 20) | func TestEntryWithError(t *testing.T) {
function TestEntryWithContext (line 39) | func TestEntryWithContext(t *testing.T) {
function TestEntryWithContextCopiesData (line 53) | func TestEntryWithContextCopiesData(t *testing.T) {
function TestEntryWithTimeCopiesData (line 96) | func TestEntryWithTimeCopiesData(t *testing.T) {
function TestEntryPanicln (line 131) | func TestEntryPanicln(t *testing.T) {
function TestEntryPanicf (line 153) | func TestEntryPanicf(t *testing.T) {
function TestEntryPanic (line 175) | func TestEntryPanic(t *testing.T) {
constant badMessage (line 198) | badMessage = "this is going to panic"
constant panicMessage (line 199) | panicMessage = "this is broken"
type panickyHook (line 202) | type panickyHook struct
method Levels (line 204) | func (p *panickyHook) Levels() []logrus.Level {
method Fire (line 208) | func (p *panickyHook) Fire(entry *logrus.Entry) error {
function TestEntryHooksPanic (line 216) | func TestEntryHooksPanic(t *testing.T) {
function TestEntryWithIncorrectField (line 235) | func TestEntryWithIncorrectField(t *testing.T) {
function getErr (line 261) | func getErr(t *testing.T, e *logrus.Entry) string {
function TestEntryLogfLevel (line 274) | func TestEntryLogfLevel(t *testing.T) {
function TestEntryLoggerMutationRace (line 288) | func TestEntryLoggerMutationRace(t *testing.T) {
type noopHook (line 316) | type noopHook struct
method Levels (line 318) | func (noopHook) Levels() []logrus.Level { return logrus.AllLevels }
method Fire (line 319) | func (noopHook) Fire(*logrus.Entry) error { return nil }
type nopBufferPool (line 321) | type nopBufferPool struct
method Get (line 323) | func (nopBufferPool) Get() *bytes.Buffer { return new(bytes.Buffer) }
method Put (line 324) | func (nopBufferPool) Put(*bytes.Buffer) {}
function runEntryLoggerRace (line 326) | func runEntryLoggerRace(t *testing.T, mutate func(logger *logrus.Logger)) {
type reentrantValue (line 371) | type reentrantValue struct
method MarshalJSON (line 375) | func (r reentrantValue) MarshalJSON() ([]byte, error) {
function TestEntryReentrantLoggingDeadlock (line 383) | func TestEntryReentrantLoggingDeadlock(t *testing.T) {
FILE: example_basic_test.go
function Example_basic (line 9) | func Example_basic() {
FILE: example_custom_caller_test.go
function ExampleJSONFormatter_CallerPrettyfier (line 12) | func ExampleJSONFormatter_CallerPrettyfier() {
FILE: example_default_field_value_test.go
type DefaultFieldHook (line 9) | type DefaultFieldHook struct
method Levels (line 13) | func (h *DefaultFieldHook) Levels() []logrus.Level {
method Fire (line 17) | func (h *DefaultFieldHook) Fire(e *logrus.Entry) error {
function ExampleDefaultFieldHook (line 22) | func ExampleDefaultFieldHook() {
FILE: example_function_test.go
function TestLogger_LogFn (line 11) | func TestLogger_LogFn(t *testing.T) {
FILE: example_global_hook_test.go
type GlobalHook (line 11) | type GlobalHook struct
method Levels (line 13) | func (h *GlobalHook) Levels() []logrus.Level {
method Fire (line 17) | func (h *GlobalHook) Fire(e *logrus.Entry) error {
function ExampleGlobalHook (line 22) | func ExampleGlobalHook() {
FILE: example_hook_test.go
function Example_hook (line 14) | func Example_hook() {
FILE: exported.go
function StandardLogger (line 13) | func StandardLogger() *Logger {
function SetOutput (line 18) | func SetOutput(out io.Writer) {
function SetFormatter (line 23) | func SetFormatter(formatter Formatter) {
function SetReportCaller (line 29) | func SetReportCaller(include bool) {
function SetLevel (line 34) | func SetLevel(level Level) {
function GetLevel (line 39) | func GetLevel() Level {
function IsLevelEnabled (line 44) | func IsLevelEnabled(level Level) bool {
function AddHook (line 49) | func AddHook(hook Hook) {
function WithError (line 54) | func WithError(err error) *Entry {
function WithContext (line 59) | func WithContext(ctx context.Context) *Entry {
function WithField (line 68) | func WithField(key string, value any) *Entry {
function WithFields (line 78) | func WithFields(fields Fields) *Entry {
function WithTime (line 87) | func WithTime(t time.Time) *Entry {
function Trace (line 92) | func Trace(args ...any) {
function Debug (line 97) | func Debug(args ...any) {
function Print (line 102) | func Print(args ...any) {
function Info (line 107) | func Info(args ...any) {
function Warn (line 112) | func Warn(args ...any) {
function Warning (line 117) | func Warning(args ...any) {
function Error (line 122) | func Error(args ...any) {
function Panic (line 127) | func Panic(args ...any) {
function Fatal (line 132) | func Fatal(args ...any) {
function TraceFn (line 137) | func TraceFn(fn LogFunction) {
function DebugFn (line 142) | func DebugFn(fn LogFunction) {
function PrintFn (line 147) | func PrintFn(fn LogFunction) {
function InfoFn (line 152) | func InfoFn(fn LogFunction) {
function WarnFn (line 157) | func WarnFn(fn LogFunction) {
function WarningFn (line 162) | func WarningFn(fn LogFunction) {
function ErrorFn (line 167) | func ErrorFn(fn LogFunction) {
function PanicFn (line 172) | func PanicFn(fn LogFunction) {
function FatalFn (line 177) | func FatalFn(fn LogFunction) {
function Tracef (line 182) | func Tracef(format string, args ...any) {
function Debugf (line 187) | func Debugf(format string, args ...any) {
function Printf (line 192) | func Printf(format string, args ...any) {
function Infof (line 197) | func Infof(format string, args ...any) {
function Warnf (line 202) | func Warnf(format string, args ...any) {
function Warningf (line 207) | func Warningf(format string, args ...any) {
function Errorf (line 212) | func Errorf(format string, args ...any) {
function Panicf (line 217) | func Panicf(format string, args ...any) {
function Fatalf (line 222) | func Fatalf(format string, args ...any) {
function Traceln (line 227) | func Traceln(args ...any) {
function Debugln (line 232) | func Debugln(args ...any) {
function Println (line 237) | func Println(args ...any) {
function Infoln (line 242) | func Infoln(args ...any) {
function Warnln (line 247) | func Warnln(args ...any) {
function Warningln (line 252) | func Warningln(args ...any) {
function Errorln (line 257) | func Errorln(args ...any) {
function Panicln (line 262) | func Panicln(args ...any) {
function Fatalln (line 267) | func Fatalln(args ...any) {
FILE: formatter.go
constant defaultTimestampFormat (line 9) | defaultTimestampFormat = time.RFC3339
constant defaultFields (line 16) | defaultFields = 3
constant FieldKeyMsg (line 21) | FieldKeyMsg = "msg"
constant FieldKeyLevel (line 22) | FieldKeyLevel = "level"
constant FieldKeyTime (line 23) | FieldKeyTime = "time"
constant FieldKeyLogrusError (line 24) | FieldKeyLogrusError = "logrus_error"
constant FieldKeyFunc (line 25) | FieldKeyFunc = "func"
constant FieldKeyFile (line 26) | FieldKeyFile = "file"
type Formatter (line 39) | type Formatter interface
function prefixFieldClashes (line 55) | func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller boo...
FILE: formatter_bench_test.go
type benchStringer (line 11) | type benchStringer
method String (line 13) | func (s benchStringer) String() string { return string(s) }
function BenchmarkZeroTextFormatter (line 87) | func BenchmarkZeroTextFormatter(b *testing.B) {
function BenchmarkOneStringTextFormatter (line 91) | func BenchmarkOneStringTextFormatter(b *testing.B) {
function BenchmarkOneNumericTextFormatter (line 95) | func BenchmarkOneNumericTextFormatter(b *testing.B) {
function BenchmarkOneBoolTextFormatter (line 99) | func BenchmarkOneBoolTextFormatter(b *testing.B) {
function BenchmarkNumericTextFormatter (line 103) | func BenchmarkNumericTextFormatter(b *testing.B) {
function BenchmarkBoolTextFormatter (line 107) | func BenchmarkBoolTextFormatter(b *testing.B) {
function BenchmarkStringerTextFormatter (line 111) | func BenchmarkStringerTextFormatter(b *testing.B) {
function BenchmarkErrorTextFormatter (line 115) | func BenchmarkErrorTextFormatter(b *testing.B) {
function BenchmarkSmallTextFormatter (line 119) | func BenchmarkSmallTextFormatter(b *testing.B) {
function BenchmarkLargeTextFormatter (line 123) | func BenchmarkLargeTextFormatter(b *testing.B) {
function BenchmarkSmallColoredTextFormatter (line 127) | func BenchmarkSmallColoredTextFormatter(b *testing.B) {
function BenchmarkLargeColoredTextFormatter (line 131) | func BenchmarkLargeColoredTextFormatter(b *testing.B) {
function BenchmarkSmallJSONFormatter (line 135) | func BenchmarkSmallJSONFormatter(b *testing.B) {
function BenchmarkLargeJSONFormatter (line 139) | func BenchmarkLargeJSONFormatter(b *testing.B) {
function doBenchmark (line 145) | func doBenchmark(b *testing.B, formatter logrus.Formatter, fields logrus...
FILE: hook_test.go
type RecordingFormatter (line 25) | type RecordingFormatter struct
method Format (line 30) | func (f *RecordingFormatter) Format(entry *Entry) ([]byte, error) {
type TestHook (line 36) | type TestHook struct
method Fire (line 40) | func (hook *TestHook) Fire(entry *Entry) error {
method Levels (line 45) | func (hook *TestHook) Levels() []Level {
function TestHookFires (line 57) | func TestHookFires(t *testing.T) {
type ModifyHook (line 70) | type ModifyHook struct
method Fire (line 74) | func (hook *ModifyHook) Fire(entry *Entry) error {
method Levels (line 80) | func (hook *ModifyHook) Levels() []Level {
function TestHookCanModifyEntry (line 92) | func TestHookCanModifyEntry(t *testing.T) {
function TestCanFireMultipleHooks (line 103) | func TestCanFireMultipleHooks(t *testing.T) {
type SingleLevelModifyHook (line 118) | type SingleLevelModifyHook struct
method Levels (line 122) | func (h *SingleLevelModifyHook) Levels() []Level {
function TestHookEntryIsPristine (line 130) | func TestHookEntryIsPristine(t *testing.T) {
type ErrorHook (line 157) | type ErrorHook struct
method Fire (line 161) | func (hook *ErrorHook) Fire(entry *Entry) error {
method Levels (line 166) | func (hook *ErrorHook) Levels() []Level {
function TestErrorHookShouldntFireOnInfo (line 172) | func TestErrorHookShouldntFireOnInfo(t *testing.T) {
function TestErrorHookShouldFireOnError (line 183) | func TestErrorHookShouldFireOnError(t *testing.T) {
function TestAddHookRace (line 194) | func TestAddHookRace(t *testing.T) {
function TestAddHookRace2 (line 215) | func TestAddHookRace2(t *testing.T) {
type HookCallFunc (line 237) | type HookCallFunc struct
method Levels (line 241) | func (h *HookCallFunc) Levels() []Level {
method Fire (line 245) | func (h *HookCallFunc) Fire(e *Entry) error {
function TestHookFireOrder (line 250) | func TestHookFireOrder(t *testing.T) {
FILE: hooks.go
type Hook (line 8) | type Hook interface
type LevelHooks (line 14) | type LevelHooks
method Add (line 18) | func (hooks LevelHooks) Add(hook Hook) {
method Fire (line 26) | func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
FILE: hooks/slog/slog.go
type LevelMapper (line 15) | type LevelMapper
type SlogHook (line 18) | type SlogHook struct
method toSlogLevel (line 45) | func (h *SlogHook) toSlogLevel(level logrus.Level) slog.Leveler {
method Levels (line 66) | func (h *SlogHook) Levels() []logrus.Level {
method Fire (line 74) | func (h *SlogHook) Fire(entry *logrus.Entry) error {
function NewSlogHook (line 36) | func NewSlogHook(logger *slog.Logger) *SlogHook {
FILE: hooks/slog/slog_test.go
function TestSlogHook (line 18) | func TestSlogHook(t *testing.T) {
type errorHandler (line 93) | type errorHandler struct
method Enabled (line 97) | func (h *errorHandler) Enabled(context.Context, slog.Level) bool {
method Handle (line 101) | func (h *errorHandler) Handle(context.Context, slog.Record) error {
method WithAttrs (line 105) | func (h *errorHandler) WithAttrs([]slog.Attr) slog.Handler {
method WithGroup (line 109) | func (h *errorHandler) WithGroup(string) slog.Handler {
function TestSlogHook_error_propagates (line 113) | func TestSlogHook_error_propagates(t *testing.T) {
function TestSlogHook_source (line 140) | func TestSlogHook_source(t *testing.T) {
FILE: hooks/syslog/syslog.go
type SyslogHook (line 14) | type SyslogHook struct
method Fire (line 35) | func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
method Levels (line 60) | func (hook *SyslogHook) Levels() []logrus.Level {
function NewSyslogHook (line 30) | func NewSyslogHook(network, raddr string, priority syslog.Priority, tag ...
FILE: hooks/syslog/syslog_test.go
function TestLocalhostAddAndPrint (line 14) | func TestLocalhostAddAndPrint(t *testing.T) {
FILE: hooks/test/test.go
type Hook (line 13) | type Hook struct
method Fire (line 47) | func (t *Hook) Fire(e *logrus.Entry) error {
method Levels (line 54) | func (t *Hook) Levels() []logrus.Level {
method LastEntry (line 59) | func (t *Hook) LastEntry() *logrus.Entry {
method AllEntries (line 70) | func (t *Hook) AllEntries() []*logrus.Entry {
method Reset (line 83) | func (t *Hook) Reset() {
function NewGlobal (line 24) | func NewGlobal() *Hook {
function NewLocal (line 32) | func NewLocal(logger *logrus.Logger) *Hook {
function NewNullLogger (line 40) | func NewNullLogger() (*logrus.Logger, *Hook) {
FILE: hooks/test/test_test.go
function TestAllHooks (line 15) | func TestAllHooks(t *testing.T) {
function TestLoggingWithHooksRace (line 53) | func TestLoggingWithHooksRace(t *testing.T) {
function TestFatalWithAlternateExit (line 86) | func TestFatalWithAlternateExit(t *testing.T) {
function TestNewLocal (line 98) | func TestNewLocal(t *testing.T) {
FILE: hooks/writer/writer.go
type Hook (line 10) | type Hook struct
method Fire (line 19) | func (hook *Hook) Fire(entry *logrus.Entry) error {
method Levels (line 29) | func (hook *Hook) Levels() []logrus.Level {
FILE: hooks/writer/writer_test.go
function TestDifferentLevelsGoToDifferentWriters (line 13) | func TestDifferentLevelsGoToDifferentWriters(t *testing.T) {
FILE: internal/testutils/testutils.go
function LogAndAssertJSON (line 15) | func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(f...
function LogAndAssertText (line 31) | func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(f...
FILE: json_formatter.go
type fieldKey (line 11) | type fieldKey
type FieldMap (line 14) | type FieldMap
method resolve (line 16) | func (f FieldMap) resolve(key fieldKey) string {
type JSONFormatter (line 25) | type JSONFormatter struct
method Format (line 64) | func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
FILE: json_formatter_test.go
function TestErrorNotLost (line 15) | func TestErrorNotLost(t *testing.T) {
function TestErrorNotLostOnFieldNotNamedError (line 34) | func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
function TestFieldClashWithTime (line 53) | func TestFieldClashWithTime(t *testing.T) {
function TestFieldClashWithMsg (line 76) | func TestFieldClashWithMsg(t *testing.T) {
function TestFieldClashWithLevel (line 95) | func TestFieldClashWithLevel(t *testing.T) {
function TestFieldClashWithRemappedFields (line 114) | func TestFieldClashWithRemappedFields(t *testing.T) {
function TestFieldsInNestedDictionary (line 168) | func TestFieldsInNestedDictionary(t *testing.T) {
function TestJSONEntryFieldValueError (line 210) | func TestJSONEntryFieldValueError(t *testing.T) {
function TestJSONEntryEndsWithNewline (line 287) | func TestJSONEntryEndsWithNewline(t *testing.T) {
function TestJSONMessageKey (line 300) | func TestJSONMessageKey(t *testing.T) {
function TestJSONLevelKey (line 317) | func TestJSONLevelKey(t *testing.T) {
function TestJSONTimeKey (line 334) | func TestJSONTimeKey(t *testing.T) {
function TestFieldDoesNotClashWithCaller (line 351) | func TestFieldDoesNotClashWithCaller(t *testing.T) {
function TestFieldClashWithCaller (line 371) | func TestFieldClashWithCaller(t *testing.T) {
function TestJSONDisableTimestamp (line 401) | func TestJSONDisableTimestamp(t *testing.T) {
function TestJSONEnableTimestamp (line 416) | func TestJSONEnableTimestamp(t *testing.T) {
function TestJSONDisableHTMLEscape (line 429) | func TestJSONDisableHTMLEscape(t *testing.T) {
function TestJSONEnableHTMLEscape (line 442) | func TestJSONEnableHTMLEscape(t *testing.T) {
FILE: level.go
constant ansiReset (line 9) | ansiReset = "\x1b[0m"
constant ansiRed (line 10) | ansiRed = "\x1b[31m"
constant ansiYellow (line 11) | ansiYellow = "\x1b[33m"
constant ansiCyan (line 12) | ansiCyan = "\x1b[36m"
constant ansiWhite (line 13) | ansiWhite = "\x1b[37m"
type lvlPrefix (line 16) | type lvlPrefix struct
function colorize (line 22) | func colorize(level Level, s string) string {
function formatLevel (line 37) | func formatLevel(level Level, disableTrunc, pad bool, maxLen int) string {
function levelPrefix (line 82) | func levelPrefix(level Level, disableTrunc, pad bool) string {
FILE: level_test.go
function TestLevelJsonEncoding (line 12) | func TestLevelJsonEncoding(t *testing.T) {
function TestLevelUnmarshalText (line 27) | func TestLevelUnmarshalText(t *testing.T) {
function TestLevelMarshalText (line 40) | func TestLevelMarshalText(t *testing.T) {
FILE: logger.go
type LogFunction (line 15) | type LogFunction
type Logger (line 17) | type Logger struct
method newEntry (line 102) | func (logger *Logger) newEntry() *Entry {
method releaseEntry (line 110) | func (logger *Logger) releaseEntry(entry *Entry) {
method WithField (line 119) | func (logger *Logger) WithField(key string, value any) *Entry {
method WithFields (line 127) | func (logger *Logger) WithFields(fields Fields) *Entry {
method WithError (line 135) | func (logger *Logger) WithError(err error) *Entry {
method WithContext (line 142) | func (logger *Logger) WithContext(ctx context.Context) *Entry {
method WithTime (line 149) | func (logger *Logger) WithTime(t time.Time) *Entry {
method Logf (line 155) | func (logger *Logger) Logf(level Level, format string, args ...any) {
method Tracef (line 163) | func (logger *Logger) Tracef(format string, args ...any) {
method Debugf (line 167) | func (logger *Logger) Debugf(format string, args ...any) {
method Infof (line 171) | func (logger *Logger) Infof(format string, args ...any) {
method Printf (line 175) | func (logger *Logger) Printf(format string, args ...any) {
method Warnf (line 181) | func (logger *Logger) Warnf(format string, args ...any) {
method Warningf (line 185) | func (logger *Logger) Warningf(format string, args ...any) {
method Errorf (line 189) | func (logger *Logger) Errorf(format string, args ...any) {
method Fatalf (line 193) | func (logger *Logger) Fatalf(format string, args ...any) {
method Panicf (line 198) | func (logger *Logger) Panicf(format string, args ...any) {
method Log (line 205) | func (logger *Logger) Log(level Level, args ...any) {
method LogFn (line 213) | func (logger *Logger) LogFn(level Level, fn LogFunction) {
method Trace (line 221) | func (logger *Logger) Trace(args ...any) {
method Debug (line 225) | func (logger *Logger) Debug(args ...any) {
method Info (line 229) | func (logger *Logger) Info(args ...any) {
method Print (line 233) | func (logger *Logger) Print(args ...any) {
method Warn (line 239) | func (logger *Logger) Warn(args ...any) {
method Warning (line 243) | func (logger *Logger) Warning(args ...any) {
method Error (line 247) | func (logger *Logger) Error(args ...any) {
method Fatal (line 251) | func (logger *Logger) Fatal(args ...any) {
method Panic (line 256) | func (logger *Logger) Panic(args ...any) {
method TraceFn (line 260) | func (logger *Logger) TraceFn(fn LogFunction) {
method DebugFn (line 264) | func (logger *Logger) DebugFn(fn LogFunction) {
method InfoFn (line 268) | func (logger *Logger) InfoFn(fn LogFunction) {
method PrintFn (line 272) | func (logger *Logger) PrintFn(fn LogFunction) {
method WarnFn (line 278) | func (logger *Logger) WarnFn(fn LogFunction) {
method WarningFn (line 282) | func (logger *Logger) WarningFn(fn LogFunction) {
method ErrorFn (line 286) | func (logger *Logger) ErrorFn(fn LogFunction) {
method FatalFn (line 290) | func (logger *Logger) FatalFn(fn LogFunction) {
method PanicFn (line 295) | func (logger *Logger) PanicFn(fn LogFunction) {
method Logln (line 299) | func (logger *Logger) Logln(level Level, args ...any) {
method Traceln (line 307) | func (logger *Logger) Traceln(args ...any) {
method Debugln (line 311) | func (logger *Logger) Debugln(args ...any) {
method Infoln (line 315) | func (logger *Logger) Infoln(args ...any) {
method Println (line 319) | func (logger *Logger) Println(args ...any) {
method Warnln (line 325) | func (logger *Logger) Warnln(args ...any) {
method Warningln (line 329) | func (logger *Logger) Warningln(args ...any) {
method Errorln (line 333) | func (logger *Logger) Errorln(args ...any) {
method Fatalln (line 337) | func (logger *Logger) Fatalln(args ...any) {
method Panicln (line 342) | func (logger *Logger) Panicln(args ...any) {
method Exit (line 346) | func (logger *Logger) Exit(code int) {
method SetNoLock (line 357) | func (logger *Logger) SetNoLock() {
method level (line 361) | func (logger *Logger) level() Level {
method SetLevel (line 366) | func (logger *Logger) SetLevel(level Level) {
method GetLevel (line 371) | func (logger *Logger) GetLevel() Level {
method AddHook (line 376) | func (logger *Logger) AddHook(hook Hook) {
method hooksForLevel (line 384) | func (logger *Logger) hooksForLevel(level Level) []Hook {
method IsLevelEnabled (line 398) | func (logger *Logger) IsLevelEnabled(level Level) bool {
method SetFormatter (line 403) | func (logger *Logger) SetFormatter(formatter Formatter) {
method SetOutput (line 410) | func (logger *Logger) SetOutput(output io.Writer) {
method SetReportCaller (line 416) | func (logger *Logger) SetReportCaller(reportCaller bool) {
method ReplaceHooks (line 423) | func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
method SetBufferPool (line 432) | func (logger *Logger) SetBufferPool(pool BufferPool) {
type MutexWrap (line 58) | type MutexWrap struct
method Lock (line 63) | func (mw *MutexWrap) Lock() {
method Unlock (line 69) | func (mw *MutexWrap) Unlock() {
method Disable (line 75) | func (mw *MutexWrap) Disable() {
function New (line 91) | func New() *Logger {
FILE: logger_bench_test.go
function BenchmarkDummyLogger (line 11) | func BenchmarkDummyLogger(b *testing.B) {
function BenchmarkDummyLoggerNoLock (line 20) | func BenchmarkDummyLoggerNoLock(b *testing.B) {
function doLoggerBenchmark (line 29) | func doLoggerBenchmark(b *testing.B, out *os.File, formatter logrus.Form...
function doLoggerBenchmarkNoLock (line 44) | func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter logru...
function BenchmarkLoggerJSONFormatter (line 60) | func BenchmarkLoggerJSONFormatter(b *testing.B) {
function BenchmarkLoggerTextFormatter (line 64) | func BenchmarkLoggerTextFormatter(b *testing.B) {
function doLoggerBenchmarkWithFormatter (line 68) | func doLoggerBenchmarkWithFormatter(b *testing.B, f logrus.Formatter) {
FILE: logger_test.go
function TestWarningAndWarninglnFormatting (line 12) | func TestWarningAndWarninglnFormatting(t *testing.T) {
type testBufferPool (line 35) | type testBufferPool struct
method Get (line 40) | func (p *testBufferPool) Get() *bytes.Buffer {
method Put (line 45) | func (p *testBufferPool) Put(buf *bytes.Buffer) {
function TestLogger_SetBufferPool (line 49) | func TestLogger_SetBufferPool(t *testing.T) {
FILE: logrus.go
type Fields (line 10) | type Fields
type Level (line 15) | type Level
method String (line 18) | func (level Level) String() string {
method UnmarshalText (line 67) | func (level *Level) UnmarshalText(text []byte) error {
method MarshalText (line 78) | func (level Level) MarshalText() ([]byte, error) {
function ParseLevel (line 40) | func ParseLevel(lvl string) (Level, error) {
function parseLevel (line 44) | func parseLevel(b []byte) (Level, error) {
constant PanicLevel (line 103) | PanicLevel Level = iota
constant FatalLevel (line 106) | FatalLevel
constant ErrorLevel (line 109) | ErrorLevel
constant WarnLevel (line 111) | WarnLevel
constant InfoLevel (line 114) | InfoLevel
constant DebugLevel (line 116) | DebugLevel
constant TraceLevel (line 118) | TraceLevel
type StdLogger (line 131) | type StdLogger interface
type FieldLogger (line 147) | type FieldLogger interface
type Ext1FieldLogger (line 190) | type Ext1FieldLogger interface
FILE: logrus_test.go
function TestReportCallerWhenConfigured (line 26) | func TestReportCallerWhenConfigured(t *testing.T) {
function logSomething (line 69) | func logSomething(t *testing.T, message string) Fields {
function TestReportCallerHelperDirect (line 91) | func TestReportCallerHelperDirect(t *testing.T) {
function TestReportCallerHelperViaPointer (line 100) | func TestReportCallerHelperViaPointer(t *testing.T) {
function TestPrint (line 109) | func TestPrint(t *testing.T) {
function TestInfo (line 118) | func TestInfo(t *testing.T) {
function TestWarn (line 127) | func TestWarn(t *testing.T) {
function TestLog (line 136) | func TestLog(t *testing.T) {
function TestInfolnShouldAddSpacesBetweenStrings (line 145) | func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
function TestInfolnShouldAddSpacesBetweenStringAndNonstring (line 153) | func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
function TestInfolnShouldAddSpacesBetweenTwoNonStrings (line 161) | func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
function TestInfoShouldAddSpacesBetweenTwoNonStrings (line 169) | func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
function TestInfoShouldNotAddSpacesBetweenStringAndNonstring (line 177) | func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
function TestInfoShouldNotAddSpacesBetweenStrings (line 185) | func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
function TestWithFieldsShouldAllowAssignments (line 193) | func TestWithFieldsShouldAllowAssignments(t *testing.T) {
function TestUserSuppliedFieldDoesNotOverwriteDefaults (line 223) | func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
function TestUserSuppliedMsgFieldHasPrefix (line 231) | func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
function TestUserSuppliedTimeFieldHasPrefix (line 240) | func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
function TestUserSuppliedLevelFieldHasPrefix (line 248) | func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
function TestDefaultFieldsAreNotPrefixed (line 257) | func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
function TestWithTimeShouldOverrideTime (line 271) | func TestWithTimeShouldOverrideTime(t *testing.T) {
function TestWithTimeShouldNotOverrideFields (line 281) | func TestWithTimeShouldNotOverrideFields(t *testing.T) {
function TestWithFieldShouldNotOverrideTime (line 292) | func TestWithFieldShouldNotOverrideTime(t *testing.T) {
function TestTimeOverrideMultipleLogs (line 303) | func TestTimeOverrideMultipleLogs(t *testing.T) {
function TestDoubleLoggingDoesntPrefixPreviousFields (line 330) | func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
function TestNestedLoggingReportsCorrectCaller (line 360) | func TestNestedLoggingReportsCorrectCaller(t *testing.T) {
function logLoop (line 418) | func logLoop(iterations int, reportCaller bool) {
function TestCallerReportingOverhead (line 432) | func TestCallerReportingOverhead(t *testing.T) {
function TestConvertLevelToString (line 452) | func TestConvertLevelToString(t *testing.T) {
function TestParseLevel (line 462) | func TestParseLevel(t *testing.T) {
function TestLevelString (line 531) | func TestLevelString(t *testing.T) {
function TestGetSetLevelRace (line 537) | func TestGetSetLevelRace(t *testing.T) {
function TestLoggingRace (line 554) | func TestLoggingRace(t *testing.T) {
function TestLoggingRaceWithHooksOnEntry (line 570) | func TestLoggingRaceWithHooksOnEntry(t *testing.T) {
function TestReplaceHooks (line 622) | func TestReplaceHooks(t *testing.T) {
function TestLogrusInterfaces (line 644) | func TestLogrusInterfaces(t *testing.T) {
type channelWriter (line 666) | type channelWriter
method Write (line 668) | func (cw channelWriter) Write(p []byte) (int, error) {
function TestEntryWriter (line 673) | func TestEntryWriter(t *testing.T) {
function TestLogLevelEnabled (line 691) | func TestLogLevelEnabled(t *testing.T) {
function TestReportCallerOnTextFormatter (line 757) | func TestReportCallerOnTextFormatter(t *testing.T) {
function TestSetReportCallerRace (line 770) | func TestSetReportCallerRace(t *testing.T) {
FILE: terminal_check_appengine.go
function checkIfTerminal (line 5) | func checkIfTerminal(_ any) bool {
FILE: terminal_check_bsd.go
constant ioctlReadTermios (line 7) | ioctlReadTermios = unix.TIOCGETA
function isTerminal (line 9) | func isTerminal(fd int) bool {
FILE: terminal_check_no_terminal.go
function checkIfTerminal (line 5) | func checkIfTerminal(_ any) bool {
FILE: terminal_check_notappengine.go
function checkIfTerminal (line 10) | func checkIfTerminal(w io.Writer) bool {
FILE: terminal_check_solaris.go
function isTerminal (line 10) | func isTerminal(fd int) bool {
FILE: terminal_check_unix.go
constant ioctlReadTermios (line 7) | ioctlReadTermios = unix.TCGETS
function isTerminal (line 9) | func isTerminal(fd int) bool {
FILE: terminal_check_windows.go
function checkIfTerminal (line 12) | func checkIfTerminal(w io.Writer) bool {
FILE: text_formatter.go
type TextFormatter (line 27) | type TextFormatter struct
method isTerminal (line 104) | func (f *TextFormatter) isTerminal(entry *Entry) bool {
method isColored (line 123) | func (f *TextFormatter) isColored(isTerminal bool) bool {
method Format (line 142) | func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
method printPlain (line 169) | func (f *TextFormatter) printPlain(b *bytes.Buffer, entry *Entry, keys...
method printColored (line 244) | func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, ke...
method appendKeyValue (line 305) | func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, va...
method appendValue (line 314) | func (f *TextFormatter) appendValue(b *bytes.Buffer, value any) {
method appendString (line 377) | func (f *TextFormatter) appendString(b *bytes.Buffer, s string) {
method appendBytes (line 392) | func (f *TextFormatter) appendBytes(b *bytes.Buffer, bs []byte) {
method appendNumeric (line 407) | func (f *TextFormatter) appendNumeric(b *bytes.Buffer, out []byte) {
function needsQuoting (line 419) | func needsQuoting(s string) bool {
function needsQuotingBytes (line 433) | func needsQuotingBytes(bs []byte) bool {
function isSafeByte (line 444) | func isSafeByte(ch byte) bool {
FILE: text_formatter_test.go
function TestFormatting (line 19) | func TestFormatting(t *testing.T) {
function TestQuoting (line 38) | func TestQuoting(t *testing.T) {
function TestEscaping (line 132) | func TestEscaping(t *testing.T) {
function TestEscaping_Interface (line 151) | func TestEscaping_Interface(t *testing.T) {
function TestTimestampFormat (line 172) | func TestTimestampFormat(t *testing.T) {
function TestDisableLevelTruncation (line 193) | func TestDisableLevelTruncation(t *testing.T) {
function TestPadLevelText (line 235) | func TestPadLevelText(t *testing.T) {
function TestDisableTimestampWithColoredOutput (line 321) | func TestDisableTimestampWithColoredOutput(t *testing.T) {
function TestNewlineBehavior (line 330) | func TestNewlineBehavior(t *testing.T) {
function TestTextFormatterFieldMap (line 353) | func TestTextFormatterFieldMap(t *testing.T) {
function TestTextFormatterIsColored (line 392) | func TestTextFormatterIsColored(t *testing.T) {
function unsetEnv (line 528) | func unsetEnv(t *testing.T, env string) {
function TestCustomSorting (line 539) | func TestCustomSorting(t *testing.T) {
function TestCustomSorting_FirstFormat (line 575) | func TestCustomSorting_FirstFormat(t *testing.T) {
function TestTextEntryFieldValueError (line 626) | func TestTextEntryFieldValueError(t *testing.T) {
FILE: writer.go
method Writer (line 11) | func (logger *Logger) Writer() *io.PipeWriter {
method WriterLevel (line 20) | func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
method Writer (line 25) | func (entry *Entry) Writer() *io.PipeWriter {
method WriterLevel (line 30) | func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
method writerScanner (line 64) | func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(...
function writerFinalizer (line 98) | func writerFinalizer(writer *io.PipeWriter) {
FILE: writer_test.go
function ExampleLogger_Writer_httpServer (line 19) | func ExampleLogger_Writer_httpServer() {
function ExampleLogger_Writer_stdlib (line 35) | func ExampleLogger_Writer_stdlib() {
type bufferWithMu (line 45) | type bufferWithMu struct
method Write (line 50) | func (b *bufferWithMu) Write(p []byte) (int, error) {
method Read (line 56) | func (b *bufferWithMu) Read(p []byte) (int, error) {
method String (line 62) | func (b *bufferWithMu) String() string {
function TestWriterSplitNewlines (line 68) | func TestWriterSplitNewlines(t *testing.T) {
function TestWriterSplitsMax64KB (line 95) | func TestWriterSplitsMax64KB(t *testing.T) {
Condensed preview — 58 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (236K chars).
[
{
"path": ".github/workflows/ci.yaml",
"chars": 1809,
"preview": "name: CI\n\n# Default to 'contents: read', which grants actions to read commits.\n#\n# If any permission is set, any permiss"
},
{
"path": ".gitignore",
"chars": 22,
"preview": "logrus\nvendor\n\n.idea/\n"
},
{
"path": ".golangci.yml",
"chars": 682,
"preview": "version: \"2\"\nlinters:\n enable:\n - asasalint\n - asciicheck\n - bidichk\n - contextcheck\n - durationcheck\n "
},
{
"path": "CHANGELOG.md",
"chars": 8566,
"preview": "# 1.9.4\n\nFixes:\n * Remove uses of deprecated `ioutil` package\n\nFeatures:\n * Add GNU/Hurd support\n * Add WASI wasip1 s"
},
{
"path": "LICENSE",
"chars": 1082,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2014 Simon Eskildsen\n\nPermission is hereby granted, free of charge, to any person o"
},
{
"path": "README.md",
"chars": 19848,
"preview": "# Logrus <img src=\"http://i.imgur.com/hTeVwmJ.png\" width=\"40\" height=\"40\" alt=\":walrus:\" class=\"emoji\" title=\":walrus:\"/"
},
{
"path": "alt_exit.go",
"chars": 2802,
"preview": "package logrus\n\n// The following code was sourced and modified from the\n// https://github.com/tebeka/atexit package gove"
},
{
"path": "alt_exit_test.go",
"chars": 4595,
"preview": "package logrus_test\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"s"
},
{
"path": "appveyor.yml",
"chars": 197,
"preview": "# Minimal stub to satisfy AppVeyor CI\nversion: 1.0.{build}\nplatform: x64\nshallow_clone: true\n\nbranches:\n only:\n - ma"
},
{
"path": "buffer_pool.go",
"chars": 613,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bufferPool BufferPool = &defaultPool{\n\tpool: &sync.Pool{\n\t\tNew: func() "
},
{
"path": "doc.go",
"chars": 565,
"preview": "/*\nPackage logrus is a structured logger for Go, completely API compatible with the standard library logger.\n\nThe simple"
},
{
"path": "entry.go",
"chars": 13452,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"maps\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nva"
},
{
"path": "entry_bench_test.go",
"chars": 3962,
"preview": "package logrus_test\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc BenchmarkEntry_WithError"
},
{
"path": "entry_test.go",
"chars": 11176,
"preview": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com"
},
{
"path": "example_basic_test.go",
"chars": 2284,
"preview": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc Example_basic() {\n\tlog := logrus.New()\n\tlog.F"
},
{
"path": "example_custom_caller_test.go",
"chars": 680,
"preview": "package logrus_test\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc ExampleJSONForm"
},
{
"path": "example_default_field_value_test.go",
"chars": 671,
"preview": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype DefaultFieldHook struct {\n\tGetValue func() st"
},
{
"path": "example_function_test.go",
"chars": 524,
"preview": "package logrus_test\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nf"
},
{
"path": "example_global_hook_test.go",
"chars": 684,
"preview": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar mystring string\n\ntype GlobalHook struct{}\n\nfun"
},
{
"path": "example_hook_test.go",
"chars": 1213,
"preview": "//go:build !windows\n\npackage logrus_test\n\nimport (\n\t\"log/syslog\"\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n\tslhooks \"github.c"
},
{
"path": "exported.go",
"chars": 7053,
"preview": "package logrus\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"time\"\n)\n\n// std is the package-level standard logger, similar to the default"
},
{
"path": "formatter.go",
"chars": 2895,
"preview": "package logrus\n\nimport \"time\"\n\nconst (\n\t// defaultTimestampFormat is the layout used to format entry timestamps\n\t// when"
},
{
"path": "formatter_bench_test.go",
"chars": 4094,
"preview": "package logrus_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype benchStringer string\n\nfun"
},
{
"path": "go.mod",
"chars": 266,
"preview": "module github.com/sirupsen/logrus\n\ngo 1.23\n\nrequire (\n\tgithub.com/stretchr/testify v1.10.0\n\tgolang.org/x/sys v0.13.0\n)\n\n"
},
{
"path": "go.sum",
"chars": 1036,
"preview": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.m"
},
{
"path": "hook_test.go",
"chars": 5702,
"preview": "package logrus_test\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"maps\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/asse"
},
{
"path": "hooks/slog/slog.go",
"chars": 2645,
"preview": "package slog\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// LevelMapper maps a [logrus.Level] to "
},
{
"path": "hooks/slog/slog_test.go",
"chars": 3698,
"preview": "package slog_test\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"git"
},
{
"path": "hooks/syslog/README.md",
"chars": 2000,
"preview": "# Syslog Hooks for Logrus <img src=\"http://i.imgur.com/hTeVwmJ.png\" width=\"40\" height=\"40\" alt=\":walrus:\" class=\"emoji\" "
},
{
"path": "hooks/syslog/syslog.go",
"chars": 1411,
"preview": "//go:build !windows && !nacl && !plan9\n\npackage syslog\n\nimport (\n\t\"fmt\"\n\t\"log/syslog\"\n\t\"os\"\n\n\t\"github.com/sirupsen/logru"
},
{
"path": "hooks/syslog/syslog_test.go",
"chars": 669,
"preview": "//go:build !windows && !nacl && !plan9\n\npackage syslog_test\n\nimport (\n\t\"io\"\n\t\"log/syslog\"\n\t\"testing\"\n\n\t\"github.com/sirup"
},
{
"path": "hooks/test/test.go",
"chars": 1967,
"preview": "// Package test is used for testing logrus.\n// It provides a simple hooks which register logged messages.\npackage test\n\n"
},
{
"path": "hooks/test/test_test.go",
"chars": 2591,
"preview": "package test_test\n\nimport (\n\t\"io\"\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/si"
},
{
"path": "hooks/writer/README.md",
"chars": 896,
"preview": "# Writer Hooks for Logrus\n\nSend logs of given levels to any object with `io.Writer` interface.\n\n## Usage\n\nIf you want fo"
},
{
"path": "hooks/writer/writer.go",
"chars": 689,
"preview": "package writer\n\nimport (\n\t\"io\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// Hook is a hook that writes logs of specified LogLeve"
},
{
"path": "hooks/writer/writer_test.go",
"chars": 857,
"preview": "package writer_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/sirupsen/logrus/hook"
},
{
"path": "hooks.go",
"chars": 1136,
"preview": "package logrus\n\n// Hook describes hooks to be fired when logging on the logging levels returned from\n// [Hook.Levels] on"
},
{
"path": "internal/testutils/testutils.go",
"chars": 1161,
"preview": "package testutils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t. \"github.com/sirupsen/logrus\" "
},
{
"path": "json_formatter.go",
"chars": 3481,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype fieldKey string\n\n// FieldMap all"
},
{
"path": "json_formatter_test.go",
"chars": 11785,
"preview": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/"
},
{
"path": "level.go",
"chars": 2009,
"preview": "package logrus\n\nimport (\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tansiReset = \"\\x1b[0m\" // reset attributes\n\tansiRed = \"\\x1b["
},
{
"path": "level_test.go",
"chars": 1265,
"preview": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/"
},
{
"path": "logger.go",
"chars": 11016,
"preview": "package logrus\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n// LogFunction For big messages, it ca"
},
{
"path": "logger_bench_test.go",
"chars": 1910,
"preview": "package logrus_test\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc BenchmarkDummyLogger(b *test"
},
{
"path": "logger_test.go",
"chars": 1296,
"preview": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/ass"
},
{
"path": "logrus.go",
"chars": 4926,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n// Fields type, used to pass to [WithFields].\ntype Fields map[string]"
},
{
"path": "logrus_test.go",
"chars": 21377,
"preview": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"sync\"\n\t\"testing"
},
{
"path": "terminal_check_appengine.go",
"chars": 88,
"preview": "//go:build appengine\n\npackage logrus\n\nfunc checkIfTerminal(_ any) bool {\n\treturn true\n}\n"
},
{
"path": "terminal_check_bsd.go",
"chars": 266,
"preview": "//go:build darwin || dragonfly || freebsd || netbsd || openbsd || hurd\n\npackage logrus\n\nimport \"golang.org/x/sys/unix\"\n\n"
},
{
"path": "terminal_check_no_terminal.go",
"chars": 117,
"preview": "//go:build js || nacl || plan9 || wasi || wasip1\n\npackage logrus\n\nfunc checkIfTerminal(_ any) bool {\n\treturn false\n}\n"
},
{
"path": "terminal_check_notappengine.go",
"chars": 329,
"preview": "//go:build !appengine && !js && !windows && !nacl && !plan9 && !wasi && !wasip1\n\npackage logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n"
},
{
"path": "terminal_check_solaris.go",
"chars": 244,
"preview": "//go:build solaris\n\npackage logrus\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\n// IsTerminal returns true if the given file de"
},
{
"path": "terminal_check_unix.go",
"chars": 224,
"preview": "//go:build linux || aix || zos\n\npackage logrus\n\nimport \"golang.org/x/sys/unix\"\n\nconst ioctlReadTermios = unix.TCGETS\n\nfu"
},
{
"path": "terminal_check_windows.go",
"chars": 490,
"preview": "//go:build windows && !appengine\n\npackage logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\nfunc checkIfTermi"
},
{
"path": "text_formatter.go",
"chars": 12182,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"maps\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar"
},
{
"path": "text_formatter_test.go",
"chars": 19854,
"preview": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"g"
},
{
"path": "writer.go",
"chars": 3138,
"preview": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n// Writer at INFO level. See WriterLevel for details.\nf"
},
{
"path": "writer_test.go",
"chars": 2928,
"preview": "package logrus_test\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/s"
}
]
About this extraction
This page contains the full source code of the sirupsen/logrus GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 58 files (210.1 KB), approximately 59.6k tokens, and a symbol index with 490 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.