[
  {
    "path": ".github/workflows/ci.yaml",
    "content": "name: CI\n\n# Default to 'contents: read', which grants actions to read commits.\n#\n# If any permission is set, any permission not included in the list is\n# implicitly set to \"none\".\n#\n# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions\npermissions:\n  contents: read\n  pull-requests: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\non: [push, pull_request]\n\nenv:\n  GOTOOLCHAIN: local\n\njobs:\n  lint:\n    name: Golang-CI Lint\n    timeout-minutes: 10\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n      - name: Install Go\n        uses: actions/setup-go@v6\n        with:\n          go-version: stable\n      - name: Install golangci-lint\n        uses: golangci/golangci-lint-action@v9\n\n  cross:\n    name: Cross\n    timeout-minutes: 10\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n      - name: Install Go\n        uses: actions/setup-go@v6\n        with:\n          go-version: stable\n      - name: Build\n        run: |\n          for target in $(go tool dist list); do\n            echo \"Building for $target\"\n            GOOS=${target%/*} GOARCH=${target#*/} go build ./...\n          done\n\n  test:\n    name: Unit test\n    timeout-minutes: 10\n    strategy:\n      matrix:\n        go-version: [stable, oldstable, 1.23.x]\n        platform: [ubuntu-latest, windows-latest, macos-latest]\n    runs-on: ${{ matrix.platform }}\n    defaults:\n      run:\n        shell: bash\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n      - name: Install Go\n        uses: actions/setup-go@v6\n        with:\n          go-version: ${{ matrix.go-version }}\n      - name: Test\n        run: go test -race -v ./...\n"
  },
  {
    "path": ".gitignore",
    "content": "logrus\nvendor\n\n.idea/\n"
  },
  {
    "path": ".golangci.yml",
    "content": "version: \"2\"\nlinters:\n  enable:\n    - asasalint\n    - asciicheck\n    - bidichk\n    - contextcheck\n    - durationcheck\n    - errchkjson\n    - errorlint\n    - exhaustive\n    - gocheckcompilerdirectives\n    - gochecksumtype\n    - gosec\n    - gosmopolitan\n    - loggercheck\n    - makezero\n    - musttag\n    - nilerr\n    - nilnesserr\n    - noctx\n    - reassign\n    - recvcheck\n    - testifylint\n    - unparam\n  exclusions:\n    presets:\n      - legacy\n      - std-error-handling\n    rules:\n      # Exclude some linters from running on tests files.\n      - path: _test\\.go\n        linters:\n          - gosec\n          - musttag\n          - noctx # TODO: enable once we switch to Go 1.24+.\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# 1.9.4\n\nFixes:\n  * Remove uses of deprecated `ioutil` package\n\nFeatures:\n  * Add GNU/Hurd support\n  * Add WASI wasip1 support\n\nCode quality:\n  * Update minimum supported Go version to 1.17\n  * Documentation updates\n\n\n# 1.9.3\n\nFixes:\n  * Re-apply fix for potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)\n  * Fix panic in Writer\n\n\n# 1.9.2\n\nFixes:\n  * Revert Writer DoS fix (#1376) due to regression\n\n\n# 1.9.1\n\nFixes:\n  * Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)\n\n\n# 1.9.0\n\nFixes:\n  * Multiple concurrency and race condition fixes\n  * Improve Windows terminal and ANSI handling\n\nCode quality:\n  * Internal cleanups and modernization\n\n\n# 1.8.3\n\nFixes:\n  * Fix potential denial of service in logrus.Writer() when logging >64KB single-line payloads without newlines (#1376)\n\n\n# 1.8.2\n\nFeatures:\n  * Add support for the logger private buffer pool (#1253)\n\nFixes:\n  * Fix race condition for SetFormatter and SetReportCaller\n  * Fix data race in hooks test package\n\n# 1.8.1\nCode quality:\n  * move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer\n  * improve timestamp format documentation\n\nFixes:\n  * fix race condition on logger hooks\n\n\n# 1.8.0\n\nCorrect versioning number replacing v1.7.1.\n\n# 1.7.1\n\nBeware this release has introduced a new public API and its semver is therefore incorrect.\n\nCode quality:\n  * use go 1.15 in travis\n  * use magefile as task runner\n\nFixes:\n  * small fixes about new go 1.13 error formatting system\n  * Fix for long time race condiction with mutating data hooks\n\nFeatures:\n  * build support for zos\n\n# 1.7.0\nFixes:\n  * the dependency toward a windows terminal library has been removed\n\nFeatures:\n  * a new buffer pool management API has been added\n  * a set of `<LogLevel>Fn()` functions have been added\n\n# 1.6.0\nFixes:\n  * end of line cleanup\n  * revert the entry concurrency bug fix which leads to deadlock under some circumstances\n  * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14\n\nFeatures:\n  * add an option to the `TextFormatter` to completely disable fields quoting\n\n# 1.5.0\nCode quality:\n  * add golangci linter run on travis\n\nFixes:\n  * add mutex for hooks concurrent access on `Entry` data\n  * caller function field for go1.14\n  * fix build issue for gopherjs target\n\nFeature:\n  * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level\n  * add a `DisableHTMLEscape` option in the `JSONFormatter`\n  * add `ForceQuote` and `PadLevelText` options in the `TextFormatter`\n\n# 1.4.2\n  * Fixes build break for plan9, nacl, solaris\n# 1.4.1\nThis new release introduces:\n  * Enhance TextFormatter to not print caller information when they are empty (#944)\n  * Remove dependency on golang.org/x/crypto (#932, #943)\n\nFixes:\n  * Fix Entry.WithContext method to return a copy of the initial entry (#941)\n\n# 1.4.0\nThis new release introduces:\n  * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).\n  * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911)\n  * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).\n\nFixes:\n  * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).\n  * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)\n  * Fix infinite recursion on unknown `Level.String()` (#907)\n  * Fix race condition in `getCaller` (#916).\n\n\n# 1.3.0\nThis new release introduces:\n  * Log, Logf, Logln functions for Logger and Entry that take a Level\n\nFixes:\n  * Building prometheus node_exporter on AIX (#840)\n  * Race condition in TextFormatter (#468)\n  * Travis CI import path (#868)\n  * Remove coloured output on Windows (#862)\n  * Pointer to func as field in JSONFormatter (#870)\n  * Properly marshal Levels (#873)\n\n# 1.2.0\nThis new release introduces:\n  * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued\n  * A new trace level named `Trace` whose level is below `Debug`\n  * A configurable exit function to be called upon a Fatal trace\n  * The `Level` object now implements `encoding.TextUnmarshaler` interface\n\n# 1.1.1\nThis is a bug fix release.\n  * fix the build break on Solaris\n  * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized\n\n# 1.1.0\nThis new release introduces:\n  * several fixes:\n    * a fix for a race condition on entry formatting\n    * proper cleanup of previously used entries before putting them back in the pool\n    * the extra new line at the end of message in text formatter has been removed\n  * a new global public API to check if a level is activated: IsLevelEnabled\n  * the following methods have been added to the Logger object\n    * IsLevelEnabled\n    * SetFormatter\n    * SetOutput\n    * ReplaceHooks\n  * introduction of go module\n  * an indent configuration for the json formatter\n  * output colour support for windows\n  * the field sort function is now configurable for text formatter\n  * the CLICOLOR and CLICOLOR\\_FORCE environment variable support in text formater\n\n# 1.0.6\n\nThis new release introduces:\n  * a new api WithTime which allows to easily force the time of the log entry\n    which is mostly useful for logger wrapper\n  * a fix reverting the immutability of the entry given as parameter to the hooks\n    a new configuration field of the json formatter in order to put all the fields\n    in a nested dictionary\n  * a new SetOutput method in the Logger\n  * a new configuration of the textformatter to configure the name of the default keys\n  * a new configuration of the text formatter to disable the level truncation\n\n# 1.0.5\n\n* Fix hooks race (#707)\n* Fix panic deadlock (#695)\n\n# 1.0.4\n\n* Fix race when adding hooks (#612)\n* Fix terminal check in AppEngine (#635)\n\n# 1.0.3\n\n* Replace example files with testable examples\n\n# 1.0.2\n\n* bug: quote non-string values in text formatter (#583)\n* Make (*Logger) SetLevel a public method\n\n# 1.0.1\n\n* bug: fix escaping in text formatter (#575)\n\n# 1.0.0\n\n* Officially changed name to lower-case\n* bug: colors on Windows 10 (#541)\n* bug: fix race in accessing level (#512)\n\n# 0.11.5\n\n* feature: add writer and writerlevel to entry (#372)\n\n# 0.11.4\n\n* bug: fix undefined variable on solaris (#493)\n\n# 0.11.3\n\n* formatter: configure quoting of empty values (#484)\n* formatter: configure quoting character (default is `\"`) (#484)\n* bug: fix not importing io correctly in non-linux environments (#481)\n\n# 0.11.2\n\n* bug: fix windows terminal detection (#476)\n\n# 0.11.1\n\n* bug: fix tty detection with custom out (#471)\n\n# 0.11.0\n\n* performance: Use bufferpool to allocate (#370)\n* terminal: terminal detection for app-engine (#343)\n* feature: exit handler (#375)\n\n# 0.10.0\n\n* feature: Add a test hook (#180)\n* feature: `ParseLevel` is now case-insensitive (#326)\n* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)\n* performance: avoid re-allocations on `WithFields` (#335)\n\n# 0.9.0\n\n* logrus/text_formatter: don't emit empty msg\n* logrus/hooks/airbrake: move out of main repository\n* logrus/hooks/sentry: move out of main repository\n* logrus/hooks/papertrail: move out of main repository\n* logrus/hooks/bugsnag: move out of main repository\n* logrus/core: run tests with `-race`\n* logrus/core: detect TTY based on `stderr`\n* logrus/core: support `WithError` on logger\n* logrus/core: Solaris support\n\n# 0.8.7\n\n* logrus/core: fix possible race (#216)\n* logrus/doc: small typo fixes and doc improvements\n\n\n# 0.8.6\n\n* hooks/raven: allow passing an initialized client\n\n# 0.8.5\n\n* logrus/core: revert #208\n\n# 0.8.4\n\n* formatter/text: fix data race (#218)\n\n# 0.8.3\n\n* logrus/core: fix entry log level (#208)\n* logrus/core: improve performance of text formatter by 40%\n* logrus/core: expose `LevelHooks` type\n* logrus/core: add support for DragonflyBSD and NetBSD\n* formatter/text: print structs more verbosely\n\n# 0.8.2\n\n* logrus: fix more Fatal family functions\n\n# 0.8.1\n\n* logrus: fix not exiting on `Fatalf` and `Fatalln`\n\n# 0.8.0\n\n* logrus: defaults to stderr instead of stdout\n* hooks/sentry: add special field for `*http.Request`\n* formatter/text: ignore Windows for colors\n\n# 0.7.3\n\n* formatter/\\*: allow configuration of timestamp layout\n\n# 0.7.2\n\n* formatter/text: Add configuration option for time format (#158)\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014 Simon Eskildsen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Logrus <img src=\"http://i.imgur.com/hTeVwmJ.png\" width=\"40\" height=\"40\" alt=\":walrus:\" class=\"emoji\" title=\":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)\n\nLogrus is a structured logger for Go (golang), completely API compatible with\nthe standard library logger.\n\n**Logrus is in maintenance-mode.** We will not be introducing new features. It's\nsimply too hard to do in a way that won't break many people's projects, which is\nthe last thing you want from your Logging library (again...).\n\nThis does not mean Logrus is dead. Logrus will continue to be maintained for\nsecurity, (backwards compatible) bug fixes, and performance (where we are\nlimited by the interface).\n\nI believe Logrus' biggest contribution is to have played a part in today's\nwidespread use of structured logging in Golang. There doesn't seem to be a\nreason to do a major, breaking iteration into Logrus V2, since the fantastic Go\ncommunity has built those independently. Many fantastic alternatives have sprung\nup. Logrus would look like those, had it been re-designed with what we know\nabout structured logging in Go today. Check out, for example,\n[Zerolog][zerolog], [Zap][zap], and [Apex][apex].\n\n[zerolog]: https://github.com/rs/zerolog\n[zap]: https://github.com/uber-go/zap\n[apex]: https://github.com/apex/log\n\n**Seeing weird case-sensitive problems?** It's in the past been possible to\nimport Logrus as both upper- and lower-case. Due to the Go package environment,\nthis caused issues in the community and we needed a standard. Some environments\nexperienced problems with the upper-case variant, so the lower-case was decided.\nEverything using `logrus` will need to use the lower-case:\n`github.com/sirupsen/logrus`. Any package that isn't, should be changed.\n\nTo fix Glide, see [these\ncomments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).\nFor an in-depth explanation of the casing issue, see [this\ncomment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).\n\nNicely color-coded in development (when a TTY is attached, otherwise just\nplain text):\n\n![Colored](http://i.imgur.com/PY7qMwd.png)\n\nWith `logrus.SetFormatter(&logrus.JSONFormatter{})`, for easy parsing by logstash\nor Splunk:\n\n```text\n{\"animal\":\"walrus\",\"level\":\"info\",\"msg\":\"A group of walrus emerges from the\nocean\",\"size\":10,\"time\":\"2014-03-10 19:57:38.562264131 -0400 EDT\"}\n\n{\"level\":\"warning\",\"msg\":\"The group's number increased tremendously!\",\n\"number\":122,\"omg\":true,\"time\":\"2014-03-10 19:57:38.562471297 -0400 EDT\"}\n\n{\"animal\":\"walrus\",\"level\":\"info\",\"msg\":\"A giant walrus appears!\",\n\"size\":10,\"time\":\"2014-03-10 19:57:38.562500591 -0400 EDT\"}\n\n{\"animal\":\"walrus\",\"level\":\"info\",\"msg\":\"Tremendously sized cow enters the ocean.\",\n\"size\":9,\"time\":\"2014-03-10 19:57:38.562527896 -0400 EDT\"}\n\n{\"level\":\"fatal\",\"msg\":\"The ice breaks!\",\"number\":100,\"omg\":true,\n\"time\":\"2014-03-10 19:57:38.562543128 -0400 EDT\"}\n```\n\nWith the default `logrus.SetFormatter(&logrus.TextFormatter{})` when a TTY is not\nattached, the output is compatible with the\n[logfmt](https://pkg.go.dev/github.com/kr/logfmt) format:\n\n```text\ntime=\"2015-03-26T01:27:38-04:00\" level=debug msg=\"Started observing beach\" animal=walrus number=8\ntime=\"2015-03-26T01:27:38-04:00\" level=info msg=\"A group of walrus emerges from the ocean\" animal=walrus size=10\ntime=\"2015-03-26T01:27:38-04:00\" level=warning msg=\"The group's number increased tremendously!\" number=122 omg=true\ntime=\"2015-03-26T01:27:38-04:00\" level=debug msg=\"Temperature changes\" temperature=-4\ntime=\"2015-03-26T01:27:38-04:00\" level=panic msg=\"It's over 9000!\" animal=orca size=9009\ntime=\"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\n```\nTo ensure this behaviour even if a TTY is attached, set your formatter as follows:\n\n```go\nlogrus.SetFormatter(&logrus.TextFormatter{\n    DisableColors: true,\n    FullTimestamp: true,\n})\n```\n\n#### Logging Method Name\n\nIf you wish to add the calling method as a field, instruct the logger via:\n\n```go\nlogrus.SetReportCaller(true)\n```\nThis adds the caller as 'method' like so:\n\n```json\n{\"animal\":\"penguin\",\"level\":\"fatal\",\"method\":\"github.com/sirupsen/arcticcreatures.migrate\",\"msg\":\"a penguin swims by\",\n\"time\":\"2014-03-10 19:57:38.562543129 -0400 EDT\"}\n```\n\n```text\ntime=\"2015-03-26T01:27:38-04:00\" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg=\"a penguin swims by\" animal=penguin\n```\nNote that this does add measurable overhead - the cost will depend on the version of Go, but is\nbetween 20 and 40% in recent tests with 1.6 and 1.7.  You can validate this in your\nenvironment via benchmarks:\n\n```bash\ngo test -bench=.*CallerTracing\n```\n\n#### Case-sensitivity\n\nThe organization's name was changed to lower-case--and this will not be changed\nback. If you are getting import conflicts due to case sensitivity, please use\nthe lower-case import: `github.com/sirupsen/logrus`.\n\n#### Example\n\nThe simplest way to use Logrus is simply the package-level exported logger:\n\n```go\npackage main\n\nimport \"github.com/sirupsen/logrus\"\n\nfunc main() {\n  logrus.WithFields(logrus.Fields{\n    \"animal\": \"walrus\",\n  }).Info(\"A walrus appears\")\n}\n```\n\nNote that it's completely api-compatible with the stdlib logger, so you can\nreplace your `log` imports everywhere with `log \"github.com/sirupsen/logrus\"`\nand you'll now have the flexibility of Logrus. You can customize it all you\nwant:\n\n```go\npackage main\n\nimport (\n  \"os\"\n\n  log \"github.com/sirupsen/logrus\"\n)\n\nfunc init() {\n  // Log as JSON instead of the default ASCII formatter.\n  log.SetFormatter(&log.JSONFormatter{})\n\n  // Output to stdout instead of the default stderr\n  // Can be any io.Writer, see below for File example\n  log.SetOutput(os.Stdout)\n\n  // Only log the warning severity or above.\n  log.SetLevel(log.WarnLevel)\n}\n\nfunc main() {\n  log.WithFields(log.Fields{\n    \"animal\": \"walrus\",\n    \"size\":   10,\n  }).Info(\"A group of walrus emerges from the ocean\")\n\n  log.WithFields(log.Fields{\n    \"omg\":    true,\n    \"number\": 122,\n  }).Warn(\"The group's number increased tremendously!\")\n\n  log.WithFields(log.Fields{\n    \"omg\":    true,\n    \"number\": 100,\n  }).Fatal(\"The ice breaks!\")\n\n  // A common pattern is to re-use fields between logging statements by re-using\n  // the logrus.Entry returned from WithFields()\n  contextLogger := log.WithFields(log.Fields{\n    \"common\": \"this is a common field\",\n    \"other\": \"I also should be logged always\",\n  })\n\n  contextLogger.Info(\"I'll be logged with common and other field\")\n  contextLogger.Info(\"Me too\")\n}\n```\n\nFor more advanced usage such as logging to multiple locations from the same\napplication, you can also create an instance of the `logrus` Logger:\n\n```go\npackage main\n\nimport (\n  \"os\"\n\n  \"github.com/sirupsen/logrus\"\n)\n\n// Create a new instance of the logger. You can have any number of instances.\nvar logger = logrus.New()\n\nfunc main() {\n  // The API for setting attributes is a little different than the package level\n  // exported logger. See Godoc. \n  logger.Out = os.Stdout\n\n  // You could set this to any `io.Writer` such as a file\n  // file, err := os.OpenFile(\"logrus.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n  // if err == nil {\n  //  logger.Out = file\n  // } else {\n  //  logger.Info(\"Failed to log to file, using default stderr\")\n  // }\n\n  logger.WithFields(logrus.Fields{\n    \"animal\": \"walrus\",\n    \"size\":   10,\n  }).Info(\"A group of walrus emerges from the ocean\")\n}\n```\n\n#### Fields\n\nLogrus encourages careful, structured logging through logging fields instead of\nlong, unparseable error messages. For example, instead of: `logrus.Fatalf(\"Failed\nto send event %s to topic %s with key %d\")`, you should log the much more\ndiscoverable:\n\n```go\nlogrus.WithFields(logrus.Fields{\n  \"event\": event,\n  \"topic\": topic,\n  \"key\": key,\n}).Fatal(\"Failed to send event\")\n```\n\nWe've found this API forces you to think about logging in a way that produces\nmuch more useful logging messages. We've been in countless situations where just\na single added field to a log statement that was already there would've saved us\nhours. The `WithFields` call is optional.\n\nIn general, with Logrus using any of the `printf`-family functions should be\nseen as a hint you should add a field, however, you can still use the\n`printf`-family functions with Logrus.\n\n#### Default Fields\n\nOften it's helpful to have fields _always_ attached to log statements in an\napplication or parts of one. For example, you may want to always log the\n`request_id` and `user_ip` in the context of a request. Instead of writing\n`logger.WithFields(logrus.Fields{\"request_id\": request_id, \"user_ip\": user_ip})` on\nevery line, you can create a `logrus.Entry` to pass around instead:\n\n```go\nrequestLogger := logger.WithFields(logrus.Fields{\"request_id\": request_id, \"user_ip\": user_ip})\nrequestLogger.Info(\"something happened on that request\") // will log request_id and user_ip\nrequestLogger.Warn(\"something not great happened\")\n```\n\n#### Hooks\n\nYou can add hooks for logging levels. For example to send errors to an exception\ntracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to\nmultiple places simultaneously, e.g. syslog.\n\nLogrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in\n`init`:\n\n```go\npackage main\n\nimport (\n  \"log/syslog\"\n\n  \"github.com/sirupsen/logrus\"\n  airbrake \"gopkg.in/gemnasium/logrus-airbrake-hook.v2\"\n  logrus_syslog \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\nfunc init() {\n\n  // Use the Airbrake hook to report errors that have Error severity or above to\n  // an exception tracker. You can create custom hooks, see the Hooks section.\n  logrus.AddHook(airbrake.NewHook(123, \"xyz\", \"production\"))\n\n  hook, err := logrus_syslog.NewSyslogHook(\"udp\", \"localhost:514\", syslog.LOG_INFO, \"\")\n  if err != nil {\n    logrus.Error(\"Unable to connect to local syslog daemon\")\n  } else {\n    logrus.AddHook(hook)\n  }\n}\n```\nNote: 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).\n\nA list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)\n\n\n#### Level logging\n\nLogrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.\n\n```go\nlogrus.Trace(\"Something very low level.\")\nlogrus.Debug(\"Useful debugging information.\")\nlogrus.Info(\"Something noteworthy happened!\")\nlogrus.Warn(\"You should probably take a look at this.\")\nlogrus.Error(\"Something failed but I'm not quitting.\")\n// Calls os.Exit(1) after logging\nlogrus.Fatal(\"Bye.\")\n// Calls panic() after logging\nlogrus.Panic(\"I'm bailing.\")\n```\n\nYou can set the logging level on a `Logger`, then it will only log entries with\nthat severity or anything above it:\n\n```go\n// Will log anything that is info or above (warn, error, fatal, panic). Default.\nlogrus.SetLevel(logrus.InfoLevel)\n```\n\nIt may be useful to set `logrus.Level = logrus.DebugLevel` in a debug or verbose\nenvironment if your application has that.\n\nNote: 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).\n\n#### Entries\n\nBesides the fields added with `WithField` or `WithFields` some fields are\nautomatically added to all logging events:\n\n1. `time`. The timestamp when the entry was created.\n2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after\n   the `AddFields` call. E.g. `Failed to send event.`\n3. `level`. The logging level. E.g. `info`.\n\n#### Environments\n\nLogrus has no notion of environment.\n\nIf you wish for hooks and formatters to only be used in specific environments,\nyou should handle that yourself. For example, if your application has a global\nvariable `Environment`, which is a string representation of the environment you\ncould do:\n\n```go\nimport (\n  \"github.com/sirupsen/logrus\"\n)\n\nfunc init() {\n  // do something here to set environment depending on an environment variable\n  // or command-line flag\n  if Environment == \"production\" {\n    logrus.SetFormatter(&logrus.JSONFormatter{})\n  } else {\n    // The TextFormatter is default, you don't actually have to do this.\n    logrus.SetFormatter(&logrus.TextFormatter{})\n  }\n}\n```\n\nThis configuration is how `logrus` was intended to be used, but JSON in\nproduction is mostly only useful if you do log aggregation with tools like\nSplunk or Logstash.\n\n#### Formatters\n\nThe built-in logging formatters are:\n\n* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise\n  without colors.\n  * *Note:* to force colored output when there is no TTY, set the `ForceColors`\n    field to `true`.  To force no colored output even if there is a TTY  set the\n    `DisableColors` field to `true`. For Windows, see\n    [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).\n  * When colors are enabled, levels are truncated to 4 characters by default. To disable\n    truncation set the `DisableLevelTruncation` field to `true`.\n  * 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.\n  * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#TextFormatter).\n* `logrus.JSONFormatter`. Logs fields as JSON.\n  * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#JSONFormatter).\n\nThird-party logging formatters:\n\n* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.\n* [`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).\n* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.\n* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.\n* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo.\n* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.\n* [`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.\n* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added.\n* [`easy-logrus-formatter`](https://github.com/WeiZhixiong/easy-logrus-formatter). Provide a user-friendly formatter for logrus.\n* [`redactrus`](https://github.com/ibreakthecloud/redactrus). Redacts sensitive information like password, apikeys, email, etc. from logs.\n\nYou can define your formatter by implementing the `Formatter` interface,\nrequiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a\n`Fields` type (`map[string]any`) with all your fields as well as the\ndefault ones (see Entries section above):\n\n```go\ntype MyJSONFormatter struct{}\n\nlogrus.SetFormatter(new(MyJSONFormatter))\n\nfunc (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {\n  // Note this doesn't include Time, Level and Message which are available on\n  // the Entry. Consult `godoc` on information about those fields or read the\n  // source of the official loggers.\n  serialized, err := json.Marshal(entry.Data)\n    if err != nil {\n      return nil, fmt.Errorf(\"Failed to marshal fields to JSON, %w\", err)\n    }\n  return append(serialized, '\\n'), nil\n}\n```\n\n#### Logger as an `io.Writer`\n\nLogrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.\n\n```go\nw := logger.Writer()\ndefer w.Close()\n\nsrv := http.Server{\n    // create a stdlib log.Logger that writes to\n    // logrus.Logger.\n    ErrorLog: log.New(w, \"\", 0),\n}\n```\n\nEach line written to that writer will be printed the usual way, using formatters\nand hooks. The level for those entries is `info`.\n\nThis means that we can override the standard library logger easily:\n\n```go\nlogger := logrus.New()\nlogger.Formatter = &logrus.JSONFormatter{}\n\n// Use logrus for standard log output\n// Note that `log` here references stdlib's log\n// Not logrus imported under the name `log`.\nlog.SetOutput(logger.Writer())\n```\n\n#### Rotation\n\nLog rotation is not provided with Logrus. Log rotation should be done by an\nexternal program (like `logrotate(8)`) that can compress and delete old log\nentries. It should not be a feature of the application-level logger.\n\n#### Tools\n\n| Tool | Description |\n| ---- | ----------- |\n|[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.|\n|[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) |\n\n#### Testing\n\nLogrus has a built-in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:\n\n* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook\n* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):\n\n```go\nimport(\n  \"testing\"\n\n  \"github.com/sirupsen/logrus\"\n  \"github.com/sirupsen/logrus/hooks/test\"\n  \"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSomething(t*testing.T){\n  logger, hook := test.NewNullLogger()\n  logger.Error(\"Helloerror\")\n\n  assert.Equal(t, 1, len(hook.Entries))\n  assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)\n  assert.Equal(t, \"Helloerror\", hook.LastEntry().Message)\n\n  hook.Reset()\n  assert.Nil(t, hook.LastEntry())\n}\n```\n\n#### Fatal handlers\n\nLogrus can register one or more functions that will be called when any `fatal`\nlevel message is logged. The registered handlers will be executed before\nlogrus performs an `os.Exit(1)`. This behavior may be helpful if callers need\nto 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.\n\n```go\n// ...\nhandler := func() {\n  // gracefully shut down something...\n}\nlogrus.RegisterExitHandler(handler)\n// ...\n```\n\n#### Thread safety\n\nBy default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.\nIf you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.\n\nSituations when locking is not needed include:\n\n* You have no hooks registered, or hooks calling is already thread-safe.\n\n* Writing to logger.Out is already thread-safe, for example:\n\n  1) logger.Out is protected by locks.\n\n  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)\n\n     (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)\n"
  },
  {
    "path": "alt_exit.go",
    "content": "package logrus\n\n// The following code was sourced and modified from the\n// https://github.com/tebeka/atexit package governed by the following license:\n//\n// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar handlers = []func(){}\n\nfunc runHandler(handler func()) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Error: Logrus exit handler error:\", err)\n\t\t}\n\t}()\n\n\thandler()\n}\n\nfunc runHandlers() {\n\tfor _, handler := range handlers {\n\t\trunHandler(handler)\n\t}\n}\n\n// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)\nfunc Exit(code int) {\n\trunHandlers()\n\tos.Exit(code)\n}\n\n// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,\n// call logrus.Exit to invoke all handlers. The handlers will also be invoked when\n// any Fatal log entry is made.\n//\n// This method is useful when a caller wishes to use logrus to log a fatal\n// message but also needs to gracefully shutdown. An example usecase could be\n// closing database connections, or sending a alert that the application is\n// closing.\nfunc RegisterExitHandler(handler func()) {\n\thandlers = append(handlers, handler)\n}\n\n// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,\n// call logrus.Exit to invoke all handlers. The handlers will also be invoked when\n// any Fatal log entry is made.\n//\n// This method is useful when a caller wishes to use logrus to log a fatal\n// message but also needs to gracefully shutdown. An example usecase could be\n// closing database connections, or sending a alert that the application is\n// closing.\nfunc DeferExitHandler(handler func()) {\n\thandlers = append([]func(){handler}, handlers...)\n}\n"
  },
  {
    "path": "alt_exit_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc TestRegister(t *testing.T) {\n\tif reexecTest(t, \"register\", func(t *testing.T) {\n\t\toutfile := os.Args[len(os.Args)-1]\n\t\tlogrus.RegisterExitHandler(func() { appendLine(outfile, \"first\") })\n\t\tlogrus.RegisterExitHandler(func() { appendLine(outfile, \"second\") })\n\t\tlogrus.Exit(23)\n\t}) {\n\t\treturn\n\t}\n\n\toutfile := filepath.Join(t.TempDir(), \"out.txt\")\n\tcmd := reexecCommand(t, \"register\", outfile)\n\tout, err := cmd.CombinedOutput()\n\tvar ee *exec.ExitError\n\tif !errors.As(err, &ee) {\n\t\tt.Fatalf(\"expected *exec.ExitError, got %T: %v (out=%s)\", err, err, out)\n\t}\n\tif ee.ExitCode() != 23 {\n\t\tt.Fatalf(\"expected exit 23, got %d (out=%s)\", ee.ExitCode(), out)\n\t}\n\twant := \"first\\nsecond\\n\"\n\tassertFileContent(t, outfile, want, out)\n}\n\nfunc TestDefer(t *testing.T) {\n\tif reexecTest(t, \"defer\", func(t *testing.T) {\n\t\toutfile := os.Args[len(os.Args)-1]\n\t\tlogrus.DeferExitHandler(func() { appendLine(outfile, \"first\") })\n\t\tlogrus.DeferExitHandler(func() { appendLine(outfile, \"second\") })\n\t\tlogrus.Exit(23)\n\t}) {\n\t\treturn\n\t}\n\n\toutfile := filepath.Join(t.TempDir(), \"out.txt\")\n\tcmd := reexecCommand(t, \"defer\", outfile)\n\tout, err := cmd.CombinedOutput()\n\tvar ee *exec.ExitError\n\tif !errors.As(err, &ee) {\n\t\tt.Fatalf(\"expected *exec.ExitError, got %T: %v (out=%s)\", err, err, out)\n\t}\n\tif ee.ExitCode() != 23 {\n\t\tt.Fatalf(\"expected exit 23, got %d (out=%s)\", ee.ExitCode(), out)\n\t}\n\twant := \"second\\nfirst\\n\"\n\tassertFileContent(t, outfile, want, out)\n}\n\nfunc TestHandler(t *testing.T) {\n\tconst payload = \"payload\"\n\tif reexecTest(t, \"handler\", func(t *testing.T) {\n\t\toutfile := os.Args[len(os.Args)-1]\n\t\tlogrus.RegisterExitHandler(func() {\n\t\t\t_ = os.WriteFile(outfile, []byte(payload), 0o666)\n\t\t})\n\t\tlogrus.RegisterExitHandler(func() { panic(\"bad handler\") })\n\n\t\tlogrus.Exit(23)\n\t}) {\n\t\treturn\n\t}\n\n\toutfile := filepath.Join(t.TempDir(), \"outfile.out\")\n\tcmd := reexecCommand(t, \"handler\", outfile)\n\tout, err := cmd.CombinedOutput()\n\tvar ee *exec.ExitError\n\tif !errors.As(err, &ee) {\n\t\tt.Fatalf(\"expected *exec.ExitError, got %T: %v (out=%s)\", err, err, out)\n\t}\n\tif ee.ExitCode() != 23 {\n\t\tt.Fatalf(\"expected exit 23, got %d (out=%s)\", ee.ExitCode(), out)\n\t}\n\n\twant := payload\n\tassertFileContent(t, outfile, want, out)\n}\n\nfunc appendLine(path, s string) {\n\tb, err := os.ReadFile(path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\t_, _ = os.Stderr.WriteString(\"appendLine: read \" + path + \": \" + err.Error() + \"\\n\")\n\t\tos.Exit(1)\n\t}\n\tb = append(b, []byte(s+\"\\n\")...)\n\tif err := os.WriteFile(path, b, 0o666); err != nil {\n\t\t_, _ = os.Stderr.WriteString(\"appendLine: write \" + path + \": \" + err.Error() + \"\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc assertFileContent(t *testing.T, path, want string, childOut []byte) {\n\tt.Helper()\n\n\tb, err := os.ReadFile(path)\n\tif err != nil {\n\t\tt.Fatalf(\"can't read output file: %v (child out=%s)\", err, childOut)\n\t}\n\n\tif got := string(b); got != want {\n\t\tt.Fatalf(\"unexpected file content: got %q, want %q (child out=%s)\", got, want, childOut)\n\t}\n}\n\nconst tokenPrefix = \"reexectest-\"\n\n// argv0Token computes a short deterministic token for (t.Name(), name).\nfunc argv0Token(t *testing.T, name string) string {\n\tsum := sha256.Sum256([]byte(t.Name() + \"\\x00\" + name))\n\treturn tokenPrefix + hex.EncodeToString(sum[:8]) // 16 hex chars\n}\n\n// reexecTest runs fn if this process is the child (argv0 == token).\n// Returns true in the child (caller should return).\nfunc reexecTest(t *testing.T, name string, f func(t *testing.T)) bool {\n\tt.Helper()\n\n\tif os.Args[0] != argv0Token(t, name) {\n\t\treturn false\n\t}\n\n\t// Scrub the \"-test.run=<pattern>\" that was injected by reexecCommand.\n\torigArgs := os.Args\n\tif len(os.Args) > 1 && strings.HasPrefix(os.Args[1], \"-test.run=\") {\n\t\tos.Args = append(os.Args[:1], os.Args[2:]...)\n\t\tdefer func() { os.Args = origArgs }()\n\t}\n\n\tf(t)\n\treturn true\n}\n\n// reexecCommand builds a command that execs the current test binary (exe)\n// with argv0 set to token and \"-test.run=<pattern>\" so the child runs only\n// this test/subtest. extraArgs are appended after that; the parent can pass\n// the outfile as extra arg, etc.\nfunc reexecCommand(t *testing.T, name string, args ...string) *exec.Cmd {\n\tt.Helper()\n\n\texe, err := os.Executable()\n\tif err != nil {\n\t\tt.Fatalf(\"os.Executable(): %v\", err)\n\t}\n\n\targv0 := argv0Token(t, name)\n\tpattern := \"^\" + regexp.QuoteMeta(t.Name()) + \"$\"\n\n\tcmd := exec.Command(exe)\n\tcmd.Path = exe\n\tcmd.Args = append([]string{argv0, \"-test.run=\" + pattern}, args...)\n\treturn cmd\n}\n"
  },
  {
    "path": "appveyor.yml",
    "content": "# Minimal stub to satisfy AppVeyor CI\nversion: 1.0.{build}\nplatform: x64\nshallow_clone: true\n\nbranches:\n  only:\n    - master\n    - main\n\nbuild_script:\n  - echo \"No-op build to satisfy AppVeyor CI\"\n"
  },
  {
    "path": "buffer_pool.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bufferPool BufferPool = &defaultPool{\n\tpool: &sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn new(bytes.Buffer)\n\t\t},\n\t},\n}\n\ntype BufferPool interface {\n\tPut(*bytes.Buffer)\n\tGet() *bytes.Buffer\n}\n\ntype defaultPool struct {\n\tpool *sync.Pool\n}\n\nfunc (p *defaultPool) Put(buf *bytes.Buffer) {\n\tp.pool.Put(buf)\n}\n\nfunc (p *defaultPool) Get() *bytes.Buffer {\n\treturn p.pool.Get().(*bytes.Buffer)\n}\n\n// SetBufferPool allows to replace the default logrus buffer pool\n// to better meets the specific needs of an application.\nfunc SetBufferPool(bp BufferPool) {\n\tbufferPool = bp\n}\n"
  },
  {
    "path": "doc.go",
    "content": "/*\nPackage logrus is a structured logger for Go, completely API compatible with the standard library logger.\n\nThe simplest way to use Logrus is simply the package-level exported logger:\n\n\tpackage main\n\n\timport (\n\t\tlog \"github.com/sirupsen/logrus\"\n\t)\n\n\tfunc main() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"animal\": \"walrus\",\n\t\t\t\"number\": 1,\n\t\t\t\"size\":   10,\n\t\t}).Info(\"A walrus appears\")\n\t}\n\nOutput:\n\n\ttime=\"2015-09-07T08:48:33Z\" level=info msg=\"A walrus appears\" animal=walrus number=1 size=10\n\nFor a full guide visit https://github.com/sirupsen/logrus\n*/\npackage logrus\n"
  },
  {
    "path": "entry.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"maps\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\n\t// qualified package name, cached at first use\n\tlogrusPackage string\n\n\t// Positions in the call stack when tracing to report the calling method.\n\t//\n\t// Start at the bottom of the stack before the package-name cache is primed.\n\tminimumCallerDepth = 1\n\n\t// Used for caller information initialisation\n\tcallerInitOnce sync.Once\n)\n\nconst (\n\tmaximumCallerDepth int = 25\n\tknownLogrusFrames  int = 4\n)\n\n// ErrorKey defines the key when adding errors using [WithError], [Logger.WithError].\nvar ErrorKey = \"error\"\n\n// Entry represents a single log event. It may be either an intermediate\n// entry (created via WithField(s), WithContext, etc.) or a final entry\n// that is emitted when one of the level methods (Trace, Debug, Info,\n// Warn, Error, Fatal, Panic) is called.\n//\n// An Entry always belongs to a Logger. A nil Logger is invalid and will\n// cause a panic when the entry is logged. Use [NewEntry] or Logger methods\n// to construct entries.\n//\n// Entries are safe to reuse for adding fields and may be passed around\n// to avoid field duplication. Each log operation operates on a copy\n// of the Entry’s data to avoid mutation during formatting.\n//\n//nolint:recvcheck // Entry methods intentionally use both pointer and value receivers.\ntype Entry struct {\n\t// Logger is the Logger that owns this entry and is responsible for\n\t// formatting, hooks, and output. It must not be nil. An Entry without\n\t// a Logger is invalid and will panic when logged.\n\tLogger *Logger\n\n\t// Data contains all user-defined fields attached to this entry.\n\tData Fields\n\n\t// Time is the timestamp for the log event. If zero when the entry is\n\t// logged, it defaults to the current time.\n\tTime time.Time\n\n\t// Level is the severity of the log entry. It is set when the entry\n\t// is fired and reflects the level used for that log call.\n\tLevel Level\n\n\t// Caller contains the calling method information when caller\n\t// reporting is enabled.\n\tCaller *runtime.Frame\n\n\t// Message is the log message supplied to one of the logging methods\n\t// (Trace, Debug, Info, Warn, Error, Fatal, or Panic). It is set when\n\t// the entry is logged.\n\tMessage string\n\n\t// Buffer is a reusable buffer provided to the formatter. It is set\n\t// before formatting in the normal log path; when nil, formatters\n\t// allocate their own.\n\tBuffer *bytes.Buffer\n\n\t// Context carries user-provided context for hooks and formatters.\n\tContext context.Context\n\n\t// err contains internal field-formatting errors.\n\terr string\n}\n\n// NewEntry creates a new Entry associated with the provided Logger.\n// The logger must not be nil. Passing a nil logger will result in a\n// panic when a logging method (e.g., Info, Error, etc.) is called.\nfunc NewEntry(logger *Logger) *Entry {\n\treturn &Entry{\n\t\tLogger: logger,\n\t\t// Reserve default predefined fields and a little extra room.\n\t\tData: make(Fields, defaultFields+3),\n\t}\n}\n\n// Dup creates a copy of the entry for further modification.\n//\n// The Data map is cloned so that changes to fields on the returned\n// entry do not mutate the original. The Logger and other metadata\n// are copied by value.\nfunc (entry *Entry) Dup() *Entry {\n\treturn &Entry{\n\t\tLogger:  entry.Logger,\n\t\tData:    maps.Clone(entry.Data),\n\t\tTime:    entry.Time,\n\t\tContext: entry.Context,\n\t\terr:     entry.err,\n\t}\n}\n\n// Bytes returns the bytes representation of this entry from the formatter.\nfunc (entry *Entry) Bytes() ([]byte, error) {\n\t// Snapshot the formatter under the lock to protect against concurrent\n\t// SetFormatter calls, then release the lock before formatting.\n\t// This avoids a data race and prevents a deadlock if Format() triggers\n\t// reentrant logging (e.g., a field's MarshalJSON calls logrus).\n\t//\n\t// See:\n\t//\n\t// - https://github.com/sirupsen/logrus/issues/1440\n\t// - https://github.com/sirupsen/logrus/issues/1448\n\tentry.Logger.mu.Lock()\n\tformatter := entry.Logger.Formatter\n\tentry.Logger.mu.Unlock()\n\n\treturn formatter.Format(entry)\n}\n\n// String returns the string representation from the reader and ultimately the\n// formatter.\nfunc (entry *Entry) String() (string, error) {\n\tserialized, err := entry.Bytes()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := string(serialized)\n\treturn str, nil\n}\n\n// WithError adds an error as single field (using the key defined in [ErrorKey])\n// to the Entry.\nfunc (entry *Entry) WithError(err error) *Entry {\n\t// Avoid reflection work in WithFields; we know the type is an error;\n\t// copy the entry data and set the ErrorKey directly.\n\tdata := make(Fields, len(entry.Data)+1)\n\tmaps.Copy(data, entry.Data)\n\tdata[ErrorKey] = err\n\n\treturn &Entry{\n\t\tLogger:  entry.Logger,\n\t\tData:    data,\n\t\tTime:    entry.Time,\n\t\tContext: entry.Context,\n\t\terr:     entry.err,\n\t}\n}\n\n// WithContext adds a context to the Entry.\nfunc (entry *Entry) WithContext(ctx context.Context) *Entry {\n\treturn &Entry{\n\t\tLogger:  entry.Logger,\n\t\tData:    maps.Clone(entry.Data),\n\t\tTime:    entry.Time,\n\t\tContext: ctx,\n\t\terr:     entry.err,\n\t}\n}\n\n// WithField adds a single field to the Entry.\nfunc (entry *Entry) WithField(key string, value any) *Entry {\n\treturn entry.WithFields(Fields{key: value})\n}\n\n// WithFields adds a map of fields to the Entry.\nfunc (entry *Entry) WithFields(fields Fields) *Entry {\n\tdata := make(Fields, len(entry.Data)+len(fields))\n\tmaps.Copy(data, entry.Data)\n\tfieldErr := entry.err\n\tfor k, v := range fields {\n\t\tisErrField := false\n\t\tif t := reflect.TypeOf(v); t != nil {\n\t\t\tswitch {\n\t\t\tcase t.Kind() == reflect.Func, t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Func:\n\t\t\t\tisErrField = true\n\t\t\t}\n\t\t}\n\t\tif isErrField {\n\t\t\ttmp := fmt.Sprintf(\"can not add field %q\", k)\n\t\t\tif fieldErr != \"\" {\n\t\t\t\tfieldErr += \", \" + tmp\n\t\t\t} else {\n\t\t\t\tfieldErr = tmp\n\t\t\t}\n\t\t} else {\n\t\t\tdata[k] = v\n\t\t}\n\t}\n\treturn &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}\n}\n\n// WithTime overrides the time of the Entry.\nfunc (entry *Entry) WithTime(t time.Time) *Entry {\n\treturn &Entry{\n\t\tLogger:  entry.Logger,\n\t\tData:    maps.Clone(entry.Data),\n\t\tTime:    t,\n\t\tContext: entry.Context,\n\t\terr:     entry.err,\n\t}\n}\n\n// getPackageName reduces a fully qualified function name to the package name\n// There really ought to be a better way...\nfunc getPackageName(f string) string {\n\tfor {\n\t\tlastPeriod := strings.LastIndex(f, \".\")\n\t\tlastSlash := strings.LastIndex(f, \"/\")\n\t\tif lastPeriod > lastSlash {\n\t\t\tf = f[:lastPeriod]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn f\n}\n\n// getCaller retrieves the name of the first non-logrus calling function\nfunc getCaller() *runtime.Frame {\n\t// cache this package's fully-qualified name\n\tcallerInitOnce.Do(func() {\n\t\tpcs := make([]uintptr, maximumCallerDepth)\n\t\t_ = runtime.Callers(0, pcs)\n\n\t\t// dynamic get the package name and the minimum caller depth\n\t\tfor i := range maximumCallerDepth {\n\t\t\tfuncName := runtime.FuncForPC(pcs[i]).Name()\n\t\t\tif strings.Contains(funcName, \"getCaller\") {\n\t\t\t\tlogrusPackage = getPackageName(funcName)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tminimumCallerDepth = knownLogrusFrames\n\t})\n\n\t// Restrict the lookback frames to avoid runaway lookups\n\tpcs := make([]uintptr, maximumCallerDepth)\n\tdepth := runtime.Callers(minimumCallerDepth, pcs)\n\tframes := runtime.CallersFrames(pcs[:depth])\n\n\tfor f, again := frames.Next(); again; f, again = frames.Next() {\n\t\tpkg := getPackageName(f.Function)\n\n\t\t// If the caller isn't part of this package, we're done\n\t\tif pkg != logrusPackage {\n\t\t\treturn &f\n\t\t}\n\t}\n\n\t// if we got here, we failed to find the caller's context\n\treturn nil\n}\n\n// HasCaller reports whether this Entry contains caller information.\n//\n// Caller is attached at log time if [Logger.ReportCaller] was enabled.\n// In most cases, it is preferable to check whether [Entry.Caller] is nil\n// directly.\nfunc (entry Entry) HasCaller() bool {\n\treturn entry.Caller != nil\n}\n\nfunc (entry *Entry) log(level Level, msg string) {\n\tnewEntry := entry.Dup()\n\tlogger := newEntry.Logger\n\n\tif newEntry.Time.IsZero() {\n\t\tnewEntry.Time = time.Now()\n\t}\n\n\tnewEntry.Level = level\n\tnewEntry.Message = msg\n\n\tlogger.mu.Lock()\n\treportCaller := logger.ReportCaller\n\tbufPool := newEntry.getBufferPool()\n\tlogger.mu.Unlock()\n\n\tif reportCaller {\n\t\tnewEntry.Caller = getCaller()\n\t}\n\n\t// Select hooks based on the level for this log call. Hooks receive the\n\t// Entry and may mutate it, but that does not affect which hooks are\n\t// fired for this event.\n\thooks := logger.hooksForLevel(level)\n\tnewEntry.fireHooks(hooks)\n\n\tbuffer := bufPool.Get()\n\tdefer func() {\n\t\tnewEntry.Buffer = nil\n\t\tbuffer.Reset()\n\t\tbufPool.Put(buffer)\n\t}()\n\tbuffer.Reset()\n\tnewEntry.Buffer = buffer\n\tnewEntry.write()\n\tnewEntry.Buffer = nil\n\n\t// To avoid Entry#log() returning a value that only would make sense for\n\t// panic() to use in Entry#Panic(), we avoid the allocation by checking\n\t// directly here.\n\tif level <= PanicLevel {\n\t\tpanic(newEntry)\n\t}\n}\n\nfunc (entry *Entry) getBufferPool() (pool BufferPool) {\n\tif entry.Logger.BufferPool != nil {\n\t\treturn entry.Logger.BufferPool\n\t}\n\treturn bufferPool\n}\n\nfunc (entry *Entry) fireHooks(hooks []Hook) {\n\tfor _, hook := range hooks {\n\t\tif err := hook.Fire(entry); err != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, \"Failed to fire hook:\", err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (entry *Entry) write() {\n\t// Snapshot the formatter under the lock to protect against concurrent\n\t// SetFormatter calls, then release the lock before formatting.\n\t// This avoids a deadlock when Format() triggers reentrant logging (e.g.,\n\t// a field's MarshalJSON calls logrus). See #1448, #1440.\n\tentry.Logger.mu.Lock()\n\tformatter := entry.Logger.Formatter\n\tentry.Logger.mu.Unlock()\n\n\tserialized, err := formatter.Format(entry)\n\tif err != nil {\n\t\t_, _ = fmt.Fprintln(os.Stderr, \"Failed to format entry:\", err)\n\t\treturn\n\t}\n\n\t// Re-acquire the lock to serialize writes to the underlying io.Writer.\n\tentry.Logger.mu.Lock()\n\tdefer entry.Logger.mu.Unlock()\n\tif _, err := entry.Logger.Out.Write(serialized); err != nil {\n\t\t_, _ = fmt.Fprintln(os.Stderr, \"Failed to write to log:\", err)\n\t}\n}\n\n// Log will log a message at the level given as parameter.\n// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.\n// For this behaviour Entry.Panic or Entry.Fatal should be used instead.\nfunc (entry *Entry) Log(level Level, args ...any) {\n\tif entry.Logger.IsLevelEnabled(level) {\n\t\tentry.log(level, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Trace(args ...any) {\n\tentry.Log(TraceLevel, args...)\n}\n\nfunc (entry *Entry) Debug(args ...any) {\n\tentry.Log(DebugLevel, args...)\n}\n\nfunc (entry *Entry) Print(args ...any) {\n\tentry.Info(args...)\n}\n\nfunc (entry *Entry) Info(args ...any) {\n\tentry.Log(InfoLevel, args...)\n}\n\nfunc (entry *Entry) Warn(args ...any) {\n\tentry.Log(WarnLevel, args...)\n}\n\nfunc (entry *Entry) Warning(args ...any) {\n\tentry.Warn(args...)\n}\n\nfunc (entry *Entry) Error(args ...any) {\n\tentry.Log(ErrorLevel, args...)\n}\n\nfunc (entry *Entry) Fatal(args ...any) {\n\tentry.Log(FatalLevel, args...)\n\tentry.Logger.Exit(1)\n}\n\nfunc (entry *Entry) Panic(args ...any) {\n\tentry.Log(PanicLevel, args...)\n}\n\n// Entry Printf family functions\n\nfunc (entry *Entry) Logf(level Level, format string, args ...any) {\n\tif entry.Logger.IsLevelEnabled(level) {\n\t\tentry.Log(level, fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Tracef(format string, args ...any) {\n\tentry.Logf(TraceLevel, format, args...)\n}\n\nfunc (entry *Entry) Debugf(format string, args ...any) {\n\tentry.Logf(DebugLevel, format, args...)\n}\n\nfunc (entry *Entry) Infof(format string, args ...any) {\n\tentry.Logf(InfoLevel, format, args...)\n}\n\nfunc (entry *Entry) Printf(format string, args ...any) {\n\tentry.Infof(format, args...)\n}\n\nfunc (entry *Entry) Warnf(format string, args ...any) {\n\tentry.Logf(WarnLevel, format, args...)\n}\n\nfunc (entry *Entry) Warningf(format string, args ...any) {\n\tentry.Warnf(format, args...)\n}\n\nfunc (entry *Entry) Errorf(format string, args ...any) {\n\tentry.Logf(ErrorLevel, format, args...)\n}\n\nfunc (entry *Entry) Fatalf(format string, args ...any) {\n\tentry.Logf(FatalLevel, format, args...)\n\tentry.Logger.Exit(1)\n}\n\nfunc (entry *Entry) Panicf(format string, args ...any) {\n\tentry.Logf(PanicLevel, format, args...)\n}\n\n// Entry Println family functions\n\nfunc (entry *Entry) Logln(level Level, args ...any) {\n\tif entry.Logger.IsLevelEnabled(level) {\n\t\tentry.Log(level, entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Traceln(args ...any) {\n\tentry.Logln(TraceLevel, args...)\n}\n\nfunc (entry *Entry) Debugln(args ...any) {\n\tentry.Logln(DebugLevel, args...)\n}\n\nfunc (entry *Entry) Infoln(args ...any) {\n\tentry.Logln(InfoLevel, args...)\n}\n\nfunc (entry *Entry) Println(args ...any) {\n\tentry.Infoln(args...)\n}\n\nfunc (entry *Entry) Warnln(args ...any) {\n\tentry.Logln(WarnLevel, args...)\n}\n\nfunc (entry *Entry) Warningln(args ...any) {\n\tentry.Warnln(args...)\n}\n\nfunc (entry *Entry) Errorln(args ...any) {\n\tentry.Logln(ErrorLevel, args...)\n}\n\nfunc (entry *Entry) Fatalln(args ...any) {\n\tentry.Logln(FatalLevel, args...)\n\tentry.Logger.Exit(1)\n}\n\nfunc (entry *Entry) Panicln(args ...any) {\n\tentry.Logln(PanicLevel, args...)\n}\n\n// sprintlnn => Sprint no newline. This is to get the behavior of how\n// fmt.Sprintln where spaces are always added between operands, regardless of\n// their type. Instead of vendoring the Sprintln implementation to spare a\n// string allocation, we do the simplest thing.\nfunc (entry *Entry) sprintlnn(args ...any) string {\n\tmsg := fmt.Sprintln(args...)\n\treturn msg[:len(msg)-1]\n}\n"
  },
  {
    "path": "entry_bench_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc BenchmarkEntry_WithError(b *testing.B) {\n\tbase := &logrus.Entry{Data: logrus.Fields{\"a\": 1}}\n\terrBoom := errors.New(\"boom\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor range b.N {\n\t\t_ = base.WithError(errBoom)\n\t}\n}\n\nfunc BenchmarkEntry_WithField_Chain(b *testing.B) {\n\tbase := &logrus.Entry{Data: logrus.Fields{\"a\": 1}}\n\terrBoom := errors.New(\"boom\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor range b.N {\n\t\te := base\n\n\t\te = e.WithField(\"k0\", 0)\n\t\te = e.WithField(\"k1\", 1)\n\t\te = e.WithField(\"k2\", 2)\n\t\te = e.WithField(\"k3\", 3)\n\t\te = e.WithError(errBoom)\n\t\t_ = e\n\t}\n}\n\nfunc BenchmarkEntry_WithFields(b *testing.B) {\n\tfn := func() {}\n\tfnPtr := &fn\n\n\ttests := []struct {\n\t\tname   string\n\t\tbase   logrus.Fields\n\t\tfields logrus.Fields\n\t}{\n\t\t{\n\t\t\tname:   \"valid_fields_only\",\n\t\t\tbase:   logrus.Fields{\"a\": 1, \"b\": \"two\"},\n\t\t\tfields: logrus.Fields{\"c\": 3, \"d\": \"four\"},\n\t\t},\n\t\t{\n\t\t\tname:   \"contains_func\",\n\t\t\tbase:   logrus.Fields{\"a\": 1},\n\t\t\tfields: logrus.Fields{\"bad\": fn},\n\t\t},\n\t\t{\n\t\t\tname:   \"contains_func_ptr\",\n\t\t\tbase:   logrus.Fields{\"a\": 1},\n\t\t\tfields: logrus.Fields{\"bad\": fnPtr},\n\t\t},\n\t\t{\n\t\t\tname:   \"mixed_valid_invalid\",\n\t\t\tbase:   logrus.Fields{\"a\": 1, \"b\": 2},\n\t\t\tfields: logrus.Fields{\"c\": 3, \"bad\": fn, \"d\": 4},\n\t\t},\n\t\t{\n\t\t\tname:   \"larger_map\",\n\t\t\tbase:   logrus.Fields{\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5, \"f\": 6, \"g\": 7, \"h\": 8, \"i\": 9, \"j\": 10},\n\t\t\tfields: logrus.Fields{\"k\": 11, \"l\": 12, \"m\": 13, \"n\": 14, \"o\": 15},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tb.Run(tc.name, func(b *testing.B) {\n\t\t\tb.ReportAllocs()\n\t\t\te := &logrus.Entry{Data: tc.base}\n\t\t\tb.ResetTimer()\n\t\t\tfor range b.N {\n\t\t\t\t_ = e.WithFields(tc.fields)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc benchmarkEntryInfo(b *testing.B, reportCaller bool) {\n\t// JSONFormatter is used intentionally to measure realistic end-to-end\n\t// ReportCaller overhead (Entry.log + caller field formatting),\n\t// not getCaller() in isolation.\n\tlogger := logrus.New()\n\tlogger.SetFormatter(&logrus.JSONFormatter{})\n\tlogger.SetReportCaller(reportCaller)\n\tlogger.SetLevel(logrus.InfoLevel) // ensure Info is enabled\n\tlogger.SetOutput(io.Discard)\n\n\tentry := logrus.NewEntry(logger)\n\n\t// getCaller has a package-level sync.Once; exclude initialization from the benchmark.\n\tentry.Info(\"warmup\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor range b.N {\n\t\tentry.Info(\"test message\")\n\t}\n}\n\nfunc BenchmarkEntry_ReportCaller_NoCaller(b *testing.B)   { benchmarkEntryInfo(b, false) }\nfunc BenchmarkEntry_ReportCaller_WithCaller(b *testing.B) { benchmarkEntryInfo(b, true) }\n\n//go:noinline\nfunc caller4(entry *logrus.Entry) { caller3(entry) }\n\n//go:noinline\nfunc caller3(entry *logrus.Entry) { caller2(entry) }\n\n//go:noinline\nfunc caller2(entry *logrus.Entry) { caller1(entry) }\n\n//go:noinline\nfunc caller1(entry *logrus.Entry) { entry.Info(\"test message\") }\n\n// benchmarkEntryReportCallerDepth4 simulates a wrapper call site.\n// It does not increase getCaller() scan depth (which stops at the first\n// non-logrus frame), but ensures ReportCaller overhead is stable with\n// wrapper layers.\nfunc benchmarkEntryReportCallerDepth4(b *testing.B, reportCaller bool) {\n\t// JSONFormatter is used intentionally to measure realistic end-to-end\n\t// ReportCaller overhead (Entry.log + caller field formatting),\n\t// not getCaller() in isolation.\n\tlogger := logrus.New()\n\tlogger.SetFormatter(&logrus.JSONFormatter{})\n\tlogger.SetReportCaller(reportCaller)\n\tlogger.SetLevel(logrus.InfoLevel)\n\tlogger.SetOutput(io.Discard)\n\n\tentry := logrus.NewEntry(logger)\n\n\t// getCaller has a package-level sync.Once; exclude initialization from the benchmark.\n\tentry.Info(\"warmup\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor range b.N {\n\t\tcaller4(entry)\n\t}\n}\n\nfunc BenchmarkEntry_ReportCaller_NoCaller_Depth4(b *testing.B) {\n\tbenchmarkEntryReportCallerDepth4(b, false)\n}\n\nfunc BenchmarkEntry_ReportCaller_WithCaller_Depth4(b *testing.B) {\n\tbenchmarkEntryReportCallerDepth4(b, true)\n}\n"
  },
  {
    "path": "entry_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype contextKeyType string\n\nfunc TestEntryWithError(t *testing.T) {\n\texpErr := fmt.Errorf(\"kaboom at layer %d\", 4711)\n\tassert.Equal(t, expErr, logrus.WithError(expErr).Data[\"error\"])\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\n\tassert.Equal(t, expErr, entry.WithError(expErr).Data[\"error\"])\n\n\ttmpKey := logrus.ErrorKey\n\tlogrus.ErrorKey = \"err\" //nolint:reassign // ignore \"reassigning variable ErrorKey in other package logrus (reassign)\"\n\tt.Cleanup(func() {\n\t\tlogrus.ErrorKey = tmpKey //nolint:reassign // ignore \"reassigning variable ErrorKey in other package logrus (reassign)\"\n\t})\n\n\tassert.Equal(t, expErr, entry.WithError(expErr).Data[\"err\"])\n}\n\nfunc TestEntryWithContext(t *testing.T) {\n\tassert := assert.New(t)\n\tvar contextKey contextKeyType = \"foo\"\n\tctx := context.WithValue(context.Background(), contextKey, \"bar\")\n\n\tassert.Equal(ctx, logrus.WithContext(ctx).Context)\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\n\tassert.Equal(ctx, entry.WithContext(ctx).Context)\n}\n\nfunc TestEntryWithContextCopiesData(t *testing.T) {\n\tassert := assert.New(t)\n\n\t// Initialize a parent Entry object with a key/value set in its Data map\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tparentEntry := logrus.NewEntry(logger).WithField(\"parentKey\", \"parentValue\")\n\n\t// Create two children Entry objects from the parent in different contexts\n\tvar contextKey1 contextKeyType = \"foo\"\n\tctx1 := context.WithValue(context.Background(), contextKey1, \"bar\")\n\tchildEntry1 := parentEntry.WithContext(ctx1)\n\tassert.Equal(ctx1, childEntry1.Context)\n\n\tvar contextKey2 contextKeyType = \"bar\"\n\tctx2 := context.WithValue(context.Background(), contextKey2, \"baz\")\n\tchildEntry2 := parentEntry.WithContext(ctx2)\n\tassert.Equal(ctx2, childEntry2.Context)\n\tassert.NotEqual(ctx1, ctx2)\n\n\t// Ensure that data set in the parent Entry are preserved to both children\n\tassert.Equal(\"parentValue\", childEntry1.Data[\"parentKey\"])\n\tassert.Equal(\"parentValue\", childEntry2.Data[\"parentKey\"])\n\n\t// Modify data stored in the child entry\n\tchildEntry1.Data[\"childKey\"] = \"childValue\"\n\n\t// Verify that data is successfully stored in the child it was set on\n\tval, exists := childEntry1.Data[\"childKey\"]\n\tassert.True(exists)\n\tassert.Equal(\"childValue\", val)\n\n\t// Verify that the data change to child 1 has not affected its sibling\n\tval, exists = childEntry2.Data[\"childKey\"]\n\tassert.False(exists)\n\tassert.Empty(val)\n\n\t// Verify that the data change to child 1 has not affected its parent\n\tval, exists = parentEntry.Data[\"childKey\"]\n\tassert.False(exists)\n\tassert.Empty(val)\n}\n\nfunc TestEntryWithTimeCopiesData(t *testing.T) {\n\tassert := assert.New(t)\n\n\t// Initialize a parent Entry object with a key/value set in its Data map\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tparentEntry := logrus.NewEntry(logger).WithField(\"parentKey\", \"parentValue\")\n\n\t// Create two children Entry objects from the parent with two different times\n\tchildEntry1 := parentEntry.WithTime(time.Now().AddDate(0, 0, 1))\n\tchildEntry2 := parentEntry.WithTime(time.Now().AddDate(0, 0, 2))\n\n\t// Ensure that data set in the parent Entry are preserved to both children\n\tassert.Equal(\"parentValue\", childEntry1.Data[\"parentKey\"])\n\tassert.Equal(\"parentValue\", childEntry2.Data[\"parentKey\"])\n\n\t// Modify data stored in the child entry\n\tchildEntry1.Data[\"childKey\"] = \"childValue\"\n\n\t// Verify that data is successfully stored in the child it was set on\n\tval, exists := childEntry1.Data[\"childKey\"]\n\tassert.True(exists)\n\tassert.Equal(\"childValue\", val)\n\n\t// Verify that the data change to child 1 has not affected its sibling\n\tval, exists = childEntry2.Data[\"childKey\"]\n\tassert.False(exists)\n\tassert.Empty(val)\n\n\t// Verify that the data change to child 1 has not affected its parent\n\tval, exists = parentEntry.Data[\"childKey\"]\n\tassert.False(exists)\n\tassert.Empty(val)\n}\n\nfunc TestEntryPanicln(t *testing.T) {\n\terrBoom := fmt.Errorf(\"boom time\")\n\n\tdefer func() {\n\t\tp := recover()\n\t\tassert.NotNil(t, p)\n\n\t\tswitch pVal := p.(type) {\n\t\tcase *logrus.Entry:\n\t\t\tassert.Equal(t, \"kaboom\", pVal.Message)\n\t\t\tassert.Equal(t, errBoom, pVal.Data[\"err\"])\n\t\tdefault:\n\t\t\tt.Fatalf(\"want type *Entry, got %T: %#v\", pVal, pVal)\n\t\t}\n\t}()\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\tentry.WithField(\"err\", errBoom).Panicln(\"kaboom\")\n}\n\nfunc TestEntryPanicf(t *testing.T) {\n\terrBoom := fmt.Errorf(\"boom again\")\n\n\tdefer func() {\n\t\tp := recover()\n\t\tassert.NotNil(t, p)\n\n\t\tswitch pVal := p.(type) {\n\t\tcase *logrus.Entry:\n\t\t\tassert.Equal(t, \"kaboom true\", pVal.Message)\n\t\t\tassert.Equal(t, errBoom, pVal.Data[\"err\"])\n\t\tdefault:\n\t\t\tt.Fatalf(\"want type *Entry, got %T: %#v\", pVal, pVal)\n\t\t}\n\t}()\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\tentry.WithField(\"err\", errBoom).Panicf(\"kaboom %v\", true)\n}\n\nfunc TestEntryPanic(t *testing.T) {\n\terrBoom := fmt.Errorf(\"boom again\")\n\n\tdefer func() {\n\t\tp := recover()\n\t\tassert.NotNil(t, p)\n\n\t\tswitch pVal := p.(type) {\n\t\tcase *logrus.Entry:\n\t\t\tassert.Equal(t, \"kaboom\", pVal.Message)\n\t\t\tassert.Equal(t, errBoom, pVal.Data[\"err\"])\n\t\tdefault:\n\t\t\tt.Fatalf(\"want type *Entry, got %T: %#v\", pVal, pVal)\n\t\t}\n\t}()\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\tentry.WithField(\"err\", errBoom).Panic(\"kaboom\")\n}\n\nconst (\n\tbadMessage   = \"this is going to panic\"\n\tpanicMessage = \"this is broken\"\n)\n\ntype panickyHook struct{}\n\nfunc (p *panickyHook) Levels() []logrus.Level {\n\treturn []logrus.Level{logrus.InfoLevel}\n}\n\nfunc (p *panickyHook) Fire(entry *logrus.Entry) error {\n\tif entry.Message == badMessage {\n\t\tpanic(panicMessage)\n\t}\n\n\treturn nil\n}\n\nfunc TestEntryHooksPanic(t *testing.T) {\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tlogger.SetLevel(logrus.InfoLevel)\n\tlogger.AddHook(&panickyHook{})\n\n\tdefer func() {\n\t\tp := recover()\n\t\tassert.NotNil(t, p)\n\t\tassert.Equal(t, panicMessage, p)\n\n\t\tentry := logrus.NewEntry(logger)\n\t\tentry.Info(\"another message\")\n\t}()\n\n\tentry := logrus.NewEntry(logger)\n\tentry.Info(badMessage)\n}\n\nfunc TestEntryWithIncorrectField(t *testing.T) {\n\tlogger := logrus.New()\n\tlogger.SetFormatter(&logrus.JSONFormatter{})\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\n\tfn := func() {}\n\teWithFunc := entry.WithFields(logrus.Fields{\"func\": fn})\n\teWithFuncPtr := entry.WithFields(logrus.Fields{\"funcPtr\": &fn})\n\n\tassert.Equal(t, `can not add field \"func\"`, getErr(t, eWithFunc))\n\tassert.Equal(t, `can not add field \"funcPtr\"`, getErr(t, eWithFuncPtr))\n\n\teWithFunc = eWithFunc.WithField(\"not_a_func\", \"it is a string\")\n\teWithFuncPtr = eWithFuncPtr.WithField(\"not_a_func\", \"it is a string\")\n\n\tassert.Equal(t, `can not add field \"func\"`, getErr(t, eWithFunc))\n\tassert.Equal(t, `can not add field \"funcPtr\"`, getErr(t, eWithFuncPtr))\n\n\teWithFunc = eWithFunc.WithTime(time.Now())\n\teWithFuncPtr = eWithFuncPtr.WithTime(time.Now())\n\n\tassert.Equal(t, `can not add field \"func\"`, getErr(t, eWithFunc))\n\tassert.Equal(t, `can not add field \"funcPtr\"`, getErr(t, eWithFuncPtr))\n}\n\nfunc getErr(t *testing.T, e *logrus.Entry) string {\n\tt.Helper()\n\n\tout, err := e.String()\n\trequire.NoError(t, err)\n\n\tvar m map[string]any\n\trequire.NoError(t, json.Unmarshal([]byte(out), &m))\n\n\tgot, _ := m[logrus.FieldKeyLogrusError].(string)\n\treturn got\n}\n\nfunc TestEntryLogfLevel(t *testing.T) {\n\tvar buffer bytes.Buffer\n\tlogger := logrus.New()\n\tlogger.SetOutput(&buffer)\n\tlogger.SetLevel(logrus.InfoLevel)\n\tentry := logrus.NewEntry(logger)\n\n\tentry.Logf(logrus.DebugLevel, \"%s\", \"debug\")\n\tassert.NotContains(t, buffer.String(), \"debug\")\n\n\tentry.Logf(logrus.WarnLevel, \"%s\", \"warn\")\n\tassert.Contains(t, buffer.String(), \"warn\")\n}\n\nfunc TestEntryLoggerMutationRace(t *testing.T) {\n\ttests := []struct {\n\t\tdoc    string\n\t\tmutate func(*logrus.Logger)\n\t}{\n\t\t{doc: \"AddHook\", mutate: func(l *logrus.Logger) { l.AddHook(noopHook{}) }},\n\t\t{doc: \"SetBufferPool\", mutate: func(l *logrus.Logger) { l.SetBufferPool(nopBufferPool{}) }},\n\t\t{doc: \"SetFormatter\", mutate: func(l *logrus.Logger) { l.SetFormatter(&logrus.TextFormatter{}) }},\n\t\t{doc: \"SetLevel\", mutate: func(l *logrus.Logger) { l.SetLevel(logrus.InfoLevel) }},\n\t\t{doc: \"SetOutput\", mutate: func(l *logrus.Logger) { l.SetOutput(io.Discard) }},\n\t\t{doc: \"SetReportCaller\", mutate: func(l *logrus.Logger) { l.SetReportCaller(true) }},\n\t\t{doc: \"ReplaceHooks_withHookPresent\", mutate: func(l *logrus.Logger) {\n\t\t\t// Replace with a fresh map each time to maximize mutation.\n\t\t\th := make(logrus.LevelHooks)\n\t\t\tfor _, lvl := range logrus.AllLevels {\n\t\t\t\th[lvl] = []logrus.Hook{noopHook{}}\n\t\t\t}\n\t\t\tl.ReplaceHooks(h)\n\t\t}},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.doc, func(t *testing.T) {\n\t\t\trunEntryLoggerRace(t, tc.mutate)\n\t\t})\n\t}\n}\n\ntype noopHook struct{}\n\nfunc (noopHook) Levels() []logrus.Level   { return logrus.AllLevels }\nfunc (noopHook) Fire(*logrus.Entry) error { return nil }\n\ntype nopBufferPool struct{}\n\nfunc (nopBufferPool) Get() *bytes.Buffer { return new(bytes.Buffer) }\nfunc (nopBufferPool) Put(*bytes.Buffer)  {}\n\nfunc runEntryLoggerRace(t *testing.T, mutate func(logger *logrus.Logger)) {\n\tt.Helper()\n\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\tentry := logrus.NewEntry(logger)\n\n\tconst n = 100\n\n\tvar wg sync.WaitGroup\n\twg.Add(4)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor range n {\n\t\t\t_, _ = entry.Bytes()\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor range n {\n\t\t\tentry.Info(\"should not race\")\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor range n {\n\t\t\tmutate(logger)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor range n {\n\t\t\tentry.Info(\"should not race\")\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\n// reentrantValue is a type whose MarshalJSON method triggers another log call,\n// which would deadlock if the logger mutex is held during formatting.\ntype reentrantValue struct {\n\tlogger *logrus.Logger\n}\n\nfunc (r reentrantValue) MarshalJSON() ([]byte, error) {\n\tr.logger.Info(\"reentrant log from MarshalJSON\")\n\treturn []byte(`\"reentrant\"`), nil\n}\n\n// TestEntryReentrantLoggingDeadlock verifies that logging from within a field's\n// MarshalJSON (or similar serialization callback) does not deadlock.\n// This is a regression test for https://github.com/sirupsen/logrus/issues/1448.\nfunc TestEntryReentrantLoggingDeadlock(t *testing.T) {\n\tvar buf bytes.Buffer\n\tlogger := logrus.New()\n\tlogger.SetOutput(&buf)\n\tlogger.SetFormatter(&logrus.JSONFormatter{})\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"key\": reentrantValue{logger: logger},\n\t\t}).Info(\"outer log message\")\n\t}()\n\n\tselect {\n\tcase <-done:\n\t\t// Success: the log call completed without deadlocking.\n\t\toutput := buf.String()\n\t\tassert.Contains(t, output, \"outer log message\")\n\t\tassert.Contains(t, output, \"reentrant log from MarshalJSON\")\n\t\tassert.Contains(t, output, `\"key\":\"reentrant\"`)\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatal(\"deadlock detected: reentrant logging from MarshalJSON blocked for 5 seconds\")\n\t}\n}\n"
  },
  {
    "path": "example_basic_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc Example_basic() {\n\tlog := logrus.New()\n\tlog.Formatter = new(logrus.JSONFormatter)\n\tlog.Formatter = new(logrus.TextFormatter)                     // default\n\tlog.Formatter.(*logrus.TextFormatter).DisableColors = true    // remove colors\n\tlog.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output\n\tlog.Level = logrus.TraceLevel\n\tlog.Out = os.Stdout\n\n\t// file, err := os.OpenFile(\"logrus.log\", os.O_CREATE|os.O_WRONLY, 0666)\n\t// if err == nil {\n\t// \tlog.Out = file\n\t// } else {\n\t// \tlog.Info(\"Failed to log to file, using default stderr\")\n\t// }\n\n\tdefer func() {\n\t\terr := recover()\n\t\tif err != nil {\n\t\t\tentry := err.(*logrus.Entry)\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"omg\":         true,\n\t\t\t\t\"err_animal\":  entry.Data[\"animal\"],\n\t\t\t\t\"err_size\":    entry.Data[\"size\"],\n\t\t\t\t\"err_level\":   entry.Level,\n\t\t\t\t\"err_message\": entry.Message,\n\t\t\t\t\"number\":      100,\n\t\t\t}).Error(\"The ice breaks!\") // or use Fatal() to force the process to exit with a nonzero code\n\t\t}\n\t}()\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"animal\": \"walrus\",\n\t\t\"number\": 0,\n\t}).Trace(\"Went to the beach\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"animal\": \"walrus\",\n\t\t\"number\": 8,\n\t}).Debug(\"Started observing beach\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"animal\": \"walrus\",\n\t\t\"size\":   10,\n\t}).Info(\"A group of walrus emerges from the ocean\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"omg\":    true,\n\t\t\"number\": 122,\n\t}).Warn(\"The group's number increased tremendously!\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"temperature\": -4,\n\t}).Debug(\"Temperature changes\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"animal\": \"orca\",\n\t\t\"size\":   9009,\n\t}).Panic(\"It's over 9000!\")\n\n\t// Output:\n\t// level=trace msg=\"Went to the beach\" animal=walrus number=0\n\t// level=debug msg=\"Started observing beach\" animal=walrus number=8\n\t// level=info msg=\"A group of walrus emerges from the ocean\" animal=walrus size=10\n\t// level=warning msg=\"The group's number increased tremendously!\" number=122 omg=true\n\t// level=debug msg=\"Temperature changes\" temperature=-4\n\t// level=panic msg=\"It's over 9000!\" animal=orca size=9009\n\t// 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\n}\n"
  },
  {
    "path": "example_custom_caller_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc ExampleJSONFormatter_CallerPrettyfier() {\n\tl := logrus.New()\n\tl.SetReportCaller(true)\n\tl.Out = os.Stdout\n\tl.Formatter = &logrus.JSONFormatter{\n\t\tDisableTimestamp: true,\n\t\tCallerPrettyfier: func(f *runtime.Frame) (string, string) {\n\t\t\ts := strings.Split(f.Function, \".\")\n\t\t\tfuncname := s[len(s)-1]\n\t\t\t_, filename := path.Split(f.File)\n\t\t\treturn funcname, filename\n\t\t},\n\t}\n\tl.Info(\"example of custom format caller\")\n\t// Output:\n\t// {\"file\":\"example_custom_caller_test.go\",\"func\":\"ExampleJSONFormatter_CallerPrettyfier\",\"level\":\"info\",\"msg\":\"example of custom format caller\"}\n}\n"
  },
  {
    "path": "example_default_field_value_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype DefaultFieldHook struct {\n\tGetValue func() string\n}\n\nfunc (h *DefaultFieldHook) Levels() []logrus.Level {\n\treturn logrus.AllLevels\n}\n\nfunc (h *DefaultFieldHook) Fire(e *logrus.Entry) error {\n\te.Data[\"aDefaultField\"] = h.GetValue()\n\treturn nil\n}\n\nfunc ExampleDefaultFieldHook() {\n\tl := logrus.New()\n\tl.Out = os.Stdout\n\tl.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}\n\n\tl.AddHook(&DefaultFieldHook{GetValue: func() string { return \"with its default value\" }})\n\tl.Info(\"first log\")\n\t// Output:\n\t// level=info msg=\"first log\" aDefaultField=\"with its default value\"\n}\n"
  },
  {
    "path": "example_function_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestLogger_LogFn(t *testing.T) {\n\tlog := logrus.New()\n\tlog.SetOutput(io.Discard)\n\tlog.SetFormatter(&logrus.JSONFormatter{})\n\tlog.SetLevel(logrus.WarnLevel)\n\n\tnotCalled := 0\n\tlog.InfoFn(func() []any {\n\t\tnotCalled++\n\t\treturn []any{\n\t\t\t\"Hello\",\n\t\t}\n\t})\n\tassert.Equal(t, 0, notCalled)\n\n\tcalled := 0\n\tlog.ErrorFn(func() []any {\n\t\tcalled++\n\t\treturn []any{\n\t\t\t\"Oopsi\",\n\t\t}\n\t})\n\tassert.Equal(t, 1, called)\n}\n"
  },
  {
    "path": "example_global_hook_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar mystring string\n\ntype GlobalHook struct{}\n\nfunc (h *GlobalHook) Levels() []logrus.Level {\n\treturn logrus.AllLevels\n}\n\nfunc (h *GlobalHook) Fire(e *logrus.Entry) error {\n\te.Data[\"mystring\"] = mystring\n\treturn nil\n}\n\nfunc ExampleGlobalHook() {\n\tl := logrus.New()\n\tl.Out = os.Stdout\n\tl.Formatter = &logrus.TextFormatter{DisableTimestamp: true, DisableColors: true}\n\tl.AddHook(&GlobalHook{})\n\tmystring = \"first value\"\n\tl.Info(\"first log\")\n\tmystring = \"another value\"\n\tl.Info(\"second log\")\n\t// Output:\n\t// level=info msg=\"first log\" mystring=\"first value\"\n\t// level=info msg=\"second log\" mystring=\"another value\"\n}\n"
  },
  {
    "path": "example_hook_test.go",
    "content": "//go:build !windows\n\npackage logrus_test\n\nimport (\n\t\"log/syslog\"\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n\tslhooks \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\n// An example on how to use a hook\nfunc Example_hook() {\n\tlog := logrus.New()\n\tlog.Formatter = new(logrus.TextFormatter)                     // default\n\tlog.Formatter.(*logrus.TextFormatter).DisableColors = true    // remove colors\n\tlog.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output\n\tif sl, err := slhooks.NewSyslogHook(\"udp\", \"localhost:514\", syslog.LOG_INFO, \"\"); err == nil {\n\t\tlog.Hooks.Add(sl)\n\t}\n\tlog.Out = os.Stdout\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"animal\": \"walrus\",\n\t\t\"size\":   10,\n\t}).Info(\"A group of walrus emerges from the ocean\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"omg\":    true,\n\t\t\"number\": 122,\n\t}).Warn(\"The group's number increased tremendously!\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"omg\":    true,\n\t\t\"number\": 100,\n\t}).Error(\"The ice breaks!\")\n\n\t// Output:\n\t// level=info msg=\"A group of walrus emerges from the ocean\" animal=walrus size=10\n\t// level=warning msg=\"The group's number increased tremendously!\" number=122 omg=true\n\t// level=error msg=\"The ice breaks!\" number=100 omg=true\n}\n"
  },
  {
    "path": "exported.go",
    "content": "package logrus\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"time\"\n)\n\n// std is the package-level standard logger, similar to the default logger\n// in the stdlib [log] package.\nvar std = New()\n\nfunc StandardLogger() *Logger {\n\treturn std\n}\n\n// SetOutput sets the standard logger output.\nfunc SetOutput(out io.Writer) {\n\tstd.SetOutput(out)\n}\n\n// SetFormatter sets the standard logger formatter.\nfunc SetFormatter(formatter Formatter) {\n\tstd.SetFormatter(formatter)\n}\n\n// SetReportCaller sets whether the standard logger will include the calling\n// method as a field.\nfunc SetReportCaller(include bool) {\n\tstd.SetReportCaller(include)\n}\n\n// SetLevel sets the standard logger level.\nfunc SetLevel(level Level) {\n\tstd.SetLevel(level)\n}\n\n// GetLevel returns the standard logger level.\nfunc GetLevel() Level {\n\treturn std.GetLevel()\n}\n\n// IsLevelEnabled checks if logging for the given level is enabled for the standard logger.\nfunc IsLevelEnabled(level Level) bool {\n\treturn std.IsLevelEnabled(level)\n}\n\n// AddHook adds a hook to the standard logger hooks.\nfunc AddHook(hook Hook) {\n\tstd.AddHook(hook)\n}\n\n// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.\nfunc WithError(err error) *Entry {\n\treturn std.WithField(ErrorKey, err)\n}\n\n// WithContext creates an entry from the standard logger and adds a context to it.\nfunc WithContext(ctx context.Context) *Entry {\n\treturn std.WithContext(ctx)\n}\n\n// WithField creates an entry from the standard logger and adds a field to\n// it. If you want multiple fields, use `WithFields`.\n//\n// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal\n// or Panic on the Entry it returns.\nfunc WithField(key string, value any) *Entry {\n\treturn std.WithField(key, value)\n}\n\n// WithFields creates an entry from the standard logger and adds multiple\n// fields to it. This is simply a helper for `WithField`, invoking it\n// once for each field.\n//\n// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal\n// or Panic on the Entry it returns.\nfunc WithFields(fields Fields) *Entry {\n\treturn std.WithFields(fields)\n}\n\n// WithTime creates an entry from the standard logger and overrides the time of\n// logs generated with it.\n//\n// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal\n// or Panic on the Entry it returns.\nfunc WithTime(t time.Time) *Entry {\n\treturn std.WithTime(t)\n}\n\n// Trace logs a message at level Trace on the standard logger.\nfunc Trace(args ...any) {\n\tstd.Trace(args...)\n}\n\n// Debug logs a message at level Debug on the standard logger.\nfunc Debug(args ...any) {\n\tstd.Debug(args...)\n}\n\n// Print logs a message at level Info on the standard logger.\nfunc Print(args ...any) {\n\tstd.Print(args...)\n}\n\n// Info logs a message at level Info on the standard logger.\nfunc Info(args ...any) {\n\tstd.Info(args...)\n}\n\n// Warn logs a message at level Warn on the standard logger.\nfunc Warn(args ...any) {\n\tstd.Warn(args...)\n}\n\n// Warning logs a message at level Warn on the standard logger.\nfunc Warning(args ...any) {\n\tstd.Warning(args...)\n}\n\n// Error logs a message at level Error on the standard logger.\nfunc Error(args ...any) {\n\tstd.Error(args...)\n}\n\n// Panic logs a message at level Panic on the standard logger.\nfunc Panic(args ...any) {\n\tstd.Panic(args...)\n}\n\n// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.\nfunc Fatal(args ...any) {\n\tstd.Fatal(args...)\n}\n\n// TraceFn logs a message from a func at level Trace on the standard logger.\nfunc TraceFn(fn LogFunction) {\n\tstd.TraceFn(fn)\n}\n\n// DebugFn logs a message from a func at level Debug on the standard logger.\nfunc DebugFn(fn LogFunction) {\n\tstd.DebugFn(fn)\n}\n\n// PrintFn logs a message from a func at level Info on the standard logger.\nfunc PrintFn(fn LogFunction) {\n\tstd.PrintFn(fn)\n}\n\n// InfoFn logs a message from a func at level Info on the standard logger.\nfunc InfoFn(fn LogFunction) {\n\tstd.InfoFn(fn)\n}\n\n// WarnFn logs a message from a func at level Warn on the standard logger.\nfunc WarnFn(fn LogFunction) {\n\tstd.WarnFn(fn)\n}\n\n// WarningFn logs a message from a func at level Warn on the standard logger.\nfunc WarningFn(fn LogFunction) {\n\tstd.WarningFn(fn)\n}\n\n// ErrorFn logs a message from a func at level Error on the standard logger.\nfunc ErrorFn(fn LogFunction) {\n\tstd.ErrorFn(fn)\n}\n\n// PanicFn logs a message from a func at level Panic on the standard logger.\nfunc PanicFn(fn LogFunction) {\n\tstd.PanicFn(fn)\n}\n\n// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.\nfunc FatalFn(fn LogFunction) {\n\tstd.FatalFn(fn)\n}\n\n// Tracef logs a message at level Trace on the standard logger.\nfunc Tracef(format string, args ...any) {\n\tstd.Tracef(format, args...)\n}\n\n// Debugf logs a message at level Debug on the standard logger.\nfunc Debugf(format string, args ...any) {\n\tstd.Debugf(format, args...)\n}\n\n// Printf logs a message at level Info on the standard logger.\nfunc Printf(format string, args ...any) {\n\tstd.Printf(format, args...)\n}\n\n// Infof logs a message at level Info on the standard logger.\nfunc Infof(format string, args ...any) {\n\tstd.Infof(format, args...)\n}\n\n// Warnf logs a message at level Warn on the standard logger.\nfunc Warnf(format string, args ...any) {\n\tstd.Warnf(format, args...)\n}\n\n// Warningf logs a message at level Warn on the standard logger.\nfunc Warningf(format string, args ...any) {\n\tstd.Warningf(format, args...)\n}\n\n// Errorf logs a message at level Error on the standard logger.\nfunc Errorf(format string, args ...any) {\n\tstd.Errorf(format, args...)\n}\n\n// Panicf logs a message at level Panic on the standard logger.\nfunc Panicf(format string, args ...any) {\n\tstd.Panicf(format, args...)\n}\n\n// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.\nfunc Fatalf(format string, args ...any) {\n\tstd.Fatalf(format, args...)\n}\n\n// Traceln logs a message at level Trace on the standard logger.\nfunc Traceln(args ...any) {\n\tstd.Traceln(args...)\n}\n\n// Debugln logs a message at level Debug on the standard logger.\nfunc Debugln(args ...any) {\n\tstd.Debugln(args...)\n}\n\n// Println logs a message at level Info on the standard logger.\nfunc Println(args ...any) {\n\tstd.Println(args...)\n}\n\n// Infoln logs a message at level Info on the standard logger.\nfunc Infoln(args ...any) {\n\tstd.Infoln(args...)\n}\n\n// Warnln logs a message at level Warn on the standard logger.\nfunc Warnln(args ...any) {\n\tstd.Warnln(args...)\n}\n\n// Warningln logs a message at level Warn on the standard logger.\nfunc Warningln(args ...any) {\n\tstd.Warningln(args...)\n}\n\n// Errorln logs a message at level Error on the standard logger.\nfunc Errorln(args ...any) {\n\tstd.Errorln(args...)\n}\n\n// Panicln logs a message at level Panic on the standard logger.\nfunc Panicln(args ...any) {\n\tstd.Panicln(args...)\n}\n\n// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.\nfunc Fatalln(args ...any) {\n\tstd.Fatalln(args...)\n}\n"
  },
  {
    "path": "formatter.go",
    "content": "package logrus\n\nimport \"time\"\n\nconst (\n\t// defaultTimestampFormat is the layout used to format entry timestamps\n\t// when a formatter has not specified a custom TimestampFormat.\n\t// It follows time.RFC3339 and is applied unless timestamps are disabled.\n\tdefaultTimestampFormat = time.RFC3339\n\n\t// defaultFields is the number of commonly included predefined log entry fields\n\t// (msg, level, time). It is used as a capacity hint when constructing\n\t// intermediate collections during formatting (for example, the fixed key list).\n\t//\n\t// It does not include the optional \"logrus_error\", \"func\", or \"file\" fields.\n\tdefaultFields = 3\n)\n\n// Default key names for the default fields\nconst (\n\tFieldKeyMsg         = \"msg\"\n\tFieldKeyLevel       = \"level\"\n\tFieldKeyTime        = \"time\"\n\tFieldKeyLogrusError = \"logrus_error\"\n\tFieldKeyFunc        = \"func\"\n\tFieldKeyFile        = \"file\"\n)\n\n// The Formatter interface is used to implement a custom Formatter. It takes an\n// `Entry`. It exposes all the fields, including the default ones:\n//\n// * `entry.Data[\"msg\"]`. The message passed from Info, Warn, Error ..\n// * `entry.Data[\"time\"]`. The timestamp.\n// * `entry.Data[\"level\"]. The level the entry was logged at.\n//\n// Any additional fields added with `WithField` or `WithFields` are also in\n// `entry.Data`. Format is expected to return an array of bytes which are then\n// logged to `logger.Out`.\ntype Formatter interface {\n\tFormat(*Entry) ([]byte, error)\n}\n\n// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when\n// dumping it. If this code wasn't there doing:\n//\n//\tlogrus.WithField(\"level\", 1).Info(\"hello\")\n//\n// Would just silently drop the user provided level. Instead with this code\n// it'll logged as:\n//\n//\t{\"level\": \"info\", \"fields.level\": 1, \"msg\": \"hello\", \"time\": \"...\"}\n//\n// It's not exported because it's still using Data in an opinionated way. It's to\n// avoid code duplication between the two default formatters.\nfunc prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) {\n\ttimeKey := fieldMap.resolve(FieldKeyTime)\n\tif t, ok := data[timeKey]; ok {\n\t\tdata[\"fields.\"+timeKey] = t\n\t\tdelete(data, timeKey)\n\t}\n\n\tmsgKey := fieldMap.resolve(FieldKeyMsg)\n\tif m, ok := data[msgKey]; ok {\n\t\tdata[\"fields.\"+msgKey] = m\n\t\tdelete(data, msgKey)\n\t}\n\n\tlevelKey := fieldMap.resolve(FieldKeyLevel)\n\tif l, ok := data[levelKey]; ok {\n\t\tdata[\"fields.\"+levelKey] = l\n\t\tdelete(data, levelKey)\n\t}\n\n\tlogrusErrKey := fieldMap.resolve(FieldKeyLogrusError)\n\tif l, ok := data[logrusErrKey]; ok {\n\t\tdata[\"fields.\"+logrusErrKey] = l\n\t\tdelete(data, logrusErrKey)\n\t}\n\n\t// If reportCaller is not set, 'func' will not conflict.\n\tif reportCaller {\n\t\tfuncKey := fieldMap.resolve(FieldKeyFunc)\n\t\tif l, ok := data[funcKey]; ok {\n\t\t\tdata[\"fields.\"+funcKey] = l\n\t\t}\n\t\tfileKey := fieldMap.resolve(FieldKeyFile)\n\t\tif l, ok := data[fileKey]; ok {\n\t\t\tdata[\"fields.\"+fileKey] = l\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "formatter_bench_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\ntype benchStringer string\n\nfunc (s benchStringer) String() string { return string(s) }\n\nvar numericFields = logrus.Fields{\n\t\"i\":   int(42),\n\t\"i64\": int64(-1234567890),\n\t\"u\":   uint(99),\n\t\"u64\": uint64(18446744073709551615),\n\t\"f32\": float32(3.1415927),\n\t\"f64\": float64(-1.2345e6),\n}\n\nvar boolFields = logrus.Fields{\n\t\"t\":   true,\n\t\"f\":   false,\n\t\"x\":   true,\n\t\"y\":   false,\n\t\"yes\": true,\n\t\"no\":  false,\n}\n\nvar stringerFields = logrus.Fields{\n\t\"s1\": benchStringer(\"alpha\"),\n\t\"s2\": benchStringer(\"beta\"),\n\t\"s3\": benchStringer(\"gamma-delta\"), // includes '-' (still unquoted)\n\t\"s4\": benchStringer(\"needs quote\"), // includes space -> quoted path\n\t\"s5\": benchStringer(`needs \"quote\"`),\n\t\"s6\": benchStringer(`needs 'quote'`),\n}\n\n// smallFields is a small size data set for benchmarking\nvar smallFields = logrus.Fields{\n\t\"foo\":   \"bar\",\n\t\"baz\":   \"qux\",\n\t\"one\":   \"two\",\n\t\"three\": \"four\",\n}\n\n// largeFields is a large size data set for benchmarking\nvar largeFields = logrus.Fields{\n\t\"foo\":       \"bar\",\n\t\"baz\":       \"qux\",\n\t\"one\":       \"two\",\n\t\"three\":     \"four\",\n\t\"five\":      \"six\",\n\t\"seven\":     \"eight\",\n\t\"nine\":      \"ten\",\n\t\"eleven\":    \"twelve\",\n\t\"thirteen\":  \"fourteen\",\n\t\"fifteen\":   \"sixteen\",\n\t\"seventeen\": \"eighteen\",\n\t\"nineteen\":  \"twenty\",\n\t\"a\":         \"b\",\n\t\"c\":         \"d\",\n\t\"e\":         \"f\",\n\t\"g\":         \"h\",\n\t\"i\":         \"j\",\n\t\"k\":         \"l\",\n\t\"m\":         \"n\",\n\t\"o\":         \"p\",\n\t\"q\":         \"r\",\n\t\"s\":         \"t\",\n\t\"u\":         \"v\",\n\t\"w\":         \"x\",\n\t\"y\":         \"z\",\n\t\"this\":      \"will\",\n\t\"make\":      \"thirty\",\n\t\"entries\":   \"yeah\",\n}\n\nvar errorFields = logrus.Fields{\n\t\"foo\": fmt.Errorf(\"bar\"),\n\t\"baz\": fmt.Errorf(\"qux\"),\n}\n\nfunc BenchmarkZeroTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{})\n}\n\nfunc BenchmarkOneStringTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{\"foo\": \"bar\"})\n}\n\nfunc BenchmarkOneNumericTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{\"i\": int(42)})\n}\n\nfunc BenchmarkOneBoolTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, logrus.Fields{\"t\": true})\n}\n\nfunc BenchmarkNumericTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, numericFields)\n}\n\nfunc BenchmarkBoolTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, boolFields)\n}\n\nfunc BenchmarkStringerTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, stringerFields)\n}\n\nfunc BenchmarkErrorTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, errorFields)\n}\n\nfunc BenchmarkSmallTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc BenchmarkLargeTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{DisableColors: true}, largeFields)\n}\n\nfunc BenchmarkSmallColoredTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{ForceColors: true}, smallFields)\n}\n\nfunc BenchmarkLargeColoredTextFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.TextFormatter{ForceColors: true}, largeFields)\n}\n\nfunc BenchmarkSmallJSONFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.JSONFormatter{}, smallFields)\n}\n\nfunc BenchmarkLargeJSONFormatter(b *testing.B) {\n\tdoBenchmark(b, &logrus.JSONFormatter{}, largeFields)\n}\n\nvar sink []byte\n\nfunc doBenchmark(b *testing.B, formatter logrus.Formatter, fields logrus.Fields) {\n\tlogger := logrus.New()\n\n\tentry := &logrus.Entry{\n\t\tTime:    time.Time{},\n\t\tLevel:   logrus.InfoLevel,\n\t\tMessage: \"message\",\n\t\tData:    fields,\n\t\tLogger:  logger,\n\t}\n\n\t// Warm once to determine output size and validate.\n\td, err := formatter.Format(entry)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tb.SetBytes(int64(len(d)))\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor range b.N {\n\t\td, err = formatter.Format(entry)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n\tsink = d\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/sirupsen/logrus\n\ngo 1.23\n\nrequire (\n\tgithub.com/stretchr/testify v1.10.0\n\tgolang.org/x/sys v0.13.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=\ngithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngolang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=\ngolang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "hook_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"maps\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t. \"github.com/sirupsen/logrus\"\n\t\"github.com/sirupsen/logrus/hooks/test\"\n\t. \"github.com/sirupsen/logrus/internal/testutils\"\n)\n\n// RecordingFormatter is a test helper that implements Formatter and\n// records information about the last formatted Entry.\n//\n// On every call to Format, it increments Calls and stores a shallow copy\n// of entry.Data in EntryData, overwriting any previous value. The formatted\n// output is the raw entry.Message as bytes.\ntype RecordingFormatter struct {\n\tCalls     atomic.Int64\n\tEntryData Fields\n}\n\nfunc (f *RecordingFormatter) Format(entry *Entry) ([]byte, error) {\n\tf.Calls.Add(1)\n\tf.EntryData = maps.Clone(entry.Data)\n\treturn []byte(entry.Message), nil\n}\n\ntype TestHook struct {\n\tFired bool\n}\n\nfunc (hook *TestHook) Fire(entry *Entry) error {\n\thook.Fired = true\n\treturn nil\n}\n\nfunc (hook *TestHook) Levels() []Level {\n\treturn []Level{\n\t\tTraceLevel,\n\t\tDebugLevel,\n\t\tInfoLevel,\n\t\tWarnLevel,\n\t\tErrorLevel,\n\t\tFatalLevel,\n\t\tPanicLevel,\n\t}\n}\n\nfunc TestHookFires(t *testing.T) {\n\thook := new(TestHook)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Hooks.Add(hook)\n\t\tassert.False(t, hook.Fired)\n\n\t\tlog.Print(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.True(t, hook.Fired)\n\t})\n}\n\ntype ModifyHook struct {\n\tCalls atomic.Int64\n}\n\nfunc (hook *ModifyHook) Fire(entry *Entry) error {\n\thook.Calls.Add(1)\n\tentry.Data[\"wow\"] = \"whale\"\n\treturn nil\n}\n\nfunc (hook *ModifyHook) Levels() []Level {\n\treturn []Level{\n\t\tTraceLevel,\n\t\tDebugLevel,\n\t\tInfoLevel,\n\t\tWarnLevel,\n\t\tErrorLevel,\n\t\tFatalLevel,\n\t\tPanicLevel,\n\t}\n}\n\nfunc TestHookCanModifyEntry(t *testing.T) {\n\thook := new(ModifyHook)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Hooks.Add(hook)\n\t\tlog.WithField(\"wow\", \"elephant\").Print(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"whale\", fields[\"wow\"])\n\t})\n}\n\nfunc TestCanFireMultipleHooks(t *testing.T) {\n\thook1 := new(ModifyHook)\n\thook2 := new(TestHook)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Hooks.Add(hook1)\n\t\tlog.Hooks.Add(hook2)\n\n\t\tlog.WithField(\"wow\", \"elephant\").Print(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"whale\", fields[\"wow\"])\n\t\tassert.True(t, hook2.Fired)\n\t})\n}\n\ntype SingleLevelModifyHook struct {\n\tModifyHook\n}\n\nfunc (h *SingleLevelModifyHook) Levels() []Level {\n\treturn []Level{InfoLevel}\n}\n\n// TestHookEntryIsPristine tests that each log gets a pristine copy of Entry,\n// and changes from modifying hooks are not persisted.\n//\n// Regression test for https://github.com/sirupsen/logrus/issues/795\nfunc TestHookEntryIsPristine(t *testing.T) {\n\tformatter := &RecordingFormatter{}\n\thook := &SingleLevelModifyHook{}\n\tl := New()\n\tl.SetOutput(io.Discard)\n\tl.SetFormatter(formatter)\n\tl.AddHook(hook)\n\n\t// Initial message should have a pristine copy of Entry.\n\tl.Error(\"first\")\n\tassert.Equal(t, int64(0), hook.Calls.Load())\n\tassert.Equal(t, int64(1), formatter.Calls.Load())\n\trequire.Empty(t, formatter.EntryData)\n\n\t// Info message modifies data through SingleLevelModifyHook\n\tl.Info(\"second\")\n\tassert.Equal(t, int64(1), hook.Calls.Load())\n\tassert.Equal(t, int64(2), formatter.Calls.Load())\n\trequire.Equal(t, Fields{\"wow\": \"whale\"}, formatter.EntryData)\n\n\t// Should have a pristine copy of Entry.\n\tl.Error(\"third\")\n\tassert.Equal(t, int64(1), hook.Calls.Load())\n\tassert.Equal(t, int64(3), formatter.Calls.Load())\n\trequire.Empty(t, formatter.EntryData)\n}\n\ntype ErrorHook struct {\n\tFired bool\n}\n\nfunc (hook *ErrorHook) Fire(entry *Entry) error {\n\thook.Fired = true\n\treturn nil\n}\n\nfunc (hook *ErrorHook) Levels() []Level {\n\treturn []Level{\n\t\tErrorLevel,\n\t}\n}\n\nfunc TestErrorHookShouldntFireOnInfo(t *testing.T) {\n\thook := new(ErrorHook)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Hooks.Add(hook)\n\t\tlog.Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.False(t, hook.Fired)\n\t})\n}\n\nfunc TestErrorHookShouldFireOnError(t *testing.T) {\n\thook := new(ErrorHook)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Hooks.Add(hook)\n\t\tlog.Error(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.True(t, hook.Fired)\n\t})\n}\n\nfunc TestAddHookRace(t *testing.T) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\thook := new(ErrorHook)\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tlog.AddHook(hook)\n\t\t}()\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tlog.Error(\"test\")\n\t\t}()\n\t\twg.Wait()\n\t}, func(fields Fields) {\n\t\t// the line may have been logged\n\t\t// before the hook was added, so we can't\n\t\t// actually assert on the hook\n\t})\n}\n\nfunc TestAddHookRace2(t *testing.T) {\n\t// Test modifies the standard-logger; restore it afterward.\n\tstdLogger := StandardLogger()\n\toldOut := stdLogger.Out\n\toldHooks := stdLogger.ReplaceHooks(make(LevelHooks))\n\tt.Cleanup(func() {\n\t\tstdLogger.SetOutput(oldOut)\n\t\tstdLogger.ReplaceHooks(oldHooks)\n\t})\n\tstdLogger.SetOutput(io.Discard)\n\n\tfor i := range 3 {\n\t\ttestname := fmt.Sprintf(\"Test %d\", i)\n\t\tt.Run(testname, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\t_ = test.NewGlobal()\n\t\t\tInfo(testname)\n\t\t})\n\t}\n}\n\ntype HookCallFunc struct {\n\tF func()\n}\n\nfunc (h *HookCallFunc) Levels() []Level {\n\treturn AllLevels\n}\n\nfunc (h *HookCallFunc) Fire(e *Entry) error {\n\th.F()\n\treturn nil\n}\n\nfunc TestHookFireOrder(t *testing.T) {\n\tcheckers := []string{}\n\th := LevelHooks{}\n\th.Add(&HookCallFunc{F: func() { checkers = append(checkers, \"first hook\") }})\n\th.Add(&HookCallFunc{F: func() { checkers = append(checkers, \"second hook\") }})\n\th.Add(&HookCallFunc{F: func() { checkers = append(checkers, \"third hook\") }})\n\n\tif err := h.Fire(InfoLevel, &Entry{}); err != nil {\n\t\tt.Error(\"unexpected error:\", err)\n\t}\n\trequire.Equal(t, []string{\"first hook\", \"second hook\", \"third hook\"}, checkers)\n}\n"
  },
  {
    "path": "hooks/slog/slog.go",
    "content": "package slog\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// LevelMapper maps a [logrus.Level] to a [slog.Leveler].\n//\n// To change the default level mapping, for instance to allow mapping to custom\n// or dynamic slog levels in your application, set [SlogHook.LevelMapper]\n// to your own implementation of this function.\ntype LevelMapper func(logrus.Level) slog.Leveler\n\n// SlogHook sends logs to slog.\ntype SlogHook struct {\n\tlogger      *slog.Logger\n\tLevelMapper LevelMapper\n}\n\nvar _ logrus.Hook = (*SlogHook)(nil)\n\n// NewSlogHook creates a hook that sends logs to an existing slog Logger.\n// This hook is intended to be used during transition from Logrus to slog,\n// or as a shim between different parts of your application or different\n// libraries that depend on different loggers.\n//\n// The provided logger must not be nil. NewSlogHook panics if logger is nil.\n//\n// Example usage:\n//\n//\tlogger := slog.New(slog.NewJSONHandler(os.Stderr, nil))\n//\thook := NewSlogHook(logger)\nfunc NewSlogHook(logger *slog.Logger) *SlogHook {\n\tif logger == nil {\n\t\tpanic(\"cannot create hook from nil logger\")\n\t}\n\treturn &SlogHook{\n\t\tlogger: logger,\n\t}\n}\n\nfunc (h *SlogHook) toSlogLevel(level logrus.Level) slog.Leveler {\n\tif h.LevelMapper != nil {\n\t\treturn h.LevelMapper(level)\n\t}\n\tswitch level {\n\tcase logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel:\n\t\treturn slog.LevelError\n\tcase logrus.WarnLevel:\n\t\treturn slog.LevelWarn\n\tcase logrus.InfoLevel:\n\t\treturn slog.LevelInfo\n\tcase logrus.DebugLevel, logrus.TraceLevel:\n\t\treturn slog.LevelDebug\n\tdefault:\n\t\t// Treat all unknown levels as errors\n\t\treturn slog.LevelError\n\t}\n}\n\n// Levels always returns all levels, since slog allows controlling level\n// enabling based on context.\nfunc (h *SlogHook) Levels() []logrus.Level {\n\treturn logrus.AllLevels\n}\n\n// Fire forwards the provided logrus Entry to the underlying slog.Logger's\n// Handler, mapping it to a slog.Record. Time and caller information are\n// preserved when available, and Entry.Data is converted to attributes.\n// If Entry.Context is nil, context.Background() is used.\nfunc (h *SlogHook) Fire(entry *logrus.Entry) error {\n\tctx := entry.Context\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tlvl := h.toSlogLevel(entry.Level).Level()\n\thandler := h.logger.Handler()\n\tif !handler.Enabled(ctx, lvl) {\n\t\treturn nil\n\t}\n\tattrs := make([]slog.Attr, 0, len(entry.Data))\n\tfor k, v := range entry.Data {\n\t\tattrs = append(attrs, slog.Any(k, v))\n\t}\n\tvar pc uintptr\n\tif entry.Caller != nil {\n\t\tpc = entry.Caller.PC\n\t}\n\tr := slog.NewRecord(entry.Time, lvl, entry.Message, pc)\n\tr.AddAttrs(attrs...)\n\treturn handler.Handle(ctx, r)\n}\n"
  },
  {
    "path": "hooks/slog/slog_test.go",
    "content": "package slog_test\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\tlslog \"github.com/sirupsen/logrus/hooks/slog\"\n)\n\nfunc TestSlogHook(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tmapper lslog.LevelMapper\n\t\tfn     func(*logrus.Logger)\n\t\twant   []string\n\t}{\n\t\t{\n\t\t\tname: \"defaults\",\n\t\t\tfn: func(log *logrus.Logger) {\n\t\t\t\tlog.Info(\"info\")\n\t\t\t},\n\t\t\twant: []string{\n\t\t\t\t\"level=INFO msg=info\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with fields\",\n\t\t\tfn: func(log *logrus.Logger) {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"chicken\": \"cluck\",\n\t\t\t\t}).Error(\"error\")\n\t\t\t},\n\t\t\twant: []string{\n\t\t\t\t\"level=ERROR msg=error chicken=cluck\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"level mapper\",\n\t\t\tmapper: func(logrus.Level) slog.Leveler {\n\t\t\t\treturn slog.LevelInfo\n\t\t\t},\n\t\t\tfn: func(log *logrus.Logger) {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"chicken\": \"cluck\",\n\t\t\t\t}).Error(\"error\")\n\t\t\t},\n\t\t\twant: []string{\n\t\t\t\t\"level=INFO msg=error chicken=cluck\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbuf := &bytes.Buffer{}\n\t\t\tslogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{\n\t\t\t\t// Remove timestamps from logs, for easier comparison\n\t\t\t\tReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {\n\t\t\t\t\tif a.Key == slog.TimeKey {\n\t\t\t\t\t\treturn slog.Attr{}\n\t\t\t\t\t}\n\t\t\t\t\treturn a\n\t\t\t\t},\n\t\t\t}))\n\t\t\tlog := logrus.New()\n\t\t\tlog.Out = io.Discard\n\t\t\thook := lslog.NewSlogHook(slogLogger)\n\t\t\thook.LevelMapper = tt.mapper\n\t\t\tlog.AddHook(hook)\n\t\t\ttt.fn(log)\n\t\t\tgot := strings.Split(strings.TrimSpace(buf.String()), \"\\n\")\n\t\t\tif len(got) != len(tt.want) {\n\t\t\t\tt.Errorf(\"Got %d log lines, expected %d\", len(got), len(tt.want))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor i, line := range got {\n\t\t\t\tif line != tt.want[i] {\n\t\t\t\t\tt.Errorf(\"line %d differs from expectation.\\n Got: %s\\nWant: %s\", i, line, tt.want[i])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype errorHandler struct{}\n\nvar _ slog.Handler = (*errorHandler)(nil)\n\nfunc (h *errorHandler) Enabled(context.Context, slog.Level) bool {\n\treturn true\n}\n\nfunc (h *errorHandler) Handle(context.Context, slog.Record) error {\n\treturn errors.New(\"boom\")\n}\n\nfunc (h *errorHandler) WithAttrs([]slog.Attr) slog.Handler {\n\treturn h\n}\n\nfunc (h *errorHandler) WithGroup(string) slog.Handler {\n\treturn h\n}\n\nfunc TestSlogHook_error_propagates(t *testing.T) {\n\tstderr := os.Stderr\n\tr, w, err := os.Pipe()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create pipe: %v\", err)\n\t}\n\tos.Stderr = w\n\tt.Cleanup(func() {\n\t\t_ = r.Close()\n\t})\n\n\tslogLogger := slog.New(&errorHandler{})\n\tlog := logrus.New()\n\tlog.SetOutput(io.Discard)\n\tlog.AddHook(lslog.NewSlogHook(slogLogger))\n\tlog.WithField(\"key\", \"value\").Error(\"test error\")\n\n\t// Restore stderr before closing the pipe writer to avoid leaving os.Stderr\n\t// pointing at a closed file descriptor.\n\tos.Stderr = stderr\n\t_ = w.Close()\n\tgotStderr, _ := io.ReadAll(r)\n\tif !bytes.Contains(gotStderr, []byte(\"boom\")) {\n\t\tt.Errorf(\"expected stderr to contain 'boom', got: %s\", string(gotStderr))\n\t}\n}\n\nfunc TestSlogHook_source(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\tslogLogger := slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{\n\t\tReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {\n\t\t\tif a.Key == slog.TimeKey {\n\t\t\t\treturn slog.Attr{}\n\t\t\t}\n\t\t\treturn a\n\t\t},\n\t\tAddSource: true,\n\t}))\n\tlog := logrus.New()\n\tlog.Out = io.Discard\n\tlog.ReportCaller = true\n\tlog.AddHook(lslog.NewSlogHook(slogLogger))\n\tlog.Info(\"info with source\")\n\tgot := strings.TrimSpace(buf.String())\n\twantRE := regexp.MustCompile(`source=.*hooks[\\\\/]+slog[\\\\/]+slog_test\\.go:\\d+`)\n\tif !wantRE.MatchString(got) {\n\t\tt.Errorf(\"expected log to contain source attribute matching %q, got: %s\", wantRE.String(), got)\n\t}\n}\n"
  },
  {
    "path": "hooks/syslog/README.md",
    "content": "# Syslog Hooks for Logrus <img src=\"http://i.imgur.com/hTeVwmJ.png\" width=\"40\" height=\"40\" alt=\":walrus:\" class=\"emoji\" title=\":walrus:\"/>\n\n## Usage\n\n```go\npackage main\n\nimport (\n\t\"log/syslog\"\n\n\t\"github.com/sirupsen/logrus\"\n\tlsyslog \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\nfunc main() {\n\tlog := logrus.New()\n\thook, err := lsyslog.NewSyslogHook(\"udp\", \"localhost:514\", syslog.LOG_INFO, \"\")\n\n\tif err == nil {\n\t\tlog.Hooks.Add(hook)\n\t}\n}\n```\n\nIf 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.\n\n```go\npackage main\n\nimport (\n\t\"log/syslog\"\n\n\t\"github.com/sirupsen/logrus\"\n\tlsyslog \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\nfunc main() {\n\tlog := logrus.New()\n\thook, err := lsyslog.NewSyslogHook(\"\", \"\", syslog.LOG_INFO, \"\")\n\n\tif err == nil {\n\t\tlog.Hooks.Add(hook)\n\t}\n}\n```\n\n### Different log levels for local and remote logging\n\nBy default `NewSyslogHook()` sends logs through the hook for all log levels. If you want to have\ndifferent log levels between local logging and syslog logging (i.e., respect the `priority` argument\npassed to `NewSyslogHook()`), you need to define a custom hook type that satisfies the `logrus.Hook`\ninterface by embedding `*lsyslog.SyslogHook` and overriding `Levels()` to return only the log levels\nyou're interested in.\n\nThe following example shows how to log at **DEBUG** level for local logging and **WARN** level for\nsyslog logging:\n\n```go\npackage main\n\nimport (\n\t\"log/syslog\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\tlsyslog \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\ntype customHook struct {\n\t*lsyslog.SyslogHook\n}\n\nfunc (h *customHook) Levels() []log.Level {\n\treturn []log.Level{log.WarnLevel}\n}\n\nfunc main() {\n\tlog.SetLevel(log.DebugLevel)\n\n\thook, err := lsyslog.NewSyslogHook(\"tcp\", \"localhost:5140\", syslog.LOG_WARNING, \"myTag\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlog.AddHook(&customHook{hook})\n\n\t// ...\n}\n```\n"
  },
  {
    "path": "hooks/syslog/syslog.go",
    "content": "//go:build !windows && !nacl && !plan9\n\npackage syslog\n\nimport (\n\t\"fmt\"\n\t\"log/syslog\"\n\t\"os\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// SyslogHook to send logs via syslog.\ntype SyslogHook struct {\n\tWriter        *syslog.Writer\n\tSyslogNetwork string\n\tSyslogRaddr   string\n}\n\nvar _ logrus.Hook = (*SyslogHook)(nil)\n\n// NewSyslogHook creates a hook to be added to an instance of logger.\n//\n// This is called with:\n//\n//\thook, err := NewSyslogHook(\"udp\", \"localhost:514\", syslog.LOG_DEBUG, \"\")\n//\tif err == nil {\n//\t\tlog.Hooks.Add(hook)\n//\t}\nfunc NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {\n\tw, err := syslog.Dial(network, raddr, priority, tag)\n\treturn &SyslogHook{w, network, raddr}, err\n}\n\nfunc (hook *SyslogHook) Fire(entry *logrus.Entry) error {\n\tline, err := entry.String()\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Unable to read entry, %v\", err)\n\t\treturn err\n\t}\n\n\tswitch entry.Level {\n\tcase logrus.PanicLevel:\n\t\treturn hook.Writer.Crit(line)\n\tcase logrus.FatalLevel:\n\t\treturn hook.Writer.Crit(line)\n\tcase logrus.ErrorLevel:\n\t\treturn hook.Writer.Err(line)\n\tcase logrus.WarnLevel:\n\t\treturn hook.Writer.Warning(line)\n\tcase logrus.InfoLevel:\n\t\treturn hook.Writer.Info(line)\n\tcase logrus.DebugLevel, logrus.TraceLevel:\n\t\treturn hook.Writer.Debug(line)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (hook *SyslogHook) Levels() []logrus.Level {\n\treturn logrus.AllLevels\n}\n"
  },
  {
    "path": "hooks/syslog/syslog_test.go",
    "content": "//go:build !windows && !nacl && !plan9\n\npackage syslog_test\n\nimport (\n\t\"io\"\n\t\"log/syslog\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\tlsyslog \"github.com/sirupsen/logrus/hooks/syslog\"\n)\n\nfunc TestLocalhostAddAndPrint(t *testing.T) {\n\tlog := logrus.New()\n\tlog.SetOutput(io.Discard)\n\thook, err := lsyslog.NewSyslogHook(\"udp\", \"localhost:514\", syslog.LOG_INFO, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unable to connect to local syslog.\")\n\t}\n\n\tlog.Hooks.Add(hook)\n\n\tfor _, level := range hook.Levels() {\n\t\tif len(log.Hooks[level]) != 1 {\n\t\t\tt.Errorf(\"SyslogHook was not added. The length of log.Hooks[%v]: %v\", level, len(log.Hooks[level]))\n\t\t}\n\t}\n\n\tlog.Info(\"Congratulations!\")\n}\n"
  },
  {
    "path": "hooks/test/test.go",
    "content": "// Package test is used for testing logrus.\n// It provides a simple hooks which register logged messages.\npackage test\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// Hook is a hook designed for dealing with logs in test scenarios.\ntype Hook struct {\n\t// Entries is an array of all entries that have been received by this hook.\n\t// For safe access, use the AllEntries() method, rather than reading this\n\t// value directly.\n\tEntries []logrus.Entry\n\tmu      sync.RWMutex\n}\n\nvar _ logrus.Hook = (*Hook)(nil)\n\n// NewGlobal installs a test hook for the global logger.\nfunc NewGlobal() *Hook {\n\thook := new(Hook)\n\tlogrus.AddHook(hook)\n\n\treturn hook\n}\n\n// NewLocal installs a test hook for a given local logger.\nfunc NewLocal(logger *logrus.Logger) *Hook {\n\thook := new(Hook)\n\tlogger.AddHook(hook)\n\n\treturn hook\n}\n\n// NewNullLogger creates a discarding logger and installs the test hook.\nfunc NewNullLogger() (*logrus.Logger, *Hook) {\n\tlogger := logrus.New()\n\tlogger.Out = io.Discard\n\n\treturn logger, NewLocal(logger)\n}\n\nfunc (t *Hook) Fire(e *logrus.Entry) error {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tt.Entries = append(t.Entries, *e)\n\treturn nil\n}\n\nfunc (t *Hook) Levels() []logrus.Level {\n\treturn logrus.AllLevels\n}\n\n// LastEntry returns the last entry that was logged or nil.\nfunc (t *Hook) LastEntry() *logrus.Entry {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\ti := len(t.Entries) - 1\n\tif i < 0 {\n\t\treturn nil\n\t}\n\treturn &t.Entries[i]\n}\n\n// AllEntries returns all entries that were logged.\nfunc (t *Hook) AllEntries() []*logrus.Entry {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\t// Make a copy so the returned value won't race with future log requests\n\tentries := make([]*logrus.Entry, len(t.Entries))\n\tfor i := 0; i < len(t.Entries); i++ {\n\t\t// Make a copy, for safety\n\t\tentries[i] = &t.Entries[i]\n\t}\n\treturn entries\n}\n\n// Reset removes all Entries from this test hook.\nfunc (t *Hook) Reset() {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tt.Entries = make([]logrus.Entry, 0)\n}\n"
  },
  {
    "path": "hooks/test/test_test.go",
    "content": "package test_test\n\nimport (\n\t\"io\"\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/sirupsen/logrus/hooks/test\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestAllHooks(t *testing.T) {\n\t// Test modifies the standard-logger; restore it afterward.\n\tstdLogger := logrus.StandardLogger()\n\toldOut := stdLogger.Out\n\toldHooks := stdLogger.ReplaceHooks(make(logrus.LevelHooks))\n\tt.Cleanup(func() {\n\t\tstdLogger.SetOutput(oldOut)\n\t\tstdLogger.ReplaceHooks(oldHooks)\n\t})\n\tassert := assert.New(t)\n\n\tlogger, hook := test.NewNullLogger()\n\tassert.Nil(hook.LastEntry())\n\tassert.Empty(hook.Entries)\n\n\tlogger.Error(\"Hello error\")\n\tassert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)\n\tassert.Equal(\"Hello error\", hook.LastEntry().Message)\n\tassert.Len(hook.Entries, 1)\n\n\tlogger.Warn(\"Hello warning\")\n\tassert.Equal(logrus.WarnLevel, hook.LastEntry().Level)\n\tassert.Equal(\"Hello warning\", hook.LastEntry().Message)\n\tassert.Len(hook.Entries, 2)\n\n\thook.Reset()\n\tassert.Nil(hook.LastEntry())\n\tassert.Empty(hook.Entries)\n\n\thook = test.NewGlobal()\n\n\tlogrus.SetOutput(io.Discard)\n\tlogrus.Error(\"Hello error\")\n\tassert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)\n\tassert.Equal(\"Hello error\", hook.LastEntry().Message)\n\tassert.Len(hook.Entries, 1)\n}\n\nfunc TestLoggingWithHooksRace(t *testing.T) {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tunlocker := r.Intn(100)\n\n\tassert := assert.New(t)\n\tlogger, hook := test.NewNullLogger()\n\n\tvar wgOne, wgAll sync.WaitGroup\n\twgOne.Add(1)\n\twgAll.Add(100)\n\n\tfor i := range 100 {\n\t\tgo func(i int) {\n\t\t\tlogger.Info(\"info\")\n\t\t\twgAll.Done()\n\t\t\tif i == unlocker {\n\t\t\t\twgOne.Done()\n\t\t\t}\n\t\t}(i)\n\t}\n\n\twgOne.Wait()\n\n\tassert.Equal(logrus.InfoLevel, hook.LastEntry().Level)\n\tassert.Equal(\"info\", hook.LastEntry().Message)\n\n\twgAll.Wait()\n\n\tentries := hook.AllEntries()\n\tassert.Len(entries, 100)\n}\n\n// nolint:staticcheck // linter assumes logger.Fatal exits, resulting in false SA4006 warnings.\nfunc TestFatalWithAlternateExit(t *testing.T) {\n\tassert := assert.New(t)\n\n\tlogger, hook := test.NewNullLogger()\n\tlogger.ExitFunc = func(code int) {}\n\n\tlogger.Fatal(\"something went very wrong\")\n\tassert.Equal(logrus.FatalLevel, hook.LastEntry().Level)\n\tassert.Equal(\"something went very wrong\", hook.LastEntry().Message)\n\tassert.Len(hook.Entries, 1)\n}\n\nfunc TestNewLocal(t *testing.T) {\n\tassert := assert.New(t)\n\tlogger := logrus.New()\n\tlogger.SetOutput(io.Discard)\n\n\tvar wg sync.WaitGroup\n\tdefer wg.Wait()\n\n\twg.Add(10)\n\tfor range 10 {\n\t\tgo func() {\n\t\t\tlogger.Info(\"info\")\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\thook := test.NewLocal(logger)\n\tassert.NotNil(hook)\n}\n"
  },
  {
    "path": "hooks/writer/README.md",
    "content": "# Writer Hooks for Logrus\n\nSend logs of given levels to any object with `io.Writer` interface.\n\n## Usage\n\nIf you want for example send high level logs to `Stderr` and\nlogs of  normal execution to `Stdout`, you could do it like this:\n\n```go\npackage main\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"github.com/sirupsen/logrus/hooks/writer\"\n)\n\nfunc main() {\n\tlog.SetOutput(ioutil.Discard) // Send all logs to nowhere by default\n\n\tlog.AddHook(&writer.Hook{ // Send logs with level higher than warning to stderr\n\t\tWriter: os.Stderr,\n\t\tLogLevels: []log.Level{\n\t\t\tlog.PanicLevel,\n\t\t\tlog.FatalLevel,\n\t\t\tlog.ErrorLevel,\n\t\t\tlog.WarnLevel,\n\t\t},\n\t})\n\tlog.AddHook(&writer.Hook{ // Send info and debug logs to stdout\n\t\tWriter: os.Stdout,\n\t\tLogLevels: []log.Level{\n\t\t\tlog.InfoLevel,\n\t\t\tlog.DebugLevel,\n\t\t},\n\t})\n\tlog.Info(\"This will go to stdout\")\n\tlog.Warn(\"This will go to stderr\")\n}\n```\n"
  },
  {
    "path": "hooks/writer/writer.go",
    "content": "package writer\n\nimport (\n\t\"io\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n// Hook is a hook that writes logs of specified LogLevels to specified Writer\ntype Hook struct {\n\tWriter    io.Writer\n\tLogLevels []logrus.Level\n}\n\nvar _ logrus.Hook = (*Hook)(nil)\n\n// Fire will be called when some logging function is called with current hook\n// It will format log entry to string and write it to appropriate writer\nfunc (hook *Hook) Fire(entry *logrus.Entry) error {\n\tline, err := entry.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = hook.Writer.Write(line)\n\treturn err\n}\n\n// Levels define on which log levels this hook would trigger\nfunc (hook *Hook) Levels() []logrus.Level {\n\treturn hook.LogLevels\n}\n"
  },
  {
    "path": "hooks/writer/writer_test.go",
    "content": "package writer_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/sirupsen/logrus/hooks/writer\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDifferentLevelsGoToDifferentWriters(t *testing.T) {\n\tvar a, b bytes.Buffer\n\n\tlog := logrus.New()\n\tlog.SetFormatter(&logrus.TextFormatter{\n\t\tDisableTimestamp: true,\n\t\tDisableColors:    true,\n\t})\n\tlog.SetOutput(io.Discard) // Send all logs to nowhere by default\n\n\tlog.AddHook(&writer.Hook{\n\t\tWriter: &a,\n\t\tLogLevels: []logrus.Level{\n\t\t\tlogrus.WarnLevel,\n\t\t},\n\t})\n\tlog.AddHook(&writer.Hook{ // Send info and debug logs to stdout\n\t\tWriter: &b,\n\t\tLogLevels: []logrus.Level{\n\t\t\tlogrus.InfoLevel,\n\t\t},\n\t})\n\tlog.Warn(\"send to a\")\n\tlog.Info(\"send to b\")\n\n\tassert.Equal(t, \"level=warning msg=\\\"send to a\\\"\\n\", a.String())\n\tassert.Equal(t, \"level=info msg=\\\"send to b\\\"\\n\", b.String())\n}\n"
  },
  {
    "path": "hooks.go",
    "content": "package logrus\n\n// Hook describes hooks to be fired when logging on the logging levels returned from\n// [Hook.Levels] on your implementation of the interface. Note that this is not\n// fired in a goroutine or a channel with workers, you should handle such\n// functionality yourself if your call is non-blocking, and you don't wish for\n// the logging calls for levels returned from `Levels()` to block.\ntype Hook interface {\n\tLevels() []Level\n\tFire(*Entry) error\n}\n\n// LevelHooks is an internal type for storing the hooks on a logger instance.\ntype LevelHooks map[Level][]Hook\n\n// Add a hook to an instance of logger. This is called with\n// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.\nfunc (hooks LevelHooks) Add(hook Hook) {\n\tfor _, level := range hook.Levels() {\n\t\thooks[level] = append(hooks[level], hook)\n\t}\n}\n\n// Fire all the hooks for the passed level. Used by `entry.log` to fire\n// appropriate hooks for a log entry.\nfunc (hooks LevelHooks) Fire(level Level, entry *Entry) error {\n\tfor _, hook := range hooks[level] {\n\t\tif err := hook.Fire(entry); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/testutils/testutils.go",
    "content": "package testutils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t. \"github.com/sirupsen/logrus\" //nolint:staticcheck\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {\n\tvar buffer bytes.Buffer\n\tvar fields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\n\tlog(logger)\n\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err)\n\n\tassertions(fields)\n}\n\nfunc LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {\n\tvar buffer bytes.Buffer\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = &TextFormatter{\n\t\tDisableColors: true,\n\t}\n\n\tlog(logger)\n\n\tfields := make(map[string]string)\n\tfor _, kv := range strings.Split(strings.TrimRight(buffer.String(), \"\\n\"), \" \") {\n\t\tif !strings.Contains(kv, \"=\") {\n\t\t\tcontinue\n\t\t}\n\t\tkvArr := strings.Split(kv, \"=\")\n\t\tkey := strings.TrimSpace(kvArr[0])\n\t\tval := kvArr[1]\n\t\tif kvArr[1][0] == '\"' {\n\t\t\tvar err error\n\t\t\tval, err = strconv.Unquote(val)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t\tfields[key] = val\n\t}\n\tassertions(fields)\n}\n"
  },
  {
    "path": "json_formatter.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype fieldKey string\n\n// FieldMap allows customization of the key names for default fields.\ntype FieldMap map[fieldKey]string\n\nfunc (f FieldMap) resolve(key fieldKey) string {\n\tif k, ok := f[key]; ok {\n\t\treturn k\n\t}\n\n\treturn string(key)\n}\n\n// JSONFormatter formats logs into parsable json\ntype JSONFormatter struct {\n\t// TimestampFormat sets the format used for marshaling timestamps.\n\t// The format to use is the same than for time.Format or time.Parse from the standard\n\t// library.\n\t// The standard Library already provides a set of predefined format.\n\tTimestampFormat string\n\n\t// DisableTimestamp allows disabling automatic timestamps in output\n\tDisableTimestamp bool\n\n\t// DisableHTMLEscape allows disabling html escaping in output\n\tDisableHTMLEscape bool\n\n\t// DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.\n\tDataKey string\n\n\t// FieldMap allows users to customize the names of keys for default fields.\n\t// As an example:\n\t// formatter := &JSONFormatter{\n\t//   \tFieldMap: FieldMap{\n\t// \t\t FieldKeyTime:  \"@timestamp\",\n\t// \t\t FieldKeyLevel: \"@level\",\n\t// \t\t FieldKeyMsg:   \"@message\",\n\t// \t\t FieldKeyFunc:  \"@caller\",\n\t//    },\n\t// }\n\tFieldMap FieldMap\n\n\t// CallerPrettyfier can be set by the user to modify the content\n\t// of the function and file keys in the json data when ReportCaller is\n\t// activated. If any of the returned value is the empty string the\n\t// corresponding key will be removed from json fields.\n\tCallerPrettyfier func(*runtime.Frame) (function string, file string)\n\n\t// PrettyPrint will indent all json logs\n\tPrettyPrint bool\n}\n\n// Format renders a single log entry\nfunc (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {\n\tcaller := entry.Caller\n\tdata := make(Fields, len(entry.Data)+defaultFields)\n\tfor k, v := range entry.Data {\n\t\tswitch v := v.(type) {\n\t\tcase error:\n\t\t\t// Otherwise errors are ignored by `encoding/json`\n\t\t\t// https://github.com/sirupsen/logrus/issues/137\n\t\t\tdata[k] = v.Error()\n\t\tdefault:\n\t\t\tdata[k] = v\n\t\t}\n\t}\n\n\tif f.DataKey != \"\" && len(entry.Data) > 0 {\n\t\tnewData := make(Fields, defaultFields+1)\n\t\tnewData[f.DataKey] = data\n\t\tdata = newData\n\t}\n\n\thasCaller := caller != nil\n\tprefixFieldClashes(data, f.FieldMap, hasCaller)\n\n\ttimestampFormat := f.TimestampFormat\n\tif timestampFormat == \"\" {\n\t\ttimestampFormat = defaultTimestampFormat\n\t}\n\n\tif entry.err != \"\" {\n\t\tdata[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err\n\t}\n\tif !f.DisableTimestamp {\n\t\tdata[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)\n\t}\n\tdata[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message\n\tdata[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()\n\tif caller != nil {\n\t\tvar funcVal, fileVal string\n\t\tif f.CallerPrettyfier != nil {\n\t\t\tfuncVal, fileVal = f.CallerPrettyfier(caller)\n\t\t} else {\n\t\t\tfuncVal = caller.Function\n\t\t\tfileVal = caller.File + \":\" + strconv.FormatInt(int64(caller.Line), 10)\n\t\t}\n\t\tif funcVal != \"\" {\n\t\t\tdata[f.FieldMap.resolve(FieldKeyFunc)] = funcVal\n\t\t}\n\t\tif fileVal != \"\" {\n\t\t\tdata[f.FieldMap.resolve(FieldKeyFile)] = fileVal\n\t\t}\n\t}\n\n\tb := entry.Buffer\n\tif b == nil {\n\t\tb = new(bytes.Buffer)\n\t}\n\n\tencoder := json.NewEncoder(b)\n\tencoder.SetEscapeHTML(!f.DisableHTMLEscape)\n\tif f.PrettyPrint {\n\t\tencoder.SetIndent(\"\", \"  \")\n\t}\n\tif err := encoder.Encode(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal fields to JSON, %w\", err)\n\t}\n\n\treturn b.Bytes(), nil\n}\n"
  },
  {
    "path": "json_formatter_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc TestErrorNotLost(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"error\", errors.New(\"wild walrus\")))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"error\"] != \"wild walrus\" {\n\t\tt.Fatal(\"Error field not set\")\n\t}\n}\n\nfunc TestErrorNotLostOnFieldNotNamedError(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"omg\", errors.New(\"wild walrus\")))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"omg\"] != \"wild walrus\" {\n\t\tt.Fatal(\"Error field not set\")\n\t}\n}\n\nfunc TestFieldClashWithTime(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"time\", \"right now!\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"fields.time\"] != \"right now!\" {\n\t\tt.Fatal(\"fields.time not set to original time field\")\n\t}\n\n\tif entry[\"time\"] != \"0001-01-01T00:00:00Z\" {\n\t\tt.Fatal(\"time field not set to current time, was: \", entry[\"time\"])\n\t}\n}\n\nfunc TestFieldClashWithMsg(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"msg\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"fields.msg\"] != \"something\" {\n\t\tt.Fatal(\"fields.msg not set to original msg field\")\n\t}\n}\n\nfunc TestFieldClashWithLevel(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"fields.level\"] != \"something\" {\n\t\tt.Fatal(\"fields.level not set to original level field\")\n\t}\n}\n\nfunc TestFieldClashWithRemappedFields(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyTime:  \"@timestamp\",\n\t\t\tlogrus.FieldKeyLevel: \"@level\",\n\t\t\tlogrus.FieldKeyMsg:   \"@message\",\n\t\t},\n\t}\n\n\tb, err := formatter.Format(logrus.WithFields(logrus.Fields{\n\t\t\"@timestamp\": \"@timestamp\",\n\t\t\"@level\":     \"@level\",\n\t\t\"@message\":   \"@message\",\n\t\t\"timestamp\":  \"timestamp\",\n\t\t\"level\":      \"level\",\n\t\t\"msg\":        \"msg\",\n\t}))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tfor _, field := range []string{\"timestamp\", \"level\", \"msg\"} {\n\t\tif entry[field] != field {\n\t\t\tt.Errorf(\"Expected field %v to be untouched; got %v\", field, entry[field])\n\t\t}\n\n\t\tremappedKey := fmt.Sprintf(\"fields.%s\", field)\n\t\tif remapped, ok := entry[remappedKey]; ok {\n\t\t\tt.Errorf(\"Expected %s to be empty; got %v\", remappedKey, remapped)\n\t\t}\n\t}\n\n\tfor _, field := range []string{\"@timestamp\", \"@level\", \"@message\"} {\n\t\tif entry[field] == field {\n\t\t\tt.Errorf(\"Expected field %v to be mapped to an Entry value\", field)\n\t\t}\n\n\t\tremappedKey := fmt.Sprintf(\"fields.%s\", field)\n\t\tif remapped, ok := entry[remappedKey]; ok {\n\t\t\tif remapped != field {\n\t\t\t\tt.Errorf(\"Expected field %v to be copied to %s; got %v\", field, remappedKey, remapped)\n\t\t\t}\n\t\t} else {\n\t\t\tt.Errorf(\"Expected field %v to be copied to %s; was absent\", field, remappedKey)\n\t\t}\n\t}\n}\n\nfunc TestFieldsInNestedDictionary(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tDataKey: \"args\",\n\t}\n\n\tlogEntry := logrus.WithFields(logrus.Fields{\n\t\t\"level\": \"level\",\n\t\t\"test\":  \"test\",\n\t})\n\tlogEntry.Level = logrus.InfoLevel\n\n\tb, err := formatter.Format(logEntry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\targs := entry[\"args\"].(map[string]any)\n\n\tfor _, field := range []string{\"test\", \"level\"} {\n\t\tif value, present := args[field]; !present || value != field {\n\t\t\tt.Errorf(\"Expected field %v to be present under 'args'; untouched\", field)\n\t\t}\n\t}\n\n\tfor _, field := range []string{\"test\", \"fields.level\"} {\n\t\tif _, present := entry[field]; present {\n\t\t\tt.Errorf(\"Expected field %v not to be present at top level\", field)\n\t\t}\n\t}\n\n\t// with nested object, \"level\" shouldn't clash\n\tif entry[\"level\"] != \"info\" {\n\t\tt.Errorf(\"Expected 'level' field to contain 'info'\")\n\t}\n}\n\nfunc TestJSONEntryFieldValueError(t *testing.T) {\n\tt.Run(\"good value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := logrus.New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})\n\n\t\tl.WithField(\"ok\", \"ok\").Info(\"test\")\n\n\t\tvar data map[string]any\n\t\terr := json.Unmarshal(buf.Bytes(), &data)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t\t}\n\n\t\tif _, ok := data[logrus.FieldKeyLogrusError]; ok {\n\t\t\tt.Errorf(`Unexpected \"logrus_error\" field in log entry: %v`, data)\n\t\t}\n\t\tif v, ok := data[\"ok\"]; !ok || v != \"ok\" {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok\"=\"ok\": %v`, data)\n\t\t}\n\t})\n\n\t// If we dropped an unsupported field, the FieldKeyLogrusError should\n\t// contain a message that we did.\n\tt.Run(\"bad and good value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := logrus.New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})\n\n\t\tl.WithField(\"func\", func() {}).WithField(\"ok\", \"ok\").Info(\"test\")\n\n\t\tvar data map[string]any\n\t\tif err := json.Unmarshal(buf.Bytes(), &data); err != nil {\n\t\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t\t}\n\n\t\tif v, ok := data[logrus.FieldKeyLogrusError]; !ok || v == \"\" {\n\t\t\tt.Errorf(`Expected log entry to contain a \"logrus_error\" field: %v`, data)\n\t\t}\n\t\tif _, ok := data[\"func\"]; ok {\n\t\t\tt.Errorf(`Expected \"func\" field to be removed from log entry: %v`, data)\n\t\t}\n\t\tif v, ok := data[\"ok\"]; !ok || v != \"ok\" {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok=ok\": %v`, data)\n\t\t}\n\t})\n\n\t// This is testing the current behavior; error is preserved, even if an\n\t// unsupported value was dropped and replaced with a supported value for\n\t// the same field.\n\tt.Run(\"replace bad value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := logrus.New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&logrus.JSONFormatter{DisableTimestamp: true})\n\n\t\tl.WithField(\"func\", func() {}).WithField(\"ok\", \"ok\").WithField(\"func\", \"not-a-func\").Info(\"test\")\n\n\t\tvar data map[string]any\n\t\tif err := json.Unmarshal(buf.Bytes(), &data); err != nil {\n\t\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t\t}\n\n\t\tif v, ok := data[logrus.FieldKeyLogrusError]; !ok || v == \"\" {\n\t\t\tt.Errorf(`Expected log entry to contain a \"logrus_error\" field: %v`, data)\n\t\t}\n\t\tif v, ok := data[\"func\"]; !ok || v != \"not-a-func\" {\n\t\t\tt.Errorf(`Expected log entry to contain \"func=not-a-func\": %v`, data)\n\t\t}\n\t\tif v, ok := data[\"ok\"]; !ok || v != \"ok\" {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok=ok\": %v`, data)\n\t\t}\n\t})\n}\n\nfunc TestJSONEntryEndsWithNewline(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tif b[len(b)-1] != '\\n' {\n\t\tt.Fatal(\"Expected JSON log entry to end with a newline\")\n\t}\n}\n\nfunc TestJSONMessageKey(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyMsg: \"message\",\n\t\t},\n\t}\n\n\tb, err := formatter.Format(&logrus.Entry{Message: \"oh hai\"})\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, `\"message\":\"oh hai\"`) {\n\t\tt.Fatal(\"Expected JSON to format message key\")\n\t}\n}\n\nfunc TestJSONLevelKey(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyLevel: \"somelevel\",\n\t\t},\n\t}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, \"somelevel\") {\n\t\tt.Fatal(\"Expected JSON to format level key\")\n\t}\n}\n\nfunc TestJSONTimeKey(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyTime: \"timeywimey\",\n\t\t},\n\t}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, \"timeywimey\") {\n\t\tt.Fatal(\"Expected JSON to format time key\")\n\t}\n}\n\nfunc TestFieldDoesNotClashWithCaller(t *testing.T) {\n\tlogrus.SetReportCaller(false)\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"func\", \"howdy pardner\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"func\"] != \"howdy pardner\" {\n\t\tt.Fatal(\"func field replaced when ReportCaller=false\")\n\t}\n}\n\nfunc TestFieldClashWithCaller(t *testing.T) {\n\tlogrus.SetReportCaller(true)\n\tt.Cleanup(func() {\n\t\tlogrus.SetReportCaller(false) // return to default value\n\t})\n\tformatter := &logrus.JSONFormatter{}\n\te := logrus.WithField(\"func\", \"howdy pardner\")\n\te.Caller = &runtime.Frame{Function: \"somefunc\"}\n\tb, err := formatter.Format(e)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tentry := make(map[string]any)\n\terr = json.Unmarshal(b, &entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to unmarshal formatted entry: \", err)\n\t}\n\n\tif entry[\"fields.func\"] != \"howdy pardner\" {\n\t\tt.Fatalf(\"fields.func not set to original func field when ReportCaller=true (got '%s')\",\n\t\t\tentry[\"fields.func\"])\n\t}\n\n\tif entry[\"func\"] != \"somefunc\" {\n\t\tt.Fatalf(\"func not set as expected when ReportCaller=true (got '%s')\",\n\t\t\tentry[\"func\"])\n\t}\n}\n\nfunc TestJSONDisableTimestamp(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{\n\t\tDisableTimestamp: true,\n\t}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif strings.Contains(s, logrus.FieldKeyTime) {\n\t\tt.Error(\"Did not prevent timestamp\", s)\n\t}\n}\n\nfunc TestJSONEnableTimestamp(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(logrus.WithField(\"level\", \"something\"))\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, logrus.FieldKeyTime) {\n\t\tt.Error(\"Timestamp not present\", s)\n\t}\n}\n\nfunc TestJSONDisableHTMLEscape(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{DisableHTMLEscape: true}\n\n\tb, err := formatter.Format(&logrus.Entry{Message: \"& < >\"})\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, \"& < >\") {\n\t\tt.Error(\"Message should not be HTML escaped\", s)\n\t}\n}\n\nfunc TestJSONEnableHTMLEscape(t *testing.T) {\n\tformatter := &logrus.JSONFormatter{}\n\n\tb, err := formatter.Format(&logrus.Entry{Message: \"& < >\"})\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\ts := string(b)\n\tif !strings.Contains(s, `\\u0026 \\u003c \\u003e`) {\n\t\tt.Error(\"Message should be HTML escaped\", s)\n\t}\n}\n"
  },
  {
    "path": "level.go",
    "content": "package logrus\n\nimport (\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tansiReset  = \"\\x1b[0m\"  // reset attributes\n\tansiRed    = \"\\x1b[31m\" // red\n\tansiYellow = \"\\x1b[33m\" // yellow\n\tansiCyan   = \"\\x1b[36m\" // cyan\n\tansiWhite  = \"\\x1b[37m\" // white (light gray)\n)\n\ntype lvlPrefix struct {\n\tfull      string\n\ttruncated string\n\tpadded    string\n}\n\nfunc colorize(level Level, s string) string {\n\tcolor := ansiCyan\n\tswitch level {\n\tcase DebugLevel, TraceLevel:\n\t\tcolor = ansiWhite\n\tcase WarnLevel:\n\t\tcolor = ansiYellow\n\tcase ErrorLevel, FatalLevel, PanicLevel:\n\t\tcolor = ansiRed\n\tcase InfoLevel:\n\t\tcolor = ansiCyan\n\t}\n\treturn color + s + ansiReset\n}\n\nfunc formatLevel(level Level, disableTrunc, pad bool, maxLen int) string {\n\tupper := strings.ToUpper(level.String())\n\n\tif pad && maxLen > len(upper) {\n\t\tupper += strings.Repeat(\" \", maxLen-len(upper))\n\t}\n\n\tif !pad && !disableTrunc && len(upper) > 4 {\n\t\tupper = upper[:4]\n\t}\n\n\treturn colorize(level, upper)\n}\n\nvar levelPrefixOnce = sync.OnceValues(func() (map[Level]lvlPrefix, lvlPrefix) {\n\tvar maxLevel Level\n\tmaxLen := 0\n\tfor _, lvl := range AllLevels {\n\t\tif lvl > maxLevel {\n\t\t\tmaxLevel = lvl\n\t\t}\n\t\tif l := len(lvl.String()); l > maxLen {\n\t\t\tmaxLen = l\n\t\t}\n\t}\n\n\tprefix := make(map[Level]lvlPrefix, len(AllLevels))\n\tfor _, lvl := range AllLevels {\n\t\tprefix[lvl] = lvlPrefix{\n\t\t\tfull:      formatLevel(lvl, true, false, maxLen),\n\t\t\ttruncated: formatLevel(lvl, false, false, maxLen),\n\t\t\tpadded:    formatLevel(lvl, true, true, maxLen),\n\t\t}\n\t}\n\n\tunknownLevel := maxLevel + 1\n\tunknown := lvlPrefix{\n\t\tfull:      formatLevel(unknownLevel, true, false, maxLen),\n\t\ttruncated: formatLevel(unknownLevel, false, false, maxLen),\n\t\tpadded:    formatLevel(unknownLevel, true, true, maxLen),\n\t}\n\n\treturn prefix, unknown\n})\n\nfunc levelPrefix(level Level, disableTrunc, pad bool) string {\n\tprefix, unknown := levelPrefixOnce()\n\n\tp, ok := prefix[level]\n\tif !ok {\n\t\tp = unknown\n\t}\n\n\tswitch {\n\tcase pad:\n\t\treturn p.padded\n\tcase !disableTrunc:\n\t\treturn p.truncated\n\tdefault:\n\t\treturn p.full\n\t}\n}\n"
  },
  {
    "path": "level_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestLevelJsonEncoding(t *testing.T) {\n\ttype X struct {\n\t\tLevel logrus.Level\n\t}\n\n\tvar x X\n\tx.Level = logrus.WarnLevel\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\trequire.NoError(t, enc.Encode(x))\n\tdec := json.NewDecoder(&buf)\n\tvar y X\n\trequire.NoError(t, dec.Decode(&y))\n}\n\nfunc TestLevelUnmarshalText(t *testing.T) {\n\tvar u logrus.Level\n\tfor _, level := range logrus.AllLevels {\n\t\tt.Run(level.String(), func(t *testing.T) {\n\t\t\trequire.NoError(t, u.UnmarshalText([]byte(level.String())))\n\t\t\trequire.Equal(t, level, u)\n\t\t})\n\t}\n\tt.Run(\"invalid\", func(t *testing.T) {\n\t\trequire.Error(t, u.UnmarshalText([]byte(\"invalid\")))\n\t})\n}\n\nfunc TestLevelMarshalText(t *testing.T) {\n\tlevelStrings := []string{\n\t\t\"panic\",\n\t\t\"fatal\",\n\t\t\"error\",\n\t\t\"warning\",\n\t\t\"info\",\n\t\t\"debug\",\n\t\t\"trace\",\n\t}\n\tfor idx, val := range logrus.AllLevels {\n\t\tlevel := val\n\t\tt.Run(level.String(), func(t *testing.T) {\n\t\t\tvar cmp logrus.Level\n\t\t\tb, err := level.MarshalText()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, levelStrings[idx], string(b))\n\t\t\terr = cmp.UnmarshalText(b)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, level, cmp)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "logger.go",
    "content": "package logrus\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n// LogFunction For big messages, it can be more efficient to pass a function\n// and only call it if the log level is actually enables rather than\n// generating the log message and then checking if the level is enabled\ntype LogFunction func() []any\n\ntype Logger struct {\n\t// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a\n\t// file, or leave it default which is `os.Stderr`. You can also set this to\n\t// something more adventurous, such as logging to Kafka.\n\tOut io.Writer\n\n\t// Hooks for the logger instance. These allow firing events based on logging\n\t// levels and log entries. For example, to send errors to an error tracking\n\t// service, log to StatsD or dump the core on fatal errors.\n\tHooks LevelHooks\n\n\t// All log entries pass through the formatter before logged to Out. The\n\t// included formatters are `TextFormatter` and `JSONFormatter` for which\n\t// TextFormatter is the default. In development (when a TTY is attached) it\n\t// logs with colors, but to a file it wouldn't. You can easily implement your\n\t// own that implements the `Formatter` interface, see the `README` or included\n\t// formatters for examples.\n\tFormatter Formatter\n\n\t// Flag for whether to log caller info (off by default)\n\tReportCaller bool\n\n\t// The logging level the logger should log at. This is typically (and defaults\n\t// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be\n\t// logged.\n\tLevel Level\n\n\t// Used to sync writing to the log. Locking is enabled by Default\n\tmu MutexWrap\n\n\t// Reusable empty entry\n\tentryPool sync.Pool\n\n\t// Function to exit the application, defaults to `os.Exit()`\n\tExitFunc func(int)\n\n\t// The buffer pool used to format the log. If it is nil, the default global\n\t// buffer pool will be used.\n\tBufferPool BufferPool\n}\n\ntype MutexWrap struct {\n\tlock     sync.Mutex\n\tdisabled bool\n}\n\nfunc (mw *MutexWrap) Lock() {\n\tif !mw.disabled {\n\t\tmw.lock.Lock()\n\t}\n}\n\nfunc (mw *MutexWrap) Unlock() {\n\tif !mw.disabled {\n\t\tmw.lock.Unlock()\n\t}\n}\n\nfunc (mw *MutexWrap) Disable() {\n\tmw.disabled = true\n}\n\n// New Creates a new logger. Configuration should be set by changing [Formatter],\n// Out and Hooks directly on the default Logger instance. You can also just\n// instantiate your own:\n//\n//\tvar log = &logrus.Logger{\n//\t  Out:       os.Stderr,\n//\t  Formatter: new(logrus.TextFormatter),\n//\t  Hooks:     make(logrus.LevelHooks),\n//\t  Level:     logrus.DebugLevel,\n//\t}\n//\n// It's recommended to make this a global instance called `log`.\nfunc New() *Logger {\n\treturn &Logger{\n\t\tOut:          os.Stderr,\n\t\tFormatter:    new(TextFormatter),\n\t\tHooks:        make(LevelHooks),\n\t\tLevel:        InfoLevel,\n\t\tExitFunc:     os.Exit,\n\t\tReportCaller: false,\n\t}\n}\n\nfunc (logger *Logger) newEntry() *Entry {\n\tentry, ok := logger.entryPool.Get().(*Entry)\n\tif ok {\n\t\treturn entry\n\t}\n\treturn NewEntry(logger)\n}\n\nfunc (logger *Logger) releaseEntry(entry *Entry) {\n\tentry.Data = map[string]any{}\n\tlogger.entryPool.Put(entry)\n}\n\n// WithField allocates a new entry and adds a field to it.\n// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to\n// this new returned entry.\n// If you want multiple fields, use `WithFields`.\nfunc (logger *Logger) WithField(key string, value any) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithField(key, value)\n}\n\n// WithFields adds a struct of fields to the log entry. It calls [Entry.WithField]\n// for each Field.\nfunc (logger *Logger) WithFields(fields Fields) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithFields(fields)\n}\n\n// WithError adds an error as single field to the log entry.  It calls\n// [Entry.WithError] for the given error.\nfunc (logger *Logger) WithError(err error) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithError(err)\n}\n\n// WithContext add a context to the log entry.\nfunc (logger *Logger) WithContext(ctx context.Context) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithContext(ctx)\n}\n\n// WithTime overrides the time of the log entry.\nfunc (logger *Logger) WithTime(t time.Time) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithTime(t)\n}\n\nfunc (logger *Logger) Logf(level Level, format string, args ...any) {\n\tif logger.IsLevelEnabled(level) {\n\t\tentry := logger.newEntry()\n\t\tentry.Logf(level, format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Tracef(format string, args ...any) {\n\tlogger.Logf(TraceLevel, format, args...)\n}\n\nfunc (logger *Logger) Debugf(format string, args ...any) {\n\tlogger.Logf(DebugLevel, format, args...)\n}\n\nfunc (logger *Logger) Infof(format string, args ...any) {\n\tlogger.Logf(InfoLevel, format, args...)\n}\n\nfunc (logger *Logger) Printf(format string, args ...any) {\n\tentry := logger.newEntry()\n\tentry.Printf(format, args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnf(format string, args ...any) {\n\tlogger.Logf(WarnLevel, format, args...)\n}\n\nfunc (logger *Logger) Warningf(format string, args ...any) {\n\tlogger.Warnf(format, args...)\n}\n\nfunc (logger *Logger) Errorf(format string, args ...any) {\n\tlogger.Logf(ErrorLevel, format, args...)\n}\n\nfunc (logger *Logger) Fatalf(format string, args ...any) {\n\tlogger.Logf(FatalLevel, format, args...)\n\tlogger.Exit(1)\n}\n\nfunc (logger *Logger) Panicf(format string, args ...any) {\n\tlogger.Logf(PanicLevel, format, args...)\n}\n\n// Log will log a message at the level given as parameter.\n// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit.\n// For this behaviour Logger.Panic or Logger.Fatal should be used instead.\nfunc (logger *Logger) Log(level Level, args ...any) {\n\tif logger.IsLevelEnabled(level) {\n\t\tentry := logger.newEntry()\n\t\tentry.Log(level, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) LogFn(level Level, fn LogFunction) {\n\tif logger.IsLevelEnabled(level) {\n\t\tentry := logger.newEntry()\n\t\tentry.Log(level, fn()...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Trace(args ...any) {\n\tlogger.Log(TraceLevel, args...)\n}\n\nfunc (logger *Logger) Debug(args ...any) {\n\tlogger.Log(DebugLevel, args...)\n}\n\nfunc (logger *Logger) Info(args ...any) {\n\tlogger.Log(InfoLevel, args...)\n}\n\nfunc (logger *Logger) Print(args ...any) {\n\tentry := logger.newEntry()\n\tentry.Print(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warn(args ...any) {\n\tlogger.Log(WarnLevel, args...)\n}\n\nfunc (logger *Logger) Warning(args ...any) {\n\tlogger.Warn(args...)\n}\n\nfunc (logger *Logger) Error(args ...any) {\n\tlogger.Log(ErrorLevel, args...)\n}\n\nfunc (logger *Logger) Fatal(args ...any) {\n\tlogger.Log(FatalLevel, args...)\n\tlogger.Exit(1)\n}\n\nfunc (logger *Logger) Panic(args ...any) {\n\tlogger.Log(PanicLevel, args...)\n}\n\nfunc (logger *Logger) TraceFn(fn LogFunction) {\n\tlogger.LogFn(TraceLevel, fn)\n}\n\nfunc (logger *Logger) DebugFn(fn LogFunction) {\n\tlogger.LogFn(DebugLevel, fn)\n}\n\nfunc (logger *Logger) InfoFn(fn LogFunction) {\n\tlogger.LogFn(InfoLevel, fn)\n}\n\nfunc (logger *Logger) PrintFn(fn LogFunction) {\n\tentry := logger.newEntry()\n\tentry.Print(fn()...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) WarnFn(fn LogFunction) {\n\tlogger.LogFn(WarnLevel, fn)\n}\n\nfunc (logger *Logger) WarningFn(fn LogFunction) {\n\tlogger.WarnFn(fn)\n}\n\nfunc (logger *Logger) ErrorFn(fn LogFunction) {\n\tlogger.LogFn(ErrorLevel, fn)\n}\n\nfunc (logger *Logger) FatalFn(fn LogFunction) {\n\tlogger.LogFn(FatalLevel, fn)\n\tlogger.Exit(1)\n}\n\nfunc (logger *Logger) PanicFn(fn LogFunction) {\n\tlogger.LogFn(PanicLevel, fn)\n}\n\nfunc (logger *Logger) Logln(level Level, args ...any) {\n\tif logger.IsLevelEnabled(level) {\n\t\tentry := logger.newEntry()\n\t\tentry.Logln(level, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Traceln(args ...any) {\n\tlogger.Logln(TraceLevel, args...)\n}\n\nfunc (logger *Logger) Debugln(args ...any) {\n\tlogger.Logln(DebugLevel, args...)\n}\n\nfunc (logger *Logger) Infoln(args ...any) {\n\tlogger.Logln(InfoLevel, args...)\n}\n\nfunc (logger *Logger) Println(args ...any) {\n\tentry := logger.newEntry()\n\tentry.Println(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnln(args ...any) {\n\tlogger.Logln(WarnLevel, args...)\n}\n\nfunc (logger *Logger) Warningln(args ...any) {\n\tlogger.Warnln(args...)\n}\n\nfunc (logger *Logger) Errorln(args ...any) {\n\tlogger.Logln(ErrorLevel, args...)\n}\n\nfunc (logger *Logger) Fatalln(args ...any) {\n\tlogger.Logln(FatalLevel, args...)\n\tlogger.Exit(1)\n}\n\nfunc (logger *Logger) Panicln(args ...any) {\n\tlogger.Logln(PanicLevel, args...)\n}\n\nfunc (logger *Logger) Exit(code int) {\n\trunHandlers()\n\tif logger.ExitFunc == nil {\n\t\tlogger.ExitFunc = os.Exit\n\t}\n\tlogger.ExitFunc(code)\n}\n\n// SetNoLock disables the lock for situations where a file is opened with\n// appending mode, and safe for concurrent writes to the file (within 4k\n// message on Linux). In these cases user can choose to disable the lock.\nfunc (logger *Logger) SetNoLock() {\n\tlogger.mu.Disable()\n}\n\nfunc (logger *Logger) level() Level {\n\treturn Level(atomic.LoadUint32((*uint32)(&logger.Level)))\n}\n\n// SetLevel sets the logger level.\nfunc (logger *Logger) SetLevel(level Level) {\n\tatomic.StoreUint32((*uint32)(&logger.Level), uint32(level))\n}\n\n// GetLevel returns the logger level.\nfunc (logger *Logger) GetLevel() Level {\n\treturn logger.level()\n}\n\n// AddHook adds a hook to the logger hooks.\nfunc (logger *Logger) AddHook(hook Hook) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.Hooks.Add(hook)\n}\n\n// hooksForLevel returns a snapshot of the hooks registered for the given level.\n// The returned slice is a shallow copy and may be used without holding logger.mu.\nfunc (logger *Logger) hooksForLevel(level Level) []Hook {\n\tlogger.mu.Lock()\n\thooks := logger.Hooks[level]\n\tif len(hooks) == 0 {\n\t\tlogger.mu.Unlock()\n\t\treturn nil\n\t}\n\tout := make([]Hook, len(hooks))\n\tcopy(out, hooks)\n\tlogger.mu.Unlock()\n\treturn out\n}\n\n// IsLevelEnabled checks if logging for the given level is enabled.\nfunc (logger *Logger) IsLevelEnabled(level Level) bool {\n\treturn logger.level() >= level\n}\n\n// SetFormatter sets the logger formatter.\nfunc (logger *Logger) SetFormatter(formatter Formatter) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.Formatter = formatter\n}\n\n// SetOutput sets the logger output.\nfunc (logger *Logger) SetOutput(output io.Writer) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.Out = output\n}\n\nfunc (logger *Logger) SetReportCaller(reportCaller bool) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.ReportCaller = reportCaller\n}\n\n// ReplaceHooks replaces the logger hooks and returns the old ones\nfunc (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\toldHooks := logger.Hooks\n\tlogger.Hooks = hooks\n\treturn oldHooks\n}\n\n// SetBufferPool sets the logger buffer pool.\nfunc (logger *Logger) SetBufferPool(pool BufferPool) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.BufferPool = pool\n}\n"
  },
  {
    "path": "logger_bench_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc BenchmarkDummyLogger(b *testing.B) {\n\tnullf, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0o666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmark(b, nullf, &logrus.TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc BenchmarkDummyLoggerNoLock(b *testing.B) {\n\tnullf, err := os.OpenFile(os.DevNull, os.O_WRONLY|os.O_APPEND, 0o666)\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\tdefer nullf.Close()\n\tdoLoggerBenchmarkNoLock(b, nullf, &logrus.TextFormatter{DisableColors: true}, smallFields)\n}\n\nfunc doLoggerBenchmark(b *testing.B, out *os.File, formatter logrus.Formatter, fields logrus.Fields) {\n\tlogger := logrus.Logger{\n\t\tOut:       out,\n\t\tLevel:     logrus.InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tentry := logger.WithFields(fields) // new entry per goroutine\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter logrus.Formatter, fields logrus.Fields) {\n\tlogger := logrus.Logger{\n\t\tOut:       out,\n\t\tLevel:     logrus.InfoLevel,\n\t\tFormatter: formatter,\n\t}\n\tlogger.SetNoLock()\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tentry := logger.WithFields(fields) // new entry per goroutine\n\t\tfor pb.Next() {\n\t\t\tentry.Info(\"aaa\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkLoggerJSONFormatter(b *testing.B) {\n\tdoLoggerBenchmarkWithFormatter(b, &logrus.JSONFormatter{})\n}\n\nfunc BenchmarkLoggerTextFormatter(b *testing.B) {\n\tdoLoggerBenchmarkWithFormatter(b, &logrus.TextFormatter{})\n}\n\nfunc doLoggerBenchmarkWithFormatter(b *testing.B, f logrus.Formatter) {\n\tb.SetParallelism(100)\n\tlog := logrus.New()\n\tlog.Formatter = f\n\tlog.Out = io.Discard\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlog.\n\t\t\t\tWithField(\"foo1\", \"bar1\").\n\t\t\t\tWithField(\"foo2\", \"bar2\").\n\t\t\t\tInfo(\"this is a dummy log\")\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "logger_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestWarningAndWarninglnFormatting(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := &logrus.Logger{\n\t\tOut: &buf,\n\t\tFormatter: &logrus.TextFormatter{\n\t\t\tDisableColors:          true,\n\t\t\tDisableTimestamp:       true,\n\t\t\tDisableLevelTruncation: true,\n\t\t},\n\t\tHooks: make(logrus.LevelHooks),\n\t\tLevel: logrus.DebugLevel,\n\t}\n\tl.Warning(\"hello\", \"world\")\n\texpected := \"level=warning msg=helloworld\\n\"\n\tassert.Equal(t, expected, buf.String())\n\n\tbuf.Reset()\n\tl.Warningln(\"hello\", \"world\")\n\n\texpected = \"level=warning msg=\\\"hello world\\\"\\n\"\n\tassert.Equal(t, expected, buf.String())\n}\n\ntype testBufferPool struct {\n\tbuffers []*bytes.Buffer\n\tget     int\n}\n\nfunc (p *testBufferPool) Get() *bytes.Buffer {\n\tp.get++\n\treturn new(bytes.Buffer)\n}\n\nfunc (p *testBufferPool) Put(buf *bytes.Buffer) {\n\tp.buffers = append(p.buffers, buf)\n}\n\nfunc TestLogger_SetBufferPool(t *testing.T) {\n\tl := logrus.New()\n\tl.SetOutput(io.Discard)\n\n\tpool := new(testBufferPool)\n\tl.SetBufferPool(pool)\n\n\tl.Info(\"test\")\n\n\tassert.Equal(t, 1, pool.get, \"Logger.SetBufferPool(): The BufferPool.Get() must be called\")\n\tassert.Len(t, pool.buffers, 1, \"Logger.SetBufferPool(): The BufferPool.Put() must be called\")\n}\n"
  },
  {
    "path": "logrus.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n// Fields type, used to pass to [WithFields].\ntype Fields map[string]any\n\n// Level type\n//\n//nolint:recvcheck // the methods of \"Entry\" use pointer receiver and non-pointer receiver.\ntype Level uint32\n\n// Convert the Level to a string. E.g. [PanicLevel] becomes \"panic\".\nfunc (level Level) String() string {\n\tswitch level {\n\tcase TraceLevel:\n\t\treturn \"trace\"\n\tcase DebugLevel:\n\t\treturn \"debug\"\n\tcase InfoLevel:\n\t\treturn \"info\"\n\tcase WarnLevel:\n\t\treturn \"warning\"\n\tcase ErrorLevel:\n\t\treturn \"error\"\n\tcase FatalLevel:\n\t\treturn \"fatal\"\n\tcase PanicLevel:\n\t\treturn \"panic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\n// ParseLevel takes a string level and returns the Logrus log level constant.\nfunc ParseLevel(lvl string) (Level, error) {\n\treturn parseLevel([]byte(lvl))\n}\n\nfunc parseLevel(b []byte) (Level, error) {\n\tswitch {\n\tcase bytes.EqualFold(b, []byte(\"panic\")):\n\t\treturn PanicLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"fatal\")):\n\t\treturn FatalLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"error\")):\n\t\treturn ErrorLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"warn\")),\n\t\tbytes.EqualFold(b, []byte(\"warning\")):\n\t\treturn WarnLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"info\")):\n\t\treturn InfoLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"debug\")):\n\t\treturn DebugLevel, nil\n\tcase bytes.EqualFold(b, []byte(\"trace\")):\n\t\treturn TraceLevel, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"not a valid logrus Level: %q\", b)\n\t}\n}\n\n// UnmarshalText implements encoding.TextUnmarshaler.\nfunc (level *Level) UnmarshalText(text []byte) error {\n\tl, err := parseLevel(text)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*level = l\n\n\treturn nil\n}\n\nfunc (level Level) MarshalText() ([]byte, error) {\n\tswitch level {\n\tcase TraceLevel, DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel:\n\t\treturn []byte(level.String()), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"not a valid logrus level %d\", level)\n\t}\n}\n\n// AllLevels exposing all logging levels.\nvar AllLevels = []Level{\n\tPanicLevel,\n\tFatalLevel,\n\tErrorLevel,\n\tWarnLevel,\n\tInfoLevel,\n\tDebugLevel,\n\tTraceLevel,\n}\n\n// These are the different logging levels. You can set the logging level to log\n// on your instance of logger, obtained with `logrus.New()`.\nconst (\n\t// PanicLevel level, highest level of severity. Logs and then calls panic with the\n\t// message passed to Debug, Info, ...\n\tPanicLevel Level = iota\n\t// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the\n\t// logging level is set to Panic.\n\tFatalLevel\n\t// ErrorLevel level. Logs. Used for errors that should definitely be noted.\n\t// Commonly used for hooks to send errors to an error tracking service.\n\tErrorLevel\n\t// WarnLevel level. Non-critical entries that deserve eyes.\n\tWarnLevel\n\t// InfoLevel level. General operational entries about what's going on inside the\n\t// application.\n\tInfoLevel\n\t// DebugLevel level. Usually only enabled when debugging. Very verbose logging.\n\tDebugLevel\n\t// TraceLevel level. Designates finer-grained informational events than the Debug.\n\tTraceLevel\n)\n\n// Won't compile if StdLogger can't be realized by a log.Logger\nvar (\n\t_ StdLogger = &log.Logger{}\n\t_ StdLogger = &Entry{}\n\t_ StdLogger = &Logger{}\n)\n\n// StdLogger is what your logrus-enabled library should take, that way\n// it'll accept a stdlib logger ([log.Logger]) and a logrus logger.\n// There's no standard interface, so this is the closest we get, unfortunately.\ntype StdLogger interface {\n\tPrint(...any)\n\tPrintf(string, ...any)\n\tPrintln(...any)\n\n\tFatal(...any)\n\tFatalf(string, ...any)\n\tFatalln(...any)\n\n\tPanic(...any)\n\tPanicf(string, ...any)\n\tPanicln(...any)\n}\n\n// FieldLogger extends the [StdLogger] interface, generalizing\n// the [Entry] and [Logger] types.\ntype FieldLogger interface {\n\tWithField(key string, value any) *Entry\n\tWithFields(fields Fields) *Entry\n\tWithError(err error) *Entry\n\n\tDebugf(format string, args ...any)\n\tInfof(format string, args ...any)\n\tPrintf(format string, args ...any)\n\tWarnf(format string, args ...any)\n\tWarningf(format string, args ...any)\n\tErrorf(format string, args ...any)\n\tFatalf(format string, args ...any)\n\tPanicf(format string, args ...any)\n\n\tDebug(args ...any)\n\tInfo(args ...any)\n\tPrint(args ...any)\n\tWarn(args ...any)\n\tWarning(args ...any)\n\tError(args ...any)\n\tFatal(args ...any)\n\tPanic(args ...any)\n\n\tDebugln(args ...any)\n\tInfoln(args ...any)\n\tPrintln(args ...any)\n\tWarnln(args ...any)\n\tWarningln(args ...any)\n\tErrorln(args ...any)\n\tFatalln(args ...any)\n\tPanicln(args ...any)\n\n\t// IsDebugEnabled() bool\n\t// IsInfoEnabled() bool\n\t// IsWarnEnabled() bool\n\t// IsErrorEnabled() bool\n\t// IsFatalEnabled() bool\n\t// IsPanicEnabled() bool\n}\n\n// Ext1FieldLogger (the first extension to [FieldLogger]) is superfluous, it is\n// here for consistency. Do not use. Use [FieldLogger], [Logger] or [Entry]\n// instead.\ntype Ext1FieldLogger interface {\n\tFieldLogger\n\tTracef(format string, args ...any)\n\tTrace(args ...any)\n\tTraceln(args ...any)\n}\n"
  },
  {
    "path": "logrus_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t. \"github.com/sirupsen/logrus\"\n\t. \"github.com/sirupsen/logrus/internal/testutils\"\n)\n\n// TestReportCaller verifies that when ReportCaller is set, the 'func' field\n// is added, and when it is unset it is not set or modified\n// Verify that functions within the Logrus package aren't considered when\n// discovering the caller.\nfunc TestReportCallerWhenConfigured(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.ReportCaller = false\n\t\tlog.Print(\"testNoCaller\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"testNoCaller\", fields[\"msg\"])\n\t\tassert.Equal(t, \"info\", fields[\"level\"])\n\t\tassert.Nil(t, fields[\"func\"])\n\t})\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.ReportCaller = true\n\t\tlog.Print(\"testWithCaller\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"testWithCaller\", fields[\"msg\"])\n\t\tassert.Equal(t, \"info\", fields[\"level\"])\n\t\tassert.Equal(t,\n\t\t\t\"github.com/sirupsen/logrus_test.TestReportCallerWhenConfigured.func3\", fields[FieldKeyFunc])\n\t})\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.ReportCaller = true\n\t\tlog.Formatter.(*JSONFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {\n\t\t\treturn \"somekindoffunc\", \"thisisafilename\"\n\t\t}\n\t\tlog.Print(\"testWithCallerPrettyfier\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"somekindoffunc\", fields[FieldKeyFunc])\n\t\tassert.Equal(t, \"thisisafilename\", fields[FieldKeyFile])\n\t})\n\n\tLogAndAssertText(t, func(log *Logger) {\n\t\tlog.ReportCaller = true\n\t\tlog.Formatter.(*TextFormatter).CallerPrettyfier = func(f *runtime.Frame) (string, string) {\n\t\t\treturn \"somekindoffunc\", \"thisisafilename\"\n\t\t}\n\t\tlog.Print(\"testWithCallerPrettyfier\")\n\t}, func(fields map[string]string) {\n\t\tassert.Equal(t, \"somekindoffunc\", fields[FieldKeyFunc])\n\t\tassert.Equal(t, \"thisisafilename\", fields[FieldKeyFile])\n\t})\n}\n\nfunc logSomething(t *testing.T, message string) Fields {\n\tvar buffer bytes.Buffer\n\tvar fields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\tlogger.ReportCaller = true\n\n\tentry := logger.WithFields(Fields{\n\t\t\"foo\": \"bar\",\n\t})\n\n\tentry.Info(message)\n\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err)\n\n\treturn fields\n}\n\n// TestReportCallerHelperDirect - verify reference when logging from a regular function\nfunc TestReportCallerHelperDirect(t *testing.T) {\n\tfields := logSomething(t, \"direct\")\n\n\tassert.Equal(t, \"direct\", fields[\"msg\"])\n\tassert.Equal(t, \"info\", fields[\"level\"])\n\tassert.Regexp(t, \"github.com/.*/logrus_test.logSomething\", fields[\"func\"])\n}\n\n// TestReportCallerHelperDirect - verify reference when logging from a function called via pointer\nfunc TestReportCallerHelperViaPointer(t *testing.T) {\n\tfptr := logSomething\n\tfields := fptr(t, \"via pointer\")\n\n\tassert.Equal(t, \"via pointer\", fields[\"msg\"])\n\tassert.Equal(t, \"info\", fields[\"level\"])\n\tassert.Regexp(t, \"github.com/.*/logrus_test.logSomething\", fields[\"func\"])\n}\n\nfunc TestPrint(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Print(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t\tassert.Equal(t, \"info\", fields[\"level\"])\n\t})\n}\n\nfunc TestInfo(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t\tassert.Equal(t, \"info\", fields[\"level\"])\n\t})\n}\n\nfunc TestWarn(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Warn(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t\tassert.Equal(t, \"warning\", fields[\"level\"])\n\t})\n}\n\nfunc TestLog(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Log(WarnLevel, \"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t\tassert.Equal(t, \"warning\", fields[\"level\"])\n\t})\n}\n\nfunc TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Infoln(\"test\", \"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test test\", fields[\"msg\"])\n\t})\n}\n\nfunc TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Infoln(\"test\", 10)\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test 10\", fields[\"msg\"])\n\t})\n}\n\nfunc TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Infoln(10, 10)\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"10 10\", fields[\"msg\"])\n\t})\n}\n\nfunc TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Infoln(10, 10)\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"10 10\", fields[\"msg\"])\n\t})\n}\n\nfunc TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Info(\"test\", 10)\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test10\", fields[\"msg\"])\n\t})\n}\n\nfunc TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.Info(\"test\", \"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"testtest\", fields[\"msg\"])\n\t})\n}\n\nfunc TestWithFieldsShouldAllowAssignments(t *testing.T) {\n\tvar buffer bytes.Buffer\n\tvar fields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\n\tlocalLog := logger.WithFields(Fields{\n\t\t\"key1\": \"value1\",\n\t})\n\n\tlocalLog.WithField(\"key2\", \"value2\").Info(\"test\")\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"value2\", fields[\"key2\"])\n\tassert.Equal(t, \"value1\", fields[\"key1\"])\n\n\tbuffer = bytes.Buffer{}\n\tfields = Fields{}\n\tlocalLog.Info(\"test\")\n\terr = json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err)\n\n\t_, ok := fields[\"key2\"]\n\tassert.False(t, ok)\n\tassert.Equal(t, \"value1\", fields[\"key1\"])\n}\n\nfunc TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithField(\"msg\", \"hello\").Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t})\n}\n\nfunc TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithField(\"msg\", \"hello\").Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"test\", fields[\"msg\"])\n\t\tassert.Equal(t, \"hello\", fields[\"fields.msg\"])\n\t})\n}\n\nfunc TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithField(\"time\", \"hello\").Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"hello\", fields[\"fields.time\"])\n\t})\n}\n\nfunc TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithField(\"level\", 1).Info(\"test\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, \"info\", fields[\"level\"])\n\t\tassert.InDelta(t, 1.0, fields[\"fields.level\"], 0.0001) // JSON has floats only\n\t})\n}\n\nfunc TestDefaultFieldsAreNotPrefixed(t *testing.T) {\n\tLogAndAssertText(t, func(log *Logger) {\n\t\tll := log.WithField(\"herp\", \"derp\")\n\t\tll.Info(\"hello\")\n\t\tll.Info(\"bye\")\n\t}, func(fields map[string]string) {\n\t\tfor _, fieldName := range []string{\"fields.level\", \"fields.time\", \"fields.msg\"} {\n\t\t\tif _, ok := fields[fieldName]; ok {\n\t\t\t\tt.Fatalf(\"should not have prefixed %q: %v\", fieldName, fields)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestWithTimeShouldOverrideTime(t *testing.T) {\n\tnow := time.Now().Add(24 * time.Hour)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithTime(now).Info(\"foobar\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, fields[\"time\"], now.Format(time.RFC3339))\n\t})\n}\n\nfunc TestWithTimeShouldNotOverrideFields(t *testing.T) {\n\tnow := time.Now().Add(24 * time.Hour)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithField(\"herp\", \"derp\").WithTime(now).Info(\"blah\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, now.Format(time.RFC3339), fields[\"time\"])\n\t\tassert.Equal(t, \"derp\", fields[\"herp\"])\n\t})\n}\n\nfunc TestWithFieldShouldNotOverrideTime(t *testing.T) {\n\tnow := time.Now().Add(24 * time.Hour)\n\n\tLogAndAssertJSON(t, func(log *Logger) {\n\t\tlog.WithTime(now).WithField(\"herp\", \"derp\").Info(\"blah\")\n\t}, func(fields Fields) {\n\t\tassert.Equal(t, now.Format(time.RFC3339), fields[\"time\"])\n\t\tassert.Equal(t, \"derp\", fields[\"herp\"])\n\t})\n}\n\nfunc TestTimeOverrideMultipleLogs(t *testing.T) {\n\tvar buffer bytes.Buffer\n\tvar firstFields, secondFields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tformatter := new(JSONFormatter)\n\tformatter.TimestampFormat = time.StampMilli\n\tlogger.Formatter = formatter\n\n\tllog := logger.WithField(\"herp\", \"derp\")\n\tllog.Info(\"foo\")\n\n\terr := json.Unmarshal(buffer.Bytes(), &firstFields)\n\trequire.NoError(t, err, \"should have decoded first message\")\n\n\tbuffer.Reset()\n\n\ttime.Sleep(10 * time.Millisecond)\n\tllog.Info(\"bar\")\n\n\terr = json.Unmarshal(buffer.Bytes(), &secondFields)\n\trequire.NoError(t, err, \"should have decoded second message\")\n\n\tassert.NotEqual(t, firstFields[\"time\"], secondFields[\"time\"], \"timestamps should not be equal\")\n}\n\nfunc TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {\n\tvar buffer bytes.Buffer\n\tvar fields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\n\tllog := logger.WithField(\"context\", \"eating raw fish\")\n\n\tllog.Info(\"looks delicious\")\n\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err, \"should have decoded first message\")\n\tassert.Len(t, fields, 4, \"should only have msg/time/level/context fields\")\n\tassert.Equal(t, \"looks delicious\", fields[\"msg\"])\n\tassert.Equal(t, \"eating raw fish\", fields[\"context\"])\n\n\tbuffer.Reset()\n\n\tllog.Warn(\"omg it is!\")\n\n\terr = json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err, \"should have decoded second message\")\n\tassert.Len(t, fields, 4, \"should only have msg/time/level/context fields\")\n\tassert.Equal(t, \"omg it is!\", fields[\"msg\"])\n\tassert.Equal(t, \"eating raw fish\", fields[\"context\"])\n\tassert.Nil(t, fields[\"fields.msg\"], \"should not have prefixed previous `msg` entry\")\n}\n\nfunc TestNestedLoggingReportsCorrectCaller(t *testing.T) {\n\tvar buffer bytes.Buffer\n\tvar fields Fields\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\tlogger.ReportCaller = true\n\n\tllog := logger.WithField(\"context\", \"eating raw fish\")\n\n\tllog.Info(\"looks delicious\")\n\t_, _, line, _ := runtime.Caller(0)\n\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err, \"should have decoded first message\")\n\tassert.Len(t, fields, 6, \"should have msg/time/level/func/context fields\")\n\tassert.Equal(t, \"looks delicious\", fields[\"msg\"])\n\tassert.Equal(t, \"eating raw fish\", fields[\"context\"])\n\tassert.Equal(t,\n\t\t\"github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller\", fields[\"func\"])\n\tcwd, err := os.Getwd()\n\trequire.NoError(t, err)\n\tassert.Equal(t, filepath.ToSlash(fmt.Sprintf(\"%s/logrus_test.go:%d\", cwd, line-1)), filepath.ToSlash(fields[\"file\"].(string)))\n\n\tbuffer.Reset()\n\n\tlogger.WithFields(Fields{\n\t\t\"Clyde\": \"Stubblefield\",\n\t}).WithFields(Fields{\n\t\t\"Jab'o\": \"Starks\",\n\t}).WithFields(Fields{\n\t\t\"uri\": \"https://www.youtube.com/watch?v=V5DTznu-9v0\",\n\t}).WithFields(Fields{\n\t\t\"func\": \"y drummer\",\n\t}).WithFields(Fields{\n\t\t\"James\": \"Brown\",\n\t}).Print(\"The hardest workin' man in show business\")\n\t_, _, line, _ = runtime.Caller(0)\n\n\terr = json.Unmarshal(buffer.Bytes(), &fields)\n\trequire.NoError(t, err, \"should have decoded second message\")\n\tassert.Len(t, fields, 11, \"should have all builtin fields plus foo,bar,baz,...\")\n\tassert.Equal(t, \"Stubblefield\", fields[\"Clyde\"])\n\tassert.Equal(t, \"Starks\", fields[\"Jab'o\"])\n\tassert.Equal(t, \"https://www.youtube.com/watch?v=V5DTznu-9v0\", fields[\"uri\"])\n\tassert.Equal(t, \"y drummer\", fields[\"fields.func\"])\n\tassert.Equal(t, \"Brown\", fields[\"James\"])\n\tassert.Equal(t, \"The hardest workin' man in show business\", fields[\"msg\"])\n\tassert.Nil(t, fields[\"fields.msg\"], \"should not have prefixed previous `msg` entry\")\n\tassert.Equal(t,\n\t\t\"github.com/sirupsen/logrus_test.TestNestedLoggingReportsCorrectCaller\", fields[\"func\"])\n\trequire.NoError(t, err)\n\tassert.Equal(t, filepath.ToSlash(fmt.Sprintf(\"%s/logrus_test.go:%d\", cwd, line-1)), filepath.ToSlash(fields[\"file\"].(string)))\n\n\tlogger.ReportCaller = false // return to default value\n}\n\nfunc logLoop(iterations int, reportCaller bool) {\n\tvar buffer bytes.Buffer\n\n\tlogger := New()\n\tlogger.Out = &buffer\n\tlogger.Formatter = new(JSONFormatter)\n\tlogger.ReportCaller = reportCaller\n\n\tfor i := range iterations {\n\t\tlogger.Infof(\"round %d of %d\", i, iterations)\n\t}\n}\n\n// Assertions for upper bounds to reporting overhead\nfunc TestCallerReportingOverhead(t *testing.T) {\n\titerations := 5000\n\tbefore := time.Now()\n\tlogLoop(iterations, false)\n\tduring := time.Now()\n\tlogLoop(iterations, true)\n\tafter := time.Now()\n\n\telapsedNotReporting := during.Sub(before).Nanoseconds()\n\telapsedReporting := after.Sub(during).Nanoseconds()\n\n\tmaxDelta := 1 * time.Second\n\tassert.WithinDuration(t, during, before, maxDelta,\n\t\t\"%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)\",\n\t\titerations, maxDelta.Seconds(), elapsedNotReporting)\n\tassert.WithinDuration(t, after, during, maxDelta,\n\t\t\"%d log calls without caller name lookup takes less than %d second(s) (was %d nanoseconds)\",\n\t\titerations, maxDelta.Seconds(), elapsedReporting)\n}\n\nfunc TestConvertLevelToString(t *testing.T) {\n\tassert.Equal(t, \"trace\", TraceLevel.String())\n\tassert.Equal(t, \"debug\", DebugLevel.String())\n\tassert.Equal(t, \"info\", InfoLevel.String())\n\tassert.Equal(t, \"warning\", WarnLevel.String())\n\tassert.Equal(t, \"error\", ErrorLevel.String())\n\tassert.Equal(t, \"fatal\", FatalLevel.String())\n\tassert.Equal(t, \"panic\", PanicLevel.String())\n}\n\nfunc TestParseLevel(t *testing.T) {\n\tl, err := ParseLevel(\"panic\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, PanicLevel, l)\n\n\tl, err = ParseLevel(\"PANIC\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, PanicLevel, l)\n\n\tl, err = ParseLevel(\"fatal\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, FatalLevel, l)\n\n\tl, err = ParseLevel(\"FATAL\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, FatalLevel, l)\n\n\tl, err = ParseLevel(\"error\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, ErrorLevel, l)\n\n\tl, err = ParseLevel(\"ERROR\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, ErrorLevel, l)\n\n\tl, err = ParseLevel(\"warn\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, WarnLevel, l)\n\n\tl, err = ParseLevel(\"WARN\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, WarnLevel, l)\n\n\tl, err = ParseLevel(\"warning\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, WarnLevel, l)\n\n\tl, err = ParseLevel(\"WARNING\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, WarnLevel, l)\n\n\tl, err = ParseLevel(\"info\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, InfoLevel, l)\n\n\tl, err = ParseLevel(\"INFO\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, InfoLevel, l)\n\n\tl, err = ParseLevel(\"debug\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, DebugLevel, l)\n\n\tl, err = ParseLevel(\"DEBUG\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, DebugLevel, l)\n\n\tl, err = ParseLevel(\"trace\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, TraceLevel, l)\n\n\tl, err = ParseLevel(\"TRACE\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, TraceLevel, l)\n\n\t_, err = ParseLevel(\"invalid\")\n\tassert.Equal(t, \"not a valid logrus Level: \\\"invalid\\\"\", err.Error())\n}\n\nfunc TestLevelString(t *testing.T) {\n\tvar loggerlevel Level = 32000\n\n\t_ = loggerlevel.String()\n}\n\nfunc TestGetSetLevelRace(t *testing.T) {\n\twg := sync.WaitGroup{}\n\tfor i := range 100 {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tif i%2 == 0 {\n\t\t\t\tSetLevel(InfoLevel)\n\t\t\t} else {\n\t\t\t\tGetLevel()\n\t\t\t}\n\t\t}(i)\n\n\t}\n\twg.Wait()\n}\n\nfunc TestLoggingRace(t *testing.T) {\n\tlogger := New()\n\tlogger.SetOutput(io.Discard)\n\n\tvar wg sync.WaitGroup\n\twg.Add(100)\n\n\tfor range 100 {\n\t\tgo func() {\n\t\t\tlogger.Info(\"info\")\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n\nfunc TestLoggingRaceWithHooksOnEntry(t *testing.T) {\n\tlogger := New()\n\tlogger.SetOutput(io.Discard)\n\thook := new(ModifyHook)\n\tlogger.AddHook(hook)\n\tentry := logger.WithField(\"context\", \"clue\")\n\n\tvar (\n\t\twg    sync.WaitGroup\n\t\tmtx   sync.Mutex\n\t\tstart bool\n\t)\n\n\tcond := sync.NewCond(&mtx)\n\n\twg.Add(100)\n\n\tfor range 50 {\n\t\tgo func() {\n\t\t\tcond.L.Lock()\n\t\t\tfor !start {\n\t\t\t\tcond.Wait()\n\t\t\t}\n\t\t\tcond.L.Unlock()\n\t\t\tfor range 100 {\n\t\t\t\tentry.Info(\"info\")\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\tfor range 50 {\n\t\tgo func() {\n\t\t\tcond.L.Lock()\n\t\t\tfor !start {\n\t\t\t\tcond.Wait()\n\t\t\t}\n\t\t\tcond.L.Unlock()\n\t\t\tfor range 100 {\n\t\t\t\tentry.WithField(\"another field\", \"with some data\").Info(\"info\")\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\tcond.L.Lock()\n\tstart = true\n\tcond.L.Unlock()\n\tcond.Broadcast()\n\twg.Wait()\n}\n\nfunc TestReplaceHooks(t *testing.T) {\n\told, cur := &TestHook{}, &TestHook{}\n\n\tlogger := New()\n\tlogger.SetOutput(io.Discard)\n\tlogger.AddHook(old)\n\n\thooks := make(LevelHooks)\n\thooks.Add(cur)\n\treplaced := logger.ReplaceHooks(hooks)\n\n\tlogger.Info(\"test\")\n\n\tassert.False(t, old.Fired)\n\tassert.True(t, cur.Fired)\n\n\tlogger.ReplaceHooks(replaced)\n\tlogger.Info(\"test\")\n\tassert.True(t, old.Fired)\n}\n\n// Compile test\nfunc TestLogrusInterfaces(t *testing.T) {\n\tvar buffer bytes.Buffer\n\t// This verifies FieldLogger and Ext1FieldLogger work as designed.\n\t// Please don't use them. Use Logger and Entry directly.\n\tfn := func(xl Ext1FieldLogger) {\n\t\tvar l FieldLogger = xl\n\t\tb := l.WithField(\"key\", \"value\")\n\t\tb.Debug(\"Test\")\n\t}\n\t// test logger\n\tlogger := New()\n\tlogger.Out = &buffer\n\tfn(logger)\n\n\t// test Entry\n\te := logger.WithField(\"another\", \"value\")\n\tfn(e)\n}\n\n// Implements io.Writer using channels for synchronization, so we can wait on\n// the Entry.Writer goroutine to write in a non-racey way. This does assume that\n// there is a single call to Logger.Out for each message.\ntype channelWriter chan []byte\n\nfunc (cw channelWriter) Write(p []byte) (int, error) {\n\tcw <- p\n\treturn len(p), nil\n}\n\nfunc TestEntryWriter(t *testing.T) {\n\tcw := channelWriter(make(chan []byte, 1))\n\tlog := New()\n\tlog.Out = cw\n\tlog.Formatter = new(JSONFormatter)\n\t_, err := log.WithField(\"foo\", \"bar\").WriterLevel(WarnLevel).Write([]byte(\"hello\\n\"))\n\tif err != nil {\n\t\tt.Error(\"unexecpted error\", err)\n\t}\n\n\tbs := <-cw\n\tvar fields Fields\n\terr = json.Unmarshal(bs, &fields)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"bar\", fields[\"foo\"])\n\tassert.Equal(t, \"warning\", fields[\"level\"])\n}\n\nfunc TestLogLevelEnabled(t *testing.T) {\n\tlog := New()\n\tlog.SetLevel(PanicLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.False(t, log.IsLevelEnabled(FatalLevel))\n\tassert.False(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.False(t, log.IsLevelEnabled(WarnLevel))\n\tassert.False(t, log.IsLevelEnabled(InfoLevel))\n\tassert.False(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(FatalLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.False(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.False(t, log.IsLevelEnabled(WarnLevel))\n\tassert.False(t, log.IsLevelEnabled(InfoLevel))\n\tassert.False(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(ErrorLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.True(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.False(t, log.IsLevelEnabled(WarnLevel))\n\tassert.False(t, log.IsLevelEnabled(InfoLevel))\n\tassert.False(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(WarnLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.True(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.True(t, log.IsLevelEnabled(WarnLevel))\n\tassert.False(t, log.IsLevelEnabled(InfoLevel))\n\tassert.False(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(InfoLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.True(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.True(t, log.IsLevelEnabled(WarnLevel))\n\tassert.True(t, log.IsLevelEnabled(InfoLevel))\n\tassert.False(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(DebugLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.True(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.True(t, log.IsLevelEnabled(WarnLevel))\n\tassert.True(t, log.IsLevelEnabled(InfoLevel))\n\tassert.True(t, log.IsLevelEnabled(DebugLevel))\n\tassert.False(t, log.IsLevelEnabled(TraceLevel))\n\n\tlog.SetLevel(TraceLevel)\n\tassert.True(t, log.IsLevelEnabled(PanicLevel))\n\tassert.True(t, log.IsLevelEnabled(FatalLevel))\n\tassert.True(t, log.IsLevelEnabled(ErrorLevel))\n\tassert.True(t, log.IsLevelEnabled(WarnLevel))\n\tassert.True(t, log.IsLevelEnabled(InfoLevel))\n\tassert.True(t, log.IsLevelEnabled(DebugLevel))\n\tassert.True(t, log.IsLevelEnabled(TraceLevel))\n}\n\nfunc TestReportCallerOnTextFormatter(t *testing.T) {\n\tl := New()\n\tl.SetOutput(io.Discard)\n\n\tl.Formatter.(*TextFormatter).ForceColors = true\n\tl.Formatter.(*TextFormatter).DisableColors = false\n\tl.WithFields(Fields{\"func\": \"func\", \"file\": \"file\"}).Info(\"test\")\n\n\tl.Formatter.(*TextFormatter).ForceColors = false\n\tl.Formatter.(*TextFormatter).DisableColors = true\n\tl.WithFields(Fields{\"func\": \"func\", \"file\": \"file\"}).Info(\"test\")\n}\n\nfunc TestSetReportCallerRace(t *testing.T) {\n\tl := New()\n\tl.Out = io.Discard\n\tl.SetReportCaller(true)\n\n\tvar wg sync.WaitGroup\n\twg.Add(100)\n\n\tfor range 100 {\n\t\tgo func() {\n\t\t\tl.Error(\"Some Error\")\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n"
  },
  {
    "path": "terminal_check_appengine.go",
    "content": "//go:build appengine\n\npackage logrus\n\nfunc checkIfTerminal(_ any) bool {\n\treturn true\n}\n"
  },
  {
    "path": "terminal_check_bsd.go",
    "content": "//go:build darwin || dragonfly || freebsd || netbsd || openbsd || hurd\n\npackage logrus\n\nimport \"golang.org/x/sys/unix\"\n\nconst ioctlReadTermios = unix.TIOCGETA\n\nfunc isTerminal(fd int) bool {\n\t_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)\n\treturn err == nil\n}\n"
  },
  {
    "path": "terminal_check_no_terminal.go",
    "content": "//go:build js || nacl || plan9 || wasi || wasip1\n\npackage logrus\n\nfunc checkIfTerminal(_ any) bool {\n\treturn false\n}\n"
  },
  {
    "path": "terminal_check_notappengine.go",
    "content": "//go:build !appengine && !js && !windows && !nacl && !plan9 && !wasi && !wasip1\n\npackage logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\nfunc checkIfTerminal(w io.Writer) bool {\n\tswitch v := w.(type) {\n\tcase *os.File:\n\t\tfd := v.Fd()\n\t\tif fd > uintptr(^uint(0)>>1) {\n\t\t\treturn false\n\t\t}\n\t\treturn isTerminal(int(fd))\n\tdefault:\n\t\treturn false\n\t}\n}\n"
  },
  {
    "path": "terminal_check_solaris.go",
    "content": "//go:build solaris\n\npackage logrus\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\n// IsTerminal returns true if the given file descriptor is a terminal.\nfunc isTerminal(fd int) bool {\n\t_, err := unix.IoctlGetTermio(fd, unix.TCGETA)\n\treturn err == nil\n}\n"
  },
  {
    "path": "terminal_check_unix.go",
    "content": "//go:build linux || aix || zos\n\npackage logrus\n\nimport \"golang.org/x/sys/unix\"\n\nconst ioctlReadTermios = unix.TCGETS\n\nfunc isTerminal(fd int) bool {\n\t_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)\n\treturn err == nil\n}\n"
  },
  {
    "path": "terminal_check_windows.go",
    "content": "//go:build windows && !appengine\n\npackage logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\nfunc checkIfTerminal(w io.Writer) bool {\n\tswitch v := w.(type) {\n\tcase *os.File:\n\t\thandle := windows.Handle(v.Fd())\n\t\tvar mode uint32\n\t\tif err := windows.GetConsoleMode(handle, &mode); err != nil {\n\t\t\treturn false\n\t\t}\n\t\tmode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING\n\t\tif err := windows.SetConsoleMode(handle, mode); err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "text_formatter.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"maps\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar baseTimestamp = time.Now()\n\n// TextFormatter formats logs into text.\n//\n// Output is logfmt-like: key=value pairs separated by spaces. Field keys are\n// written as-is (unquoted and unescaped) in the plain (non-colored) format;\n// only field values may be quoted depending on DisableQuote, ForceQuote,\n// QuoteEmptyFields, and the value content.\n//\n// When colors are enabled, ANSI escape sequences may be added for presentation.\n// For fully escaped structured output (including safe keys), use JSONFormatter.\ntype TextFormatter struct {\n\t// Set to true to bypass checking for a TTY before outputting colors.\n\tForceColors bool\n\n\t// Force disabling colors.\n\tDisableColors bool\n\n\t// Force quoting of all values\n\tForceQuote bool\n\n\t// DisableQuote disables quoting for all values.\n\t// DisableQuote will have a lower priority than ForceQuote.\n\t// If both of them are set to true, quote will be forced on all values.\n\tDisableQuote bool\n\n\t// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/\n\tEnvironmentOverrideColors bool\n\n\t// Disable timestamp logging. useful when output is redirected to logging\n\t// system that already adds timestamps.\n\tDisableTimestamp bool\n\n\t// Enable logging the full timestamp when a TTY is attached instead of just\n\t// the time passed since beginning of execution.\n\tFullTimestamp bool\n\n\t// TimestampFormat to use for display when a full timestamp is printed.\n\t// The format to use is the same than for time.Format or time.Parse from the standard\n\t// library.\n\t// The standard Library already provides a set of predefined format.\n\tTimestampFormat string\n\n\t// The fields are sorted by default for a consistent output. For applications\n\t// that log extremely frequently and don't use the JSON formatter this may not\n\t// be desired.\n\tDisableSorting bool\n\n\t// The keys sorting function, when uninitialized it uses slices.Sort.\n\tSortingFunc func([]string)\n\n\t// Disables the truncation of the level text to 4 characters.\n\tDisableLevelTruncation bool\n\n\t// PadLevelText Adds padding the level text so that all the levels output at the same length\n\t// PadLevelText is a superset of the DisableLevelTruncation option\n\tPadLevelText bool\n\n\t// QuoteEmptyFields will wrap empty fields in quotes if true\n\tQuoteEmptyFields bool\n\n\t// Whether the logger's out is to a terminal. Don't use this field\n\t// directly; use TextFormatter.isTerminal instead.\n\tterminal bool\n\n\t// FieldMap allows users to customize the names of keys for default fields.\n\t// Mapped keys are written as-is, so they should be safe for plain-text output.\n\t//\n\t// As an example:\n\t//\n\t// formatter := &TextFormatter{\n\t// \tFieldMap: FieldMap{\n\t// \t\tFieldKeyTime:  \"@timestamp\",\n\t// \t\tFieldKeyLevel: \"@level\",\n\t// \t\tFieldKeyMsg:   \"@message\",\n\t// \t},\n\t// }\n\tFieldMap FieldMap\n\n\t// CallerPrettyfier can be set by the user to modify the content\n\t// of the function and file keys in the data when ReportCaller is\n\t// activated. If any of the returned value is the empty string the\n\t// corresponding key will be removed from fields.\n\tCallerPrettyfier func(*runtime.Frame) (function string, file string)\n\n\tterminalInitOnce sync.Once\n}\n\nfunc (f *TextFormatter) isTerminal(entry *Entry) bool {\n\tif entry == nil || entry.Logger == nil {\n\t\t// Don't run the terminalInitOnce without a logger, otherwise we'd\n\t\t// cache the default (false) forever even if a logger is attached\n\t\t// later.\n\t\treturn false\n\t}\n\n\tf.terminalInitOnce.Do(func() {\n\t\tentry.Logger.mu.Lock()\n\t\tout := entry.Logger.Out\n\t\tentry.Logger.mu.Unlock()\n\n\t\tf.terminal = checkIfTerminal(out)\n\t})\n\n\treturn f.terminal\n}\n\nfunc (f *TextFormatter) isColored(isTerminal bool) bool {\n\tif f.DisableColors {\n\t\treturn false\n\t}\n\n\tcolored := f.ForceColors || (isTerminal && (runtime.GOOS != \"windows\"))\n\tif !f.EnvironmentOverrideColors {\n\t\treturn colored\n\t}\n\tif force, ok := os.LookupEnv(\"CLICOLOR_FORCE\"); ok {\n\t\treturn force != \"0\"\n\t}\n\tif os.Getenv(\"CLICOLOR\") == \"0\" {\n\t\treturn false\n\t}\n\treturn colored\n}\n\n// Format renders a single log entry\nfunc (f *TextFormatter) Format(entry *Entry) ([]byte, error) {\n\tdata := make(Fields, len(entry.Data))\n\tmaps.Copy(data, entry.Data)\n\tisColored := f.isColored(f.isTerminal(entry))\n\n\tcaller := entry.Caller\n\thasCaller := caller != nil\n\tprefixFieldClashes(data, f.FieldMap, hasCaller)\n\tkeys := make([]string, 0, len(data))\n\tfor k := range data {\n\t\tkeys = append(keys, k)\n\t}\n\n\tb := entry.Buffer\n\tif b == nil {\n\t\tb = new(bytes.Buffer)\n\t}\n\n\tif isColored {\n\t\tf.printColored(b, entry, keys, data)\n\t} else {\n\t\tf.printPlain(b, entry, keys, data)\n\t}\n\n\treturn b.Bytes(), nil\n}\n\nfunc (f *TextFormatter) printPlain(b *bytes.Buffer, entry *Entry, keys []string, data Fields) {\n\tcaller := entry.Caller\n\thasCaller := caller != nil\n\n\tfixedKeys := make([]string, 0, len(keys)+defaultFields)\n\tif !f.DisableTimestamp {\n\t\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))\n\t}\n\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))\n\tif entry.Message != \"\" {\n\t\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))\n\t}\n\tif entry.err != \"\" {\n\t\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))\n\t}\n\n\tvar funcVal, fileVal string\n\tif caller != nil {\n\t\tif f.CallerPrettyfier != nil {\n\t\t\tfuncVal, fileVal = f.CallerPrettyfier(caller)\n\t\t} else {\n\t\t\tfuncVal = caller.Function\n\t\t\tfileVal = caller.File + \":\" + strconv.FormatInt(int64(caller.Line), 10)\n\t\t}\n\n\t\tif funcVal != \"\" {\n\t\t\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))\n\t\t}\n\t\tif fileVal != \"\" {\n\t\t\tfixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))\n\t\t}\n\t}\n\n\tif !f.DisableSorting {\n\t\tif f.SortingFunc == nil {\n\t\t\t// Default sorting does not sort the \"fixed keys\";\n\t\t\t// see https://github.com/sirupsen/logrus/commit/73bc94e60c753099e8bae902f81fbd6e7dd95f26\n\t\t\tslices.Sort(keys)\n\t\t\tfixedKeys = append(fixedKeys, keys...)\n\t\t} else {\n\t\t\tfixedKeys = append(fixedKeys, keys...)\n\t\t\tf.SortingFunc(fixedKeys)\n\t\t}\n\t} else {\n\t\tfixedKeys = append(fixedKeys, keys...)\n\t}\n\n\tfor _, key := range fixedKeys {\n\t\tvar value any\n\t\tswitch {\n\t\tcase key == f.FieldMap.resolve(FieldKeyTime):\n\t\t\tif f.TimestampFormat == \"\" {\n\t\t\t\tvalue = entry.Time.Format(defaultTimestampFormat)\n\t\t\t} else {\n\t\t\t\tvalue = entry.Time.Format(f.TimestampFormat)\n\t\t\t}\n\t\tcase key == f.FieldMap.resolve(FieldKeyLevel):\n\t\t\tvalue = entry.Level.String()\n\t\tcase key == f.FieldMap.resolve(FieldKeyMsg):\n\t\t\tvalue = entry.Message\n\t\tcase key == f.FieldMap.resolve(FieldKeyLogrusError):\n\t\t\tvalue = entry.err\n\t\tcase key == f.FieldMap.resolve(FieldKeyFunc) && hasCaller:\n\t\t\tvalue = funcVal\n\t\tcase key == f.FieldMap.resolve(FieldKeyFile) && hasCaller:\n\t\t\tvalue = fileVal\n\t\tdefault:\n\t\t\tvalue = data[key]\n\t\t}\n\t\tf.appendKeyValue(b, key, value)\n\t}\n\n\tb.WriteByte('\\n')\n}\n\nfunc (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields) {\n\t// Remove a single newline if it already exists in the message to keep\n\t// the behavior of logrus text_formatter the same as the stdlib log package\n\tentry.Message = strings.TrimSuffix(entry.Message, \"\\n\")\n\n\tvar callerText string\n\tif caller := entry.Caller; caller != nil {\n\t\tvar funcVal, fileVal string\n\t\tif f.CallerPrettyfier != nil {\n\t\t\tfuncVal, fileVal = f.CallerPrettyfier(caller)\n\t\t} else {\n\t\t\tif caller.Function != \"\" {\n\t\t\t\tfuncVal = caller.Function + \"()\"\n\t\t\t}\n\t\t\tfileVal = caller.File + \":\" + strconv.FormatInt(int64(caller.Line), 10)\n\t\t}\n\n\t\tif fileVal == \"\" {\n\t\t\tcallerText = funcVal\n\t\t} else if funcVal == \"\" {\n\t\t\tcallerText = fileVal\n\t\t} else {\n\t\t\tcallerText = fileVal + \" \" + funcVal\n\t\t}\n\t}\n\n\tlevelText := levelPrefix(entry.Level, f.DisableLevelTruncation, f.PadLevelText)\n\tswitch {\n\tcase f.DisableTimestamp:\n\t\t_, _ = fmt.Fprintf(b, \"%s%s %-44s \", levelText, callerText, entry.Message)\n\tcase !f.FullTimestamp:\n\t\t_, _ = fmt.Fprintf(b, \"%s[%04d]%s %-44s \", levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), callerText, entry.Message)\n\tdefault:\n\t\ttimestampFormat := f.TimestampFormat\n\t\tif timestampFormat == \"\" {\n\t\t\ttimestampFormat = defaultTimestampFormat\n\t\t}\n\t\t_, _ = fmt.Fprintf(b, \"%s[%s]%s %-44s \", levelText, entry.Time.Format(timestampFormat), callerText, entry.Message)\n\t}\n\n\tif !f.DisableSorting {\n\t\tif f.SortingFunc == nil {\n\t\t\tslices.Sort(keys)\n\t\t} else {\n\t\t\tf.SortingFunc(keys)\n\t\t}\n\t}\n\n\t// Keys use the same color as the level-prefix.\n\tfor _, k := range keys {\n\t\tb.WriteByte(' ')\n\t\tb.WriteString(colorize(entry.Level, k))\n\t\tb.WriteByte('=')\n\t\tf.appendValue(b, data[k])\n\t}\n\n\tb.WriteByte('\\n')\n}\n\n// appendKeyValue writes key=value. Keys are written verbatim (unquoted/unescaped);\n// values are subject to quoting/escaping.\nfunc (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value any) {\n\tif b.Len() > 0 {\n\t\tb.WriteByte(' ')\n\t}\n\tb.WriteString(key)\n\tb.WriteByte('=')\n\tf.appendValue(b, value)\n}\n\nfunc (f *TextFormatter) appendValue(b *bytes.Buffer, value any) {\n\t// Fast paths.\n\tswitch v := value.(type) {\n\tcase string:\n\t\tf.appendString(b, v)\n\t\treturn\n\tcase []byte:\n\t\tf.appendBytes(b, v)\n\t\treturn\n\tcase bool:\n\t\tvar raw [8]byte\n\t\tf.appendBytes(b, strconv.AppendBool(raw[:0], v))\n\t\treturn\n\tcase error:\n\t\tf.appendString(b, v.Error())\n\t\treturn\n\tcase fmt.Stringer:\n\t\tf.appendString(b, v.String())\n\t\treturn\n\t}\n\n\t// Handle common primitives.\n\tvar raw [64]byte\n\tvar num []byte\n\n\tswitch v := value.(type) {\n\tcase int:\n\t\tnum = strconv.AppendInt(raw[:0], int64(v), 10)\n\tcase int8:\n\t\tnum = strconv.AppendInt(raw[:0], int64(v), 10)\n\tcase int16:\n\t\tnum = strconv.AppendInt(raw[:0], int64(v), 10)\n\tcase int32:\n\t\tnum = strconv.AppendInt(raw[:0], int64(v), 10)\n\tcase int64:\n\t\tnum = strconv.AppendInt(raw[:0], v, 10)\n\n\tcase uint:\n\t\tnum = strconv.AppendUint(raw[:0], uint64(v), 10)\n\tcase uint8:\n\t\tnum = strconv.AppendUint(raw[:0], uint64(v), 10)\n\tcase uint16:\n\t\tnum = strconv.AppendUint(raw[:0], uint64(v), 10)\n\tcase uint32:\n\t\tnum = strconv.AppendUint(raw[:0], uint64(v), 10)\n\tcase uint64:\n\t\tnum = strconv.AppendUint(raw[:0], v, 10)\n\tcase uintptr:\n\t\tnum = strconv.AppendUint(raw[:0], uint64(v), 10)\n\n\tcase float32:\n\t\tnum = strconv.AppendFloat(raw[:0], float64(v), 'g', -1, 32)\n\tcase float64:\n\t\tnum = strconv.AppendFloat(raw[:0], v, 'g', -1, 64)\n\n\tdefault:\n\t\tf.appendString(b, fmt.Sprint(value))\n\t\treturn\n\t}\n\n\tf.appendNumeric(b, num)\n}\n\nfunc (f *TextFormatter) appendString(b *bytes.Buffer, s string) {\n\tquote := f.ForceQuote || (f.QuoteEmptyFields && len(s) == 0) || (!f.DisableQuote && needsQuoting(s))\n\tif !quote {\n\t\tb.WriteString(s)\n\t\treturn\n\t}\n\tif len(s) == 0 {\n\t\tb.WriteString(`\"\"`)\n\t\treturn\n\t}\n\n\tvar tmp [128]byte\n\tb.Write(strconv.AppendQuote(tmp[:0], s))\n}\n\nfunc (f *TextFormatter) appendBytes(b *bytes.Buffer, bs []byte) {\n\tquote := f.ForceQuote || (f.QuoteEmptyFields && len(bs) == 0) || (!f.DisableQuote && needsQuotingBytes(bs))\n\tif !quote {\n\t\tb.Write(bs)\n\t\treturn\n\t}\n\tif len(bs) == 0 {\n\t\tb.WriteString(`\"\"`)\n\t\treturn\n\t}\n\n\tvar tmp [128]byte\n\tb.Write(strconv.AppendQuote(tmp[:0], string(bs)))\n}\n\nfunc (f *TextFormatter) appendNumeric(b *bytes.Buffer, out []byte) {\n\tif f.ForceQuote {\n\t\tvar tmp [128]byte\n\t\tb.Write(strconv.AppendQuote(tmp[:0], string(out)))\n\t\treturn\n\t}\n\tb.Write(out)\n}\n\n// needsQuoting returns true if the string contains any byte that\n// requires quoting. It returns false when every byte is \"safe\" according\n// to isSafeByte.\nfunc needsQuoting(s string) bool {\n\t// use an index loop (avoid rune decoding).\n\tfor i := range len(s) {\n\t\tc := s[i]\n\t\tif !isSafeByte(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// needsQuotingBytes returns true if the byte slice contains any byte that\n// requires quoting. It returns false when every byte is \"safe\" according\n// to isSafeByte.\nfunc needsQuotingBytes(bs []byte) bool {\n\tfor _, c := range bs {\n\t\tif !isSafeByte(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// isSafeByte returns true if the byte is allowed unquoted (ASCII and in the allowlist).\n// It purposely uses byte arithmetic (no runes) for performance.\nfunc isSafeByte(ch byte) bool {\n\tok := ch < 0x80 && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))\n\tif ok {\n\t\treturn true\n\t}\n\tswitch ch {\n\tcase '-', '.', '_', '/', '@', '^', '+':\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"
  },
  {
    "path": "text_formatter_test.go",
    "content": "package logrus\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestFormatting(t *testing.T) {\n\ttf := &TextFormatter{DisableColors: true}\n\n\ttestCases := []struct {\n\t\tvalue    string\n\t\texpected string\n\t}{\n\t\t{`foo`, \"time=\\\"0001-01-01T00:00:00Z\\\" level=panic test=foo\\n\"},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tb, _ := tf.Format(WithField(\"test\", tc.value))\n\n\t\tif string(b) != tc.expected {\n\t\t\tt.Errorf(\"formatting expected for %q (result was %q instead of %q)\", tc.value, string(b), tc.expected)\n\t\t}\n\t}\n}\n\nfunc TestQuoting(t *testing.T) {\n\ttf := &TextFormatter{DisableColors: true}\n\n\tcheckQuoting := func(q bool, value any) {\n\t\tb, _ := tf.Format(WithField(\"test\", value))\n\t\t_, after, _ := bytes.Cut(b, ([]byte)(\"test=\"))\n\t\tcont := bytes.Contains(after, []byte(\"\\\"\"))\n\t\tif cont != q {\n\t\t\tif q {\n\t\t\t\tt.Errorf(\"quoting expected for: %#v\", value)\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"quoting not expected for: %#v\", value)\n\t\t\t}\n\t\t}\n\t}\n\n\tcheckQuoting(false, \"\")\n\tcheckQuoting(false, \"abcd\")\n\tcheckQuoting(false, \"v1.0\")\n\tcheckQuoting(false, \"1234567890\")\n\tcheckQuoting(false, \"/foobar\")\n\tcheckQuoting(false, \"foo_bar\")\n\tcheckQuoting(false, \"foo@bar\")\n\tcheckQuoting(false, \"foobar^\")\n\tcheckQuoting(false, \"+/-_^@f.oobar\")\n\tcheckQuoting(true, \"foo\\n\\rbar\")\n\tcheckQuoting(true, \"foobar$\")\n\tcheckQuoting(true, \"&foobar\")\n\tcheckQuoting(true, \"x y\")\n\tcheckQuoting(true, \"x,y\")\n\n\t// New/explicit: bool fast path (never needs quoting unless forced).\n\tcheckQuoting(false, true)\n\tcheckQuoting(false, false)\n\n\t// New/explicit: numeric fast path (never needs quoting unless forced).\n\tcheckQuoting(false, 0)\n\tcheckQuoting(false, int64(-123))\n\tcheckQuoting(false, uint64(123))\n\tcheckQuoting(false, float64(3.14))\n\n\t// New/explicit: []byte fast path.\n\tcheckQuoting(false, []byte(\"abcd\"))\n\tcheckQuoting(true, []byte(\"x y\"))\n\n\t// Error path (string fast path via Error()).\n\tcheckQuoting(false, errors.New(\"invalid\"))\n\tcheckQuoting(true, errors.New(\"invalid argument\"))\n\n\t// Test for quoting empty fields.\n\ttf.QuoteEmptyFields = true\n\tcheckQuoting(true, \"\")\n\tcheckQuoting(false, \"abcd\")\n\tcheckQuoting(true, \"foo\\n\\rbar\")\n\tcheckQuoting(true, errors.New(\"invalid argument\"))\n\n\t// New/explicit: QuoteEmptyFields shouldn't affect non-empty primitives.\n\tcheckQuoting(false, 0)\n\tcheckQuoting(false, true)\n\tcheckQuoting(false, []byte(\"abcd\"))\n\n\t// Test forcing quotes.\n\ttf.ForceQuote = true\n\tcheckQuoting(true, \"\")\n\tcheckQuoting(true, \"abcd\")\n\tcheckQuoting(true, \"foo\\n\\rbar\")\n\tcheckQuoting(true, errors.New(\"invalid argument\"))\n\n\t// New/explicit: ForceQuote should quote numeric/bool/[]byte too.\n\tcheckQuoting(true, 0)\n\tcheckQuoting(true, true)\n\tcheckQuoting(true, []byte(\"abcd\"))\n\n\t// Test forcing quotes when also disabling them.\n\ttf.DisableQuote = true\n\tcheckQuoting(true, \"\")\n\tcheckQuoting(true, \"abcd\")\n\tcheckQuoting(true, \"foo\\n\\rbar\")\n\tcheckQuoting(true, errors.New(\"invalid argument\"))\n\n\t// Test disabling quotes\n\ttf.ForceQuote = false\n\ttf.QuoteEmptyFields = false\n\tcheckQuoting(false, \"\")\n\tcheckQuoting(false, \"abcd\")\n\tcheckQuoting(false, \"foo\\n\\rbar\")\n\tcheckQuoting(false, errors.New(\"invalid argument\"))\n\n\t// New/explicit: DisableQuote should keep primitives unquoted.\n\tcheckQuoting(false, 0)\n\tcheckQuoting(false, true)\n\tcheckQuoting(false, []byte(\"x y\"))\n}\n\nfunc TestEscaping(t *testing.T) {\n\ttf := &TextFormatter{DisableColors: true}\n\n\ttestCases := []struct {\n\t\tvalue    string\n\t\texpected string\n\t}{\n\t\t{`ba\"r`, `ba\\\"r`},\n\t\t{`ba'r`, `ba'r`},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tb, _ := tf.Format(WithField(\"test\", tc.value))\n\t\tif !bytes.Contains(b, []byte(tc.expected)) {\n\t\t\tt.Errorf(\"escaping expected for %q (result was %q instead of %q)\", tc.value, string(b), tc.expected)\n\t\t}\n\t}\n}\n\nfunc TestEscaping_Interface(t *testing.T) {\n\ttf := &TextFormatter{DisableColors: true}\n\n\tts := time.Now()\n\n\ttestCases := []struct {\n\t\tvalue    any\n\t\texpected string\n\t}{\n\t\t{ts, fmt.Sprintf(\"\\\"%s\\\"\", ts.String())},\n\t\t{errors.New(\"error: something went wrong\"), \"\\\"error: something went wrong\\\"\"},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tb, _ := tf.Format(WithField(\"test\", tc.value))\n\t\tif !bytes.Contains(b, []byte(tc.expected)) {\n\t\t\tt.Errorf(\"escaping expected for %q (result was %q instead of %q)\", tc.value, string(b), tc.expected)\n\t\t}\n\t}\n}\n\nfunc TestTimestampFormat(t *testing.T) {\n\tcheckTimeStr := func(format string) {\n\t\tcustomFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}\n\t\tcustomStr, _ := customFormatter.Format(WithField(\"test\", \"test\"))\n\t\ttimeStart := bytes.Index(customStr, ([]byte)(\"time=\"))\n\t\ttimeEnd := bytes.Index(customStr, ([]byte)(\"level=\"))\n\t\ttimeStr := customStr[timeStart+5+len(\"\\\"\") : timeEnd-1-len(\"\\\"\")]\n\t\tif format == \"\" {\n\t\t\tformat = time.RFC3339\n\t\t}\n\t\t_, e := time.Parse(format, (string)(timeStr))\n\t\tif e != nil {\n\t\t\tt.Errorf(\"time string \\\"%s\\\" did not match provided time format \\\"%s\\\": %s\", timeStr, format, e)\n\t\t}\n\t}\n\n\tcheckTimeStr(\"2006-01-02T15:04:05.000000000Z07:00\")\n\tcheckTimeStr(\"Mon Jan _2 15:04:05 2006\")\n\tcheckTimeStr(\"\")\n}\n\nfunc TestDisableLevelTruncation(t *testing.T) {\n\tentry := &Entry{\n\t\tTime:    time.Now(),\n\t\tMessage: \"testing\",\n\t}\n\tcheckDisableTruncation := func(disabled bool, level Level) {\n\t\ttf := &TextFormatter{\n\t\t\tDisableLevelTruncation: disabled,\n\t\t\tForceColors:            true,\n\t\t\tDisableTimestamp:       true,\n\t\t}\n\t\tentry.Level = level\n\t\tout, err := tf.Format(entry)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"error formatting log entry: %s\", err)\n\t\t}\n\t\tlogLine := string(out)\n\t\tif disabled {\n\t\t\texpected := strings.ToUpper(level.String())\n\t\t\tif !strings.Contains(logLine, expected) {\n\t\t\t\tt.Errorf(\"level string expected to be %s when truncation disabled\", expected)\n\t\t\t}\n\t\t} else {\n\t\t\texpected := strings.ToUpper(level.String())\n\t\t\tif len(level.String()) > 4 {\n\t\t\t\tif strings.Contains(logLine, expected) {\n\t\t\t\t\tt.Errorf(\"level string %s expected to be truncated to %s when truncation is enabled\", expected, expected[0:4])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !strings.Contains(logLine, expected) {\n\t\t\t\t\tt.Errorf(\"level string expected to be %s when truncation is enabled and level string is below truncation threshold\", expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcheckDisableTruncation(true, DebugLevel)\n\tcheckDisableTruncation(true, InfoLevel)\n\tcheckDisableTruncation(false, ErrorLevel)\n\tcheckDisableTruncation(false, InfoLevel)\n}\n\nfunc TestPadLevelText(t *testing.T) {\n\t// A note for future maintainers / committers:\n\t//\n\t// This test denormalizes the level text as a part of its assertions.\n\t// Because of that, its not really a \"unit test\" of the PadLevelText functionality.\n\t// So! Many apologies to the potential future person who has to rewrite this test\n\t// when they are changing some completely unrelated functionality.\n\tparams := []struct {\n\t\tname            string\n\t\tlevel           Level\n\t\tpaddedLevelText string\n\t}{\n\t\t{\n\t\t\tname:            \"PanicLevel\",\n\t\t\tlevel:           PanicLevel,\n\t\t\tpaddedLevelText: \"PANIC  \", // 2 extra spaces\n\t\t},\n\t\t{\n\t\t\tname:            \"FatalLevel\",\n\t\t\tlevel:           FatalLevel,\n\t\t\tpaddedLevelText: \"FATAL  \", // 2 extra spaces\n\t\t},\n\t\t{\n\t\t\tname:            \"ErrorLevel\",\n\t\t\tlevel:           ErrorLevel,\n\t\t\tpaddedLevelText: \"ERROR  \", // 2 extra spaces\n\t\t},\n\t\t{\n\t\t\tname:  \"WarnLevel\",\n\t\t\tlevel: WarnLevel,\n\t\t\t// WARNING is already the max length, so we don't need to assert a paddedLevelText\n\t\t},\n\t\t{\n\t\t\tname:            \"DebugLevel\",\n\t\t\tlevel:           DebugLevel,\n\t\t\tpaddedLevelText: \"DEBUG  \", // 2 extra spaces\n\t\t},\n\t\t{\n\t\t\tname:            \"TraceLevel\",\n\t\t\tlevel:           TraceLevel,\n\t\t\tpaddedLevelText: \"TRACE  \", // 2 extra spaces\n\t\t},\n\t\t{\n\t\t\tname:            \"InfoLevel\",\n\t\t\tlevel:           InfoLevel,\n\t\t\tpaddedLevelText: \"INFO   \", // 3 extra spaces\n\t\t},\n\t}\n\n\t// We create a \"default\" TextFormatter to do a control test.\n\t// We also create a TextFormatter with PadLevelText, which is the parameter we want to do our most relevant assertions against.\n\ttfDefault := TextFormatter{ForceColors: true}\n\ttfWithPadding := TextFormatter{ForceColors: true, PadLevelText: true}\n\n\tfor _, val := range params {\n\t\tt.Run(val.name, func(t *testing.T) {\n\t\t\tout, err := tfDefault.Format(&Entry{Level: val.level})\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"error formatting log entry: %s\", err)\n\t\t\t}\n\t\t\tlogLineDefault := string(out)\n\n\t\t\tout, err = tfWithPadding.Format(&Entry{Level: val.level})\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"error formatting log entry: %s\", err)\n\t\t\t}\n\t\t\tlogLineWithPadding := string(out)\n\n\t\t\t// Control: the level text should not be padded by default\n\t\t\tif val.paddedLevelText != \"\" && strings.Contains(logLineDefault, val.paddedLevelText) {\n\t\t\t\tt.Errorf(\"log line %q should not contain the padded level text %q by default\", logLineDefault, val.paddedLevelText)\n\t\t\t}\n\n\t\t\t// Assertion: the level text should still contain the string representation of the level\n\t\t\tif !strings.Contains(strings.ToLower(logLineWithPadding), val.level.String()) {\n\t\t\t\tt.Errorf(\"log line %q should contain the level text %q when padding is enabled\", logLineWithPadding, val.level.String())\n\t\t\t}\n\n\t\t\t// Assertion: the level text should be in its padded form now\n\t\t\tif val.paddedLevelText != \"\" && !strings.Contains(logLineWithPadding, val.paddedLevelText) {\n\t\t\t\tt.Errorf(\"log line %q should contain the padded level text %q when padding is enabled\", logLineWithPadding, val.paddedLevelText)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDisableTimestampWithColoredOutput(t *testing.T) {\n\ttf := &TextFormatter{DisableTimestamp: true, ForceColors: true}\n\n\tb, _ := tf.Format(WithField(\"test\", \"test\"))\n\tif strings.Contains(string(b), \"[0000]\") {\n\t\tt.Error(\"timestamp not expected when DisableTimestamp is true\")\n\t}\n}\n\nfunc TestNewlineBehavior(t *testing.T) {\n\ttf := &TextFormatter{ForceColors: true}\n\n\t// Ensure a single new line is removed as per stdlib log\n\te := NewEntry(StandardLogger())\n\te.Message = \"test message\\n\"\n\tb, _ := tf.Format(e)\n\tif bytes.Contains(b, []byte(\"test message\\n\")) {\n\t\tt.Error(\"first newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected newline to be removed.\")\n\t}\n\n\t// Ensure a double new line is reduced to a single new line\n\te = NewEntry(StandardLogger())\n\te.Message = \"test message\\n\\n\"\n\tb, _ = tf.Format(e)\n\tif bytes.Contains(b, []byte(\"test message\\n\\n\")) {\n\t\tt.Error(\"Double newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected single newline\")\n\t}\n\tif !bytes.Contains(b, []byte(\"test message\\n\")) {\n\t\tt.Error(\"Double newline at end of Entry.Message did not result in a single newline after formatting\")\n\t}\n}\n\nfunc TestTextFormatterFieldMap(t *testing.T) {\n\tformatter := &TextFormatter{\n\t\tDisableColors: true,\n\t\tFieldMap: FieldMap{\n\t\t\tFieldKeyMsg:   \"message\",\n\t\t\tFieldKeyLevel: \"somelevel\",\n\t\t\tFieldKeyTime:  \"timeywimey\",\n\t\t},\n\t}\n\n\tentry := &Entry{\n\t\tMessage: \"oh hi\",\n\t\tLevel:   WarnLevel,\n\t\tTime:    time.Date(1981, time.February, 24, 4, 28, 3, 100, time.UTC),\n\t\tData: Fields{\n\t\t\t\"field1\":     \"f1\",\n\t\t\t\"message\":    \"messagefield\",\n\t\t\t\"somelevel\":  \"levelfield\",\n\t\t\t\"timeywimey\": \"timeywimeyfield\",\n\t\t},\n\t}\n\n\tb, err := formatter.Format(entry)\n\tif err != nil {\n\t\tt.Fatal(\"Unable to format entry: \", err)\n\t}\n\n\tassert.Equal(t,\n\t\t`timeywimey=\"1981-02-24T04:28:03Z\" `+\n\t\t\t`somelevel=warning `+\n\t\t\t`message=\"oh hi\" `+\n\t\t\t`field1=f1 `+\n\t\t\t`fields.message=messagefield `+\n\t\t\t`fields.somelevel=levelfield `+\n\t\t\t`fields.timeywimey=timeywimeyfield`+\"\\n\",\n\t\tstring(b),\n\t\t\"Formatted output doesn't respect FieldMap\")\n}\n\nfunc TestTextFormatterIsColored(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\texpected     bool\n\t\tisTerminal   bool\n\t\tdisableColor bool\n\t\tforceColors  bool\n\t\tenvVars      []string\n\t}{\n\t\t{\n\t\t\t// Default values\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\t// Output on terminal\n\t\t\tname:       \"tty\",\n\t\t\texpected:   true,\n\t\t\tisTerminal: true,\n\t\t},\n\t\t{\n\t\t\t// Output on terminal with color disabled\n\t\t\tname:         \"tty,DisableColors=1\",\n\t\t\texpected:     false,\n\t\t\tisTerminal:   true,\n\t\t\tdisableColor: true,\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with color disabled\n\t\t\tname:         \"DisableColors=1\",\n\t\t\texpected:     false,\n\t\t\tdisableColor: true,\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with color forced\n\t\t\tname:        \"ForceColors=1\",\n\t\t\texpected:    true,\n\t\t\tforceColors: true,\n\t\t},\n\t\t{\n\t\t\t// Output on terminal with clicolor set to \"0\"\n\t\t\tname:       \"tty,CLICOLOR=0\",\n\t\t\texpected:   false,\n\t\t\tisTerminal: true,\n\t\t\tenvVars:    []string{\"CLICOLOR=0\"},\n\t\t},\n\t\t{\n\t\t\t// Output on terminal with clicolor set to \"1\"\n\t\t\tname:       \"tty,CLICOLOR=1\",\n\t\t\texpected:   true,\n\t\t\tisTerminal: true,\n\t\t\tenvVars:    []string{\"CLICOLOR=1\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor set to \"0\"\n\t\t\tname:     \"CLICOLOR=0\",\n\t\t\texpected: false,\n\t\t\tenvVars:  []string{\"CLICOLOR=0\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor set to \"1\"\n\t\t\tname:     \"CLICOLOR=1\",\n\t\t\texpected: false,\n\t\t\tenvVars:  []string{\"CLICOLOR=1\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor set to \"1\" and force color\n\t\t\tname:        \"ForceColors=1,CLICOLOR=1\",\n\t\t\texpected:    true,\n\t\t\tforceColors: true,\n\t\t\tenvVars:     []string{\"CLICOLOR=1\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor set to \"0\" and force color\n\t\t\tname:        \"ForceColors=1,CLICOLOR=0\",\n\t\t\texpected:    false,\n\t\t\tforceColors: true,\n\t\t\tenvVars:     []string{\"CLICOLOR=0\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor_force set to \"1\"\n\t\t\tname:     \"CLICOLOR_FORCE=1\",\n\t\t\texpected: true,\n\t\t\tenvVars:  []string{\"CLICOLOR_FORCE=1\"},\n\t\t},\n\t\t{\n\t\t\t// Output not on terminal with clicolor_force set to \"0\"\n\t\t\tname:     \"CLICOLOR_FORCE=0\",\n\t\t\texpected: false,\n\t\t\tenvVars:  []string{\"CLICOLOR_FORCE=0\"},\n\t\t},\n\t\t{\n\t\t\t// Output on terminal with clicolor_force set to \"0\"\n\t\t\tname:       \"tty,CLICOLOR_FORCE=0\",\n\t\t\texpected:   false,\n\t\t\tisTerminal: true,\n\t\t\tenvVars:    []string{\"CLICOLOR_FORCE=0\"},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Unset existing vars to prevent them from interfering with the test.\n\t\t\tunsetEnv(t, \"CLICOLOR\")\n\t\t\tunsetEnv(t, \"CLICOLOR_FORCE\")\n\t\t\tfor _, envVar := range tc.envVars {\n\t\t\t\tk, v, _ := strings.Cut(envVar, \"=\")\n\t\t\t\tt.Setenv(k, v)\n\t\t\t}\n\t\t\ttf := TextFormatter{\n\t\t\t\tDisableColors:             tc.disableColor,\n\t\t\t\tForceColors:               tc.forceColors,\n\t\t\t\tEnvironmentOverrideColors: len(tc.envVars) > 0,\n\t\t\t}\n\n\t\t\texpected := tc.expected\n\t\t\tif runtime.GOOS == \"windows\" && !tc.forceColors && os.Getenv(\"CLICOLOR_FORCE\") == \"\" {\n\t\t\t\t// On Windows, without ForceColors or CLICOLOR_FORCE, colors are disabled.\n\t\t\t\texpected = false\n\t\t\t}\n\n\t\t\t// TODO(thaJeztah): need a way to mock \"isTerminal\" and check \"isColored\" for testing\n\t\t\t//  without depending on non-exported methods and fields.\n\t\t\tres := tf.isColored(tc.isTerminal) // tc.isTerminal avoids depending on a real TTY\n\t\t\tassert.Equal(t, expected, res)\n\t\t})\n\t}\n}\n\n// unsetEnv calls [os.Unsetenv] to unset an environment\n// variable if it is set, and uses t.Cleanup to restore\n// the environment variable to its original value after\n// the test.\n//\n// Because unsetEnv affects the whole process, it should\n// not be used in parallel tests or tests with parallel\n// ancestors.\nfunc unsetEnv(t *testing.T, env string) {\n\tt.Helper()\n\tprevValue, ok := os.LookupEnv(env)\n\tif ok {\n\t\t_ = os.Unsetenv(env)\n\t\tt.Cleanup(func() {\n\t\t\t_ = os.Setenv(env, prevValue)\n\t\t})\n\t}\n}\n\nfunc TestCustomSorting(t *testing.T) {\n\tformatter := &TextFormatter{\n\t\tDisableColors: true,\n\t\tSortingFunc: func(keys []string) {\n\t\t\tsort.Slice(keys, func(i, j int) bool {\n\t\t\t\tif keys[j] == \"prefix\" {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif keys[i] == \"prefix\" {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn strings.Compare(keys[i], keys[j]) == -1\n\t\t\t})\n\t\t},\n\t}\n\n\tentry := &Entry{\n\t\tMessage: \"Testing custom sort function\",\n\t\tTime:    time.Now(),\n\t\tLevel:   InfoLevel,\n\t\tData: Fields{\n\t\t\t\"test\":      \"testvalue\",\n\t\t\t\"prefix\":    \"the application prefix\",\n\t\t\t\"blablabla\": \"blablabla\",\n\t\t},\n\t}\n\tb, err := formatter.Format(entry)\n\trequire.NoError(t, err)\n\trequire.True(t, strings.HasPrefix(string(b), \"prefix=\"), \"format output is %q\", string(b))\n}\n\n// TestCustomSorting_FirstFormat tests that color and terminal settings\n// are performed on the first message, and the message is properly\n// formatted with default (fixedKeys) fields excluded.\n//\n// regression test for https://github.com/sirupsen/logrus/issues/1298\nfunc TestCustomSorting_FirstFormat(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"colored output not supported on Windows\")\n\t}\n\tif !checkIfTerminal(os.Stderr) {\n\t\tt.Skip(\"test requires a TTY\")\n\t}\n\n\tt.Setenv(\"CLICOLOR\", \"\")\n\tt.Setenv(\"CLICOLOR_FORCE\", \"\")\n\n\tlogger := New()\n\tlogger.SetOutput(os.Stderr) // don't discard output; we need terminal detection\n\tentry := &Entry{\n\t\tLogger:  logger,\n\t\tMessage: `colored messages are pretty`,\n\t\tLevel:   InfoLevel,\n\t\tData:    Fields{\"z\": 2, \"a\": 1},\n\t}\n\n\tvar sortCalled bool\n\tvar otherFields []string\n\ttf := &TextFormatter{\n\t\tDisableTimestamp: true,\n\t\tSortingFunc: func(keys []string) {\n\t\t\tsortCalled = true\n\t\t\tslices.Sort(keys)\n\t\t\tfor _, key := range keys {\n\t\t\t\tif _, ok := entry.Data[key]; !ok {\n\t\t\t\t\t// default (\"fixedKeys\") should not be included when printing colored.\n\t\t\t\t\totherFields = append(otherFields, key)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\tfor _, name := range []string{\"first\", \"second\"} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tsortCalled = false\n\t\t\totherFields = []string{}\n\t\t\tout, err := tf.Format(entry)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.True(t, sortCalled)\n\t\t\tassert.Empty(t, otherFields)\n\n\t\t\t// sanity checks:\n\t\t\tassert.Contains(t, string(out), \"\\x1b[\") // ANSI present\n\t\t\tassert.Contains(t, string(out), \"colored messages are pretty\")\n\t\t})\n\t}\n}\n\nfunc TestTextEntryFieldValueError(t *testing.T) {\n\tt.Run(\"good value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true})\n\n\t\tl.WithField(\"ok\", \"ok\").Info(\"test\")\n\n\t\tout := buf.String()\n\t\tif field := FieldKeyLogrusError + \"=\"; strings.Contains(out, field) {\n\t\t\tt.Errorf(`Unexpected \"logrus_error\" field in log entry: %v`, out)\n\t\t}\n\t\tif field := `ok=ok`; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok=ok\": %v`, out)\n\t\t}\n\t})\n\n\t// If we dropped an unsupported field, the FieldKeyLogrusError should\n\t// contain a message that we did.\n\tt.Run(\"bad and good value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true})\n\n\t\tl.WithField(\"func\", func() {}).WithField(\"ok\", \"ok\").Info(\"test\")\n\n\t\tout := buf.String()\n\t\tif field := FieldKeyLogrusError + \"=\"; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain a \"logrus_error\" field: %v`, out)\n\t\t}\n\t\tif field := `func=`; strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected \"func\" field to be removed from log entry: %v`, out)\n\t\t}\n\t\tif field := `ok=ok`; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok=ok\": %v`, out)\n\t\t}\n\n\t})\n\n\t// This is testing the current behavior; error is preserved, even if an\n\t// unsupported value was dropped and replaced with a supported value for\n\t// the same field.\n\tt.Run(\"replace bad value\", func(t *testing.T) {\n\t\tvar buf bytes.Buffer\n\t\tl := New()\n\t\tl.SetOutput(&buf)\n\t\tl.SetFormatter(&TextFormatter{DisableTimestamp: true, DisableColors: true})\n\n\t\tl.WithField(\"func\", func() {}).WithField(\"ok\", \"ok\").WithField(\"func\", \"not-a-func\").Info(\"test\")\n\n\t\tout := buf.String()\n\t\tif field := FieldKeyLogrusError + \"=\"; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain a \"logrus_error\" field: %v`, out)\n\t\t}\n\t\tif field := `func=not-a-func`; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain \"func=not-a-func\": %v`, out)\n\t\t}\n\t\tif field := `ok=ok`; !strings.Contains(out, field) {\n\t\t\tt.Errorf(`Expected log entry to contain \"ok=ok\": %v`, out)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "writer.go",
    "content": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n// Writer at INFO level. See WriterLevel for details.\nfunc (logger *Logger) Writer() *io.PipeWriter {\n\treturn logger.WriterLevel(InfoLevel)\n}\n\n// WriterLevel returns an io.Writer that can be used to write arbitrary text to\n// the logger at the given log level. Each line written to the writer will be\n// printed in the usual way using formatters and hooks. The writer is part of an\n// io.Pipe and it is the callers responsibility to close the writer when done.\n// This can be used to override the standard library logger easily.\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter {\n\treturn NewEntry(logger).WriterLevel(level)\n}\n\n// Writer returns an io.Writer that writes to the logger at the info log level\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\n// WriterLevel returns an io.Writer that writes to the logger at the given log level\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter {\n\treader, writer := io.Pipe()\n\n\tprintFunc := entry.Print\n\n\t// Determine which log function to use based on the specified log level\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\t}\n\n\t// Start a new goroutine to scan the input and write it to the logger using the specified print function.\n\t// It splits the input into chunks of up to 64KB to avoid buffer overflows.\n\tgo entry.writerScanner(reader, printFunc)\n\n\t// Set a finalizer function to close the writer when it is garbage collected\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}\n\n// writerScanner scans the input from the reader and writes it to the logger\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...any)) {\n\tscanner := bufio.NewScanner(reader)\n\n\t// Set the buffer size to the maximum token size to avoid buffer overflows\n\tscanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize)\n\n\t// Define a split function to split the input into chunks of up to 64KB\n\tchunkSize := bufio.MaxScanTokenSize // 64KB\n\tsplitFunc := func(data []byte, atEOF bool) (int, []byte, error) {\n\t\tif len(data) >= chunkSize {\n\t\t\treturn chunkSize, data[:chunkSize], nil\n\t\t}\n\n\t\treturn bufio.ScanLines(data, atEOF)\n\t}\n\n\t// Use the custom split function to split the input\n\tscanner.Split(splitFunc)\n\n\t// Scan the input and write it to the logger using the specified print function\n\tfor scanner.Scan() {\n\t\tprintFunc(strings.TrimRight(scanner.Text(), \"\\r\\n\"))\n\t}\n\n\t// If there was an error while scanning the input, log an error\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\n\t// Close the reader when we are done\n\treader.Close()\n}\n\n// WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected\nfunc writerFinalizer(writer *io.PipeWriter) {\n\twriter.Close()\n}\n"
  },
  {
    "path": "writer_test.go",
    "content": "package logrus_test\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc ExampleLogger_Writer_httpServer() {\n\tlogger := logrus.New()\n\tw := logger.Writer()\n\tdefer w.Close()\n\n\tsrv := http.Server{\n\t\t// create a stdlib log.Logger that writes to\n\t\t// logrus.Logger.\n\t\tErrorLog: log.New(w, \"\", 0),\n\t}\n\n\tif err := srv.ListenAndServe(); err != nil {\n\t\tlogger.Fatal(err)\n\t}\n}\n\nfunc ExampleLogger_Writer_stdlib() {\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.JSONFormatter{}\n\n\t// Use logrus for standard log output\n\t// Note that `log` here references stdlib's log\n\t// Not logrus imported under the name `log`.\n\tlog.SetOutput(logger.Writer())\n}\n\ntype bufferWithMu struct {\n\tbuf *bytes.Buffer\n\tmu  sync.RWMutex\n}\n\nfunc (b *bufferWithMu) Write(p []byte) (int, error) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\treturn b.buf.Write(p)\n}\n\nfunc (b *bufferWithMu) Read(p []byte) (int, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.buf.Read(p)\n}\n\nfunc (b *bufferWithMu) String() string {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.buf.String()\n}\n\nfunc TestWriterSplitNewlines(t *testing.T) {\n\tbuf := &bufferWithMu{\n\t\tbuf: bytes.NewBuffer(nil),\n\t}\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.TextFormatter{\n\t\tDisableColors:    true,\n\t\tDisableTimestamp: true,\n\t}\n\tlogger.SetOutput(buf)\n\twriter := logger.Writer()\n\n\tconst logNum = 10\n\n\tfor range logNum {\n\t\t_, err := writer.Write([]byte(\"bar\\nfoo\\n\"))\n\t\trequire.NoError(t, err, \"writer.Write failed\")\n\t}\n\twriter.Close()\n\t// Test is flaky because it writes in another goroutine,\n\t// we need to make sure to wait a bit so all write are done.\n\ttime.Sleep(500 * time.Millisecond)\n\n\tlines := strings.Split(strings.TrimRight(buf.String(), \"\\n\"), \"\\n\")\n\tassert.Len(t, lines, logNum*2, \"logger printed incorrect number of lines\")\n}\n\nfunc TestWriterSplitsMax64KB(t *testing.T) {\n\tbuf := &bufferWithMu{\n\t\tbuf: bytes.NewBuffer(nil),\n\t}\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.TextFormatter{\n\t\tDisableColors:    true,\n\t\tDisableTimestamp: true,\n\t}\n\tlogger.SetOutput(buf)\n\twriter := logger.Writer()\n\n\t// write more than 64KB\n\tconst bigWriteLen = bufio.MaxScanTokenSize + 100\n\toutput := make([]byte, bigWriteLen)\n\t// lets not write zero bytes\n\tfor i := range bigWriteLen {\n\t\toutput[i] = 'A'\n\t}\n\n\tfor range 3 {\n\t\tlen, err := writer.Write(output)\n\t\trequire.NoError(t, err, \"writer.Write failed\")\n\t\tassert.Equal(t, bigWriteLen, len, \"bytes written\")\n\t}\n\twriter.Close()\n\t// Test is flaky because it writes in another goroutine,\n\t// we need to make sure to wait a bit so all write are done.\n\ttime.Sleep(500 * time.Millisecond)\n\n\tlines := strings.Split(strings.TrimRight(buf.String(), \"\\n\"), \"\\n\")\n\t// we should have 4 lines because we wrote more than 64 KB each time\n\tassert.Len(t, lines, 4, \"logger printed incorrect number of lines\")\n}\n"
  }
]