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 `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 :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](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): ![Colored](http://i.imgur.com/PY7qMwd.png) 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 . // // 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=" 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=" 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 :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 TestEscaping_Interface(t *testing.T) { tf := &TextFormatter{DisableColors: true} ts := time.Now() testCases := []struct { value any expected string }{ {ts, fmt.Sprintf("\"%s\"", ts.String())}, {errors.New("error: something went wrong"), "\"error: something went wrong\""}, } 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 TestTimestampFormat(t *testing.T) { checkTimeStr := func(format string) { customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} customStr, _ := customFormatter.Format(WithField("test", "test")) timeStart := bytes.Index(customStr, ([]byte)("time=")) timeEnd := bytes.Index(customStr, ([]byte)("level=")) timeStr := customStr[timeStart+5+len("\"") : timeEnd-1-len("\"")] if format == "" { format = time.RFC3339 } _, e := time.Parse(format, (string)(timeStr)) if e != nil { t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) } } checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") checkTimeStr("Mon Jan _2 15:04:05 2006") checkTimeStr("") } func TestDisableLevelTruncation(t *testing.T) { entry := &Entry{ Time: time.Now(), Message: "testing", } checkDisableTruncation := func(disabled bool, level Level) { tf := &TextFormatter{ DisableLevelTruncation: disabled, ForceColors: true, DisableTimestamp: true, } entry.Level = level out, err := tf.Format(entry) if err != nil { t.Errorf("error formatting log entry: %s", err) } logLine := string(out) if disabled { expected := strings.ToUpper(level.String()) if !strings.Contains(logLine, expected) { t.Errorf("level string expected to be %s when truncation disabled", expected) } } else { expected := strings.ToUpper(level.String()) if len(level.String()) > 4 { if strings.Contains(logLine, expected) { t.Errorf("level string %s expected to be truncated to %s when truncation is enabled", expected, expected[0:4]) } } else { if !strings.Contains(logLine, expected) { t.Errorf("level string expected to be %s when truncation is enabled and level string is below truncation threshold", expected) } } } } checkDisableTruncation(true, DebugLevel) checkDisableTruncation(true, InfoLevel) checkDisableTruncation(false, ErrorLevel) checkDisableTruncation(false, InfoLevel) } func TestPadLevelText(t *testing.T) { // A note for future maintainers / committers: // // This test denormalizes the level text as a part of its assertions. // Because of that, its not really a "unit test" of the PadLevelText functionality. // So! Many apologies to the potential future person who has to rewrite this test // when they are changing some completely unrelated functionality. params := []struct { name string level Level paddedLevelText string }{ { name: "PanicLevel", level: PanicLevel, paddedLevelText: "PANIC ", // 2 extra spaces }, { name: "FatalLevel", level: FatalLevel, paddedLevelText: "FATAL ", // 2 extra spaces }, { name: "ErrorLevel", level: ErrorLevel, paddedLevelText: "ERROR ", // 2 extra spaces }, { name: "WarnLevel", level: WarnLevel, // WARNING is already the max length, so we don't need to assert a paddedLevelText }, { name: "DebugLevel", level: DebugLevel, paddedLevelText: "DEBUG ", // 2 extra spaces }, { name: "TraceLevel", level: TraceLevel, paddedLevelText: "TRACE ", // 2 extra spaces }, { name: "InfoLevel", level: InfoLevel, paddedLevelText: "INFO ", // 3 extra spaces }, } // We create a "default" TextFormatter to do a control test. // We also create a TextFormatter with PadLevelText, which is the parameter we want to do our most relevant assertions against. tfDefault := TextFormatter{ForceColors: true} tfWithPadding := TextFormatter{ForceColors: true, PadLevelText: true} for _, val := range params { t.Run(val.name, func(t *testing.T) { out, err := tfDefault.Format(&Entry{Level: val.level}) if err != nil { t.Errorf("error formatting log entry: %s", err) } logLineDefault := string(out) out, err = tfWithPadding.Format(&Entry{Level: val.level}) if err != nil { t.Errorf("error formatting log entry: %s", err) } logLineWithPadding := string(out) // Control: the level text should not be padded by default if val.paddedLevelText != "" && strings.Contains(logLineDefault, val.paddedLevelText) { t.Errorf("log line %q should not contain the padded level text %q by default", logLineDefault, val.paddedLevelText) } // Assertion: the level text should still contain the string representation of the level if !strings.Contains(strings.ToLower(logLineWithPadding), val.level.String()) { t.Errorf("log line %q should contain the level text %q when padding is enabled", logLineWithPadding, val.level.String()) } // Assertion: the level text should be in its padded form now if val.paddedLevelText != "" && !strings.Contains(logLineWithPadding, val.paddedLevelText) { t.Errorf("log line %q should contain the padded level text %q when padding is enabled", logLineWithPadding, val.paddedLevelText) } }) } } func TestDisableTimestampWithColoredOutput(t *testing.T) { tf := &TextFormatter{DisableTimestamp: true, ForceColors: true} b, _ := tf.Format(WithField("test", "test")) if strings.Contains(string(b), "[0000]") { t.Error("timestamp not expected when DisableTimestamp is true") } } func TestNewlineBehavior(t *testing.T) { tf := &TextFormatter{ForceColors: true} // Ensure a single new line is removed as per stdlib log e := NewEntry(StandardLogger()) e.Message = "test message\n" b, _ := tf.Format(e) if bytes.Contains(b, []byte("test message\n")) { t.Error("first newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected newline to be removed.") } // Ensure a double new line is reduced to a single new line e = NewEntry(StandardLogger()) e.Message = "test message\n\n" b, _ = tf.Format(e) if bytes.Contains(b, []byte("test message\n\n")) { t.Error("Double newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected single newline") } if !bytes.Contains(b, []byte("test message\n")) { t.Error("Double newline at end of Entry.Message did not result in a single newline after formatting") } } func TestTextFormatterFieldMap(t *testing.T) { formatter := &TextFormatter{ DisableColors: true, FieldMap: FieldMap{ FieldKeyMsg: "message", FieldKeyLevel: "somelevel", FieldKeyTime: "timeywimey", }, } entry := &Entry{ Message: "oh hi", Level: WarnLevel, Time: time.Date(1981, time.February, 24, 4, 28, 3, 100, time.UTC), Data: Fields{ "field1": "f1", "message": "messagefield", "somelevel": "levelfield", "timeywimey": "timeywimeyfield", }, } b, err := formatter.Format(entry) if err != nil { t.Fatal("Unable to format entry: ", err) } assert.Equal(t, `timeywimey="1981-02-24T04:28:03Z" `+ `somelevel=warning `+ `message="oh hi" `+ `field1=f1 `+ `fields.message=messagefield `+ `fields.somelevel=levelfield `+ `fields.timeywimey=timeywimeyfield`+"\n", string(b), "Formatted output doesn't respect FieldMap") } func TestTextFormatterIsColored(t *testing.T) { tests := []struct { name string expected bool isTerminal bool disableColor bool forceColors bool envVars []string }{ { // Default values name: "default", }, { // Output on terminal name: "tty", expected: true, isTerminal: true, }, { // Output on terminal with color disabled name: "tty,DisableColors=1", expected: false, isTerminal: true, disableColor: true, }, { // Output not on terminal with color disabled name: "DisableColors=1", expected: false, disableColor: true, }, { // Output not on terminal with color forced name: "ForceColors=1", expected: true, forceColors: true, }, { // Output on terminal with clicolor set to "0" name: "tty,CLICOLOR=0", expected: false, isTerminal: true, envVars: []string{"CLICOLOR=0"}, }, { // Output on terminal with clicolor set to "1" name: "tty,CLICOLOR=1", expected: true, isTerminal: true, envVars: []string{"CLICOLOR=1"}, }, { // Output not on terminal with clicolor set to "0" name: "CLICOLOR=0", expected: false, envVars: []string{"CLICOLOR=0"}, }, { // Output not on terminal with clicolor set to "1" name: "CLICOLOR=1", expected: false, envVars: []string{"CLICOLOR=1"}, }, { // Output not on terminal with clicolor set to "1" and force color name: "ForceColors=1,CLICOLOR=1", expected: true, forceColors: true, envVars: []string{"CLICOLOR=1"}, }, { // Output not on terminal with clicolor set to "0" and force color name: "ForceColors=1,CLICOLOR=0", expected: false, forceColors: true, envVars: []string{"CLICOLOR=0"}, }, { // Output not on terminal with clicolor_force set to "1" name: "CLICOLOR_FORCE=1", expected: true, envVars: []string{"CLICOLOR_FORCE=1"}, }, { // Output not on terminal with clicolor_force set to "0" name: "CLICOLOR_FORCE=0", expected: false, envVars: []string{"CLICOLOR_FORCE=0"}, }, { // Output on terminal with clicolor_force set to "0" name: "tty,CLICOLOR_FORCE=0", expected: false, isTerminal: true, envVars: []string{"CLICOLOR_FORCE=0"}, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { // Unset existing vars to prevent them from interfering with the test. unsetEnv(t, "CLICOLOR") unsetEnv(t, "CLICOLOR_FORCE") for _, envVar := range tc.envVars { k, v, _ := strings.Cut(envVar, "=") t.Setenv(k, v) } tf := TextFormatter{ DisableColors: tc.disableColor, ForceColors: tc.forceColors, EnvironmentOverrideColors: len(tc.envVars) > 0, } expected := tc.expected if runtime.GOOS == "windows" && !tc.forceColors && os.Getenv("CLICOLOR_FORCE") == "" { // On Windows, without ForceColors or CLICOLOR_FORCE, colors are disabled. expected = false } // TODO(thaJeztah): need a way to mock "isTerminal" and check "isColored" for testing // without depending on non-exported methods and fields. res := tf.isColored(tc.isTerminal) // tc.isTerminal avoids depending on a real TTY assert.Equal(t, expected, res) }) } } // unsetEnv calls [os.Unsetenv] to unset an environment // variable if it is set, and uses t.Cleanup to restore // the environment variable to its original value after // the test. // // Because unsetEnv affects the whole process, it should // not be used in parallel tests or tests with parallel // ancestors. func unsetEnv(t *testing.T, env string) { t.Helper() prevValue, ok := os.LookupEnv(env) if ok { _ = os.Unsetenv(env) t.Cleanup(func() { _ = os.Setenv(env, prevValue) }) } } func TestCustomSorting(t *testing.T) { formatter := &TextFormatter{ DisableColors: true, SortingFunc: func(keys []string) { sort.Slice(keys, func(i, j int) bool { if keys[j] == "prefix" { return false } if keys[i] == "prefix" { return true } return strings.Compare(keys[i], keys[j]) == -1 }) }, } entry := &Entry{ Message: "Testing custom sort function", Time: time.Now(), Level: InfoLevel, Data: Fields{ "test": "testvalue", "prefix": "the application prefix", "blablabla": "blablabla", }, } b, err := formatter.Format(entry) require.NoError(t, err) require.True(t, strings.HasPrefix(string(b), "prefix="), "format output is %q", string(b)) } // TestCustomSorting_FirstFormat tests that color and terminal settings // are performed on the first message, and the message is properly // formatted with default (fixedKeys) fields excluded. // // regression test for https://github.com/sirupsen/logrus/issues/1298 func TestCustomSorting_FirstFormat(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("colored output not supported on Windows") } if !checkIfTerminal(os.Stderr) { t.Skip("test requires a TTY") } t.Setenv("CLICOLOR", "") t.Setenv("CLICOLOR_FORCE", "") logger := New() logger.SetOutput(os.Stderr) // don't discard output; we need terminal detection entry := &Entry{ Logger: logger, Message: `colored messages are pretty`, Level: InfoLevel, Data: Fields{"z": 2, "a": 1}, } var sortCalled bool var otherFields []string tf := &TextFormatter{ DisableTimestamp: true, SortingFunc: func(keys []string) { sortCalled = true slices.Sort(keys) for _, key := range keys { if _, ok := entry.Data[key]; !ok { // default ("fixedKeys") should not be included when printing colored. otherFields = append(otherFields, key) } } }, } for _, name := range []string{"first", "second"} { t.Run(name, func(t *testing.T) { sortCalled = false otherFields = []string{} out, err := tf.Format(entry) require.NoError(t, err) assert.True(t, sortCalled) assert.Empty(t, otherFields) // sanity checks: assert.Contains(t, string(out), "\x1b[") // ANSI present assert.Contains(t, string(out), "colored messages are pretty") }) } } func TestTextEntryFieldValueError(t *testing.T) { t.Run("good value", func(t *testing.T) { var buf bytes.Buffer l := New() l.SetOutput(&buf) l.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true}) l.WithField("ok", "ok").Info("test") out := buf.String() if field := FieldKeyLogrusError + "="; strings.Contains(out, field) { t.Errorf(`Unexpected "logrus_error" field in log entry: %v`, out) } if field := `ok=ok`; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain "ok=ok": %v`, out) } }) // 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 := New() l.SetOutput(&buf) l.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true}) l.WithField("func", func() {}).WithField("ok", "ok").Info("test") out := buf.String() if field := FieldKeyLogrusError + "="; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain a "logrus_error" field: %v`, out) } if field := `func=`; strings.Contains(out, field) { t.Errorf(`Expected "func" field to be removed from log entry: %v`, out) } if field := `ok=ok`; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain "ok=ok": %v`, out) } }) // 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 := New() l.SetOutput(&buf) l.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true}) l.WithField("func", func() {}).WithField("ok", "ok").WithField("func", "not-a-func").Info("test") out := buf.String() if field := FieldKeyLogrusError + "="; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain a "logrus_error" field: %v`, out) } if field := `func=not-a-func`; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain "func=not-a-func": %v`, out) } if field := `ok=ok`; !strings.Contains(out, field) { t.Errorf(`Expected log entry to contain "ok=ok": %v`, out) } }) } ================================================ FILE: writer.go ================================================ package logrus import ( "bufio" "io" "runtime" "strings" ) // Writer at INFO level. See WriterLevel for details. func (logger *Logger) Writer() *io.PipeWriter { return logger.WriterLevel(InfoLevel) } // WriterLevel returns an io.Writer that can be used to write arbitrary text to // the logger at the given log level. Each line written to the writer will be // printed in the usual way using formatters and hooks. The writer is part of an // io.Pipe and it is the callers responsibility to close the writer when done. // This can be used to override the standard library logger easily. func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { return NewEntry(logger).WriterLevel(level) } // Writer returns an io.Writer that writes to the logger at the info log level func (entry *Entry) Writer() *io.PipeWriter { return entry.WriterLevel(InfoLevel) } // WriterLevel returns an io.Writer that writes to the logger at the given log level func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { reader, writer := io.Pipe() printFunc := entry.Print // Determine which log function to use based on the specified log level switch level { case TraceLevel: printFunc = entry.Trace case DebugLevel: printFunc = entry.Debug case InfoLevel: printFunc = entry.Info case WarnLevel: printFunc = entry.Warn case ErrorLevel: printFunc = entry.Error case FatalLevel: printFunc = entry.Fatal case PanicLevel: printFunc = entry.Panic } // Start a new goroutine to scan the input and write it to the logger using the specified print function. // It splits the input into chunks of up to 64KB to avoid buffer overflows. go entry.writerScanner(reader, printFunc) // Set a finalizer function to close the writer when it is garbage collected runtime.SetFinalizer(writer, writerFinalizer) return writer } // writerScanner scans the input from the reader and writes it to the logger func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...any)) { scanner := bufio.NewScanner(reader) // Set the buffer size to the maximum token size to avoid buffer overflows scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize) // Define a split function to split the input into chunks of up to 64KB chunkSize := bufio.MaxScanTokenSize // 64KB splitFunc := func(data []byte, atEOF bool) (int, []byte, error) { if len(data) >= chunkSize { return chunkSize, data[:chunkSize], nil } return bufio.ScanLines(data, atEOF) } // Use the custom split function to split the input scanner.Split(splitFunc) // Scan the input and write it to the logger using the specified print function for scanner.Scan() { printFunc(strings.TrimRight(scanner.Text(), "\r\n")) } // If there was an error while scanning the input, log an error if err := scanner.Err(); err != nil { entry.Errorf("Error while reading from Writer: %s", err) } // Close the reader when we are done reader.Close() } // WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected func writerFinalizer(writer *io.PipeWriter) { writer.Close() } ================================================ FILE: writer_test.go ================================================ package logrus_test import ( "bufio" "bytes" "log" "net/http" "strings" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/sirupsen/logrus" ) func ExampleLogger_Writer_httpServer() { logger := logrus.New() w := logger.Writer() defer w.Close() srv := http.Server{ // create a stdlib log.Logger that writes to // logrus.Logger. ErrorLog: log.New(w, "", 0), } if err := srv.ListenAndServe(); err != nil { logger.Fatal(err) } } func ExampleLogger_Writer_stdlib() { 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()) } type bufferWithMu struct { buf *bytes.Buffer mu sync.RWMutex } func (b *bufferWithMu) Write(p []byte) (int, error) { b.mu.Lock() defer b.mu.Unlock() return b.buf.Write(p) } func (b *bufferWithMu) Read(p []byte) (int, error) { b.mu.RLock() defer b.mu.RUnlock() return b.buf.Read(p) } func (b *bufferWithMu) String() string { b.mu.RLock() defer b.mu.RUnlock() return b.buf.String() } func TestWriterSplitNewlines(t *testing.T) { buf := &bufferWithMu{ buf: bytes.NewBuffer(nil), } logger := logrus.New() logger.Formatter = &logrus.TextFormatter{ DisableColors: true, DisableTimestamp: true, } logger.SetOutput(buf) writer := logger.Writer() const logNum = 10 for range logNum { _, err := writer.Write([]byte("bar\nfoo\n")) require.NoError(t, err, "writer.Write failed") } writer.Close() // Test is flaky because it writes in another goroutine, // we need to make sure to wait a bit so all write are done. time.Sleep(500 * time.Millisecond) lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") assert.Len(t, lines, logNum*2, "logger printed incorrect number of lines") } func TestWriterSplitsMax64KB(t *testing.T) { buf := &bufferWithMu{ buf: bytes.NewBuffer(nil), } logger := logrus.New() logger.Formatter = &logrus.TextFormatter{ DisableColors: true, DisableTimestamp: true, } logger.SetOutput(buf) writer := logger.Writer() // write more than 64KB const bigWriteLen = bufio.MaxScanTokenSize + 100 output := make([]byte, bigWriteLen) // lets not write zero bytes for i := range bigWriteLen { output[i] = 'A' } for range 3 { len, err := writer.Write(output) require.NoError(t, err, "writer.Write failed") assert.Equal(t, bigWriteLen, len, "bytes written") } writer.Close() // Test is flaky because it writes in another goroutine, // we need to make sure to wait a bit so all write are done. time.Sleep(500 * time.Millisecond) lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") // we should have 4 lines because we wrote more than 64 KB each time assert.Len(t, lines, 4, "logger printed incorrect number of lines") }