pax_global_header00006660000000000000000000000064144767357430014536gustar00rootroot0000000000000052 comment=0fc1e28871fdf2786e2cc51bbe4133db6547a199 log-0.1.0/000077500000000000000000000000001447673574300123155ustar00rootroot00000000000000log-0.1.0/.github/000077500000000000000000000000001447673574300136555ustar00rootroot00000000000000log-0.1.0/.github/workflows/000077500000000000000000000000001447673574300157125ustar00rootroot00000000000000log-0.1.0/.github/workflows/ci.yml000066400000000000000000000043121447673574300170300ustar00rootroot00000000000000name: CI on: push: branches: [ main ] pull_request: branches: [ main ] env: # Go version we currently use to build containerd across all CI. # Note: don't forget to update `Binaries` step, as it contains the matrix of all supported Go versions. GO_VERSION: "1.21.0" permissions: # added using https://github.com/step-security/secure-workflows contents: read jobs: # # golangci-lint # linters: permissions: contents: read # for actions/checkout to fetch code pull-requests: read # for golangci/golangci-lint-action to fetch pull requests name: Linters runs-on: ${{ matrix.os }} timeout-minutes: 10 strategy: matrix: os: [ubuntu-22.04, macos-12] # TODO: Add windows-2019 steps: - uses: actions/setup-go@v4 with: go-version: ${{ env.GO_VERSION }} cache: false # see actions/setup-go#368 - uses: actions/checkout@v3 - uses: golangci/golangci-lint-action@v3 with: version: v1.52.2 skip-cache: true args: --timeout=5m # # Project checks # project: name: Project Checks if: github.repository == 'containerd/log' runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - uses: actions/setup-go@v4 with: go-version: ${{ env.GO_VERSION }} cache: false # see actions/setup-go#368 - uses: actions/checkout@v3 with: path: src/github.com/containerd/log fetch-depth: 25 - uses: containerd/project-checks@v1.1.0 with: working-directory: src/github.com/containerd/log repo-access-token: ${{ secrets.GITHUB_TOKEN }} tests: name: Tests runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - uses: actions/checkout@v2 with: path: src/github.com/containerd/log - uses: actions/setup-go@v2 with: go-version: ${{ env.GO_VERSION }} - name: Set env shell: bash run: | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - run: | go test -v -race working-directory: src/github.com/containerd/log log-0.1.0/.golangci.yml000066400000000000000000000010561447673574300147030ustar00rootroot00000000000000linters: enable: - exportloopref # Checks for pointers to enclosing loop variables - gofmt - goimports - gosec - ineffassign - misspell - nolintlint - revive - staticcheck - tenv # Detects using os.Setenv instead of t.Setenv since Go 1.17 - unconvert - unused - vet - dupword # Checks for duplicate words in the source code disable: - errcheck run: timeout: 5m skip-dirs: - api - cluster - design - docs - docs/man - releases - reports - test # e2e scripts log-0.1.0/LICENSE000066400000000000000000000250151447673574300133250ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright The containerd Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. log-0.1.0/README.md000066400000000000000000000016561447673574300136040ustar00rootroot00000000000000# log A Go package providing a common logging interface across containerd repositories and a way for clients to use and configure logging in containerd packages. This package is not intended to be used as a standalone logging package outside of the containerd ecosystem and is intended as an interface wrapper around a logging implementation. In the future this package may be replaced with a common go logging interface. ## Project details **log** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). As a containerd sub-project, you will find the: * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) information in our [`containerd/project`](https://github.com/containerd/project) repository. log-0.1.0/context.go000066400000000000000000000132111447673574300143260ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package log provides types and functions related to logging, passing // loggers through a context, and attaching context to the logger. // // # Transitional types // // This package contains various types that are aliases for types in [logrus]. // These aliases are intended for transitioning away from hard-coding logrus // as logging implementation. Consumers of this package are encouraged to use // the type-aliases from this package instead of directly using their logrus // equivalent. // // The intent is to replace these aliases with locally defined types and // interfaces once all consumers are no longer directly importing logrus // types. // // IMPORTANT: due to the transitional purpose of this package, it is not // guaranteed for the full logrus API to be provided in the future. As // outlined, these aliases are provided as a step to transition away from // a specific implementation which, as a result, exposes the full logrus API. // While no decisions have been made on the ultimate design and interface // provided by this package, we do not expect carrying "less common" features. package log import ( "context" "fmt" "github.com/sirupsen/logrus" ) // G is a shorthand for [GetLogger]. // // We may want to define this locally to a package to get package tagged log // messages. var G = GetLogger // L is an alias for the standard logger. var L = &Entry{ Logger: logrus.StandardLogger(), // Default is three fields plus a little extra room. Data: make(Fields, 6), } type loggerKey struct{} // Fields type to pass to "WithFields". type Fields = map[string]any // Entry is a logging entry. It contains all the fields passed with // [Entry.WithFields]. It's finally logged when Trace, Debug, Info, Warn, // Error, Fatal or Panic is called on it. These objects can be reused and // passed around as much as you wish to avoid field duplication. // // Entry is a transitional type, and currently an alias for [logrus.Entry]. type Entry = logrus.Entry // RFC3339NanoFixed is [time.RFC3339Nano] with nanoseconds padded using // zeros to ensure the formatted time is always the same number of // characters. const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" // Level is a logging level. type Level = logrus.Level // Supported log levels. const ( // TraceLevel level. Designates finer-grained informational events // than [DebugLevel]. TraceLevel Level = logrus.TraceLevel // DebugLevel level. Usually only enabled when debugging. Very verbose // logging. DebugLevel Level = logrus.DebugLevel // InfoLevel level. General operational entries about what's going on // inside the application. InfoLevel Level = logrus.InfoLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel Level = logrus.WarnLevel // ErrorLevel level. Logs errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel Level = logrus.ErrorLevel // FatalLevel level. Logs and then calls "logger.Exit(1)". It exits // even if the logging level is set to Panic. FatalLevel Level = logrus.FatalLevel // PanicLevel level. This is the highest level of severity. Logs and // then calls panic with the message passed to Debug, Info, ... PanicLevel Level = logrus.PanicLevel ) // SetLevel sets log level globally. It returns an error if the given // level is not supported. // // level can be one of: // // - "trace" ([TraceLevel]) // - "debug" ([DebugLevel]) // - "info" ([InfoLevel]) // - "warn" ([WarnLevel]) // - "error" ([ErrorLevel]) // - "fatal" ([FatalLevel]) // - "panic" ([PanicLevel]) func SetLevel(level string) error { lvl, err := logrus.ParseLevel(level) if err != nil { return err } L.Logger.SetLevel(lvl) return nil } // GetLevel returns the current log level. func GetLevel() Level { return L.Logger.GetLevel() } // OutputFormat specifies a log output format. type OutputFormat string // Supported log output formats. const ( // TextFormat represents the text logging format. TextFormat OutputFormat = "text" // JSONFormat represents the JSON logging format. JSONFormat OutputFormat = "json" ) // SetFormat sets the log output format ([TextFormat] or [JSONFormat]). func SetFormat(format OutputFormat) error { switch format { case TextFormat: L.Logger.SetFormatter(&logrus.TextFormatter{ TimestampFormat: RFC3339NanoFixed, FullTimestamp: true, }) return nil case JSONFormat: L.Logger.SetFormatter(&logrus.JSONFormatter{ TimestampFormat: RFC3339NanoFixed, }) return nil default: return fmt.Errorf("unknown log format: %s", format) } } // WithLogger returns a new context with the provided logger. Use in // combination with logger.WithField(s) for great effect. func WithLogger(ctx context.Context, logger *Entry) context.Context { return context.WithValue(ctx, loggerKey{}, logger.WithContext(ctx)) } // GetLogger retrieves the current logger from the context. If no logger is // available, the default logger is returned. func GetLogger(ctx context.Context) *Entry { if logger := ctx.Value(loggerKey{}); logger != nil { return logger.(*Entry) } return L.WithContext(ctx) } log-0.1.0/context_test.go000066400000000000000000000034401447673574300153700ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package log import ( "context" "reflect" "testing" "github.com/sirupsen/logrus" ) func TestLoggerContext(t *testing.T) { const expected = "one" ctx := context.Background() ctx = WithLogger(ctx, G(ctx).WithField("test", expected)) if actual := GetLogger(ctx).Data["test"]; actual != expected { t.Errorf("expected: %v, got: %v", expected, actual) } a := G(ctx) b := GetLogger(ctx) if !reflect.DeepEqual(a, b) || a != b { t.Errorf("should be the same: %+v, %+v", a, b) } } func TestCompat(t *testing.T) { expected := Fields{ "hello1": "world1", "hello2": "world2", "hello3": "world3", } l := G(context.TODO()) l = l.WithFields(logrus.Fields{"hello1": "world1"}) l = l.WithFields(Fields{"hello2": "world2"}) l = l.WithFields(map[string]any{"hello3": "world3"}) if !reflect.DeepEqual(Fields(l.Data), expected) { t.Errorf("expected: (%[1]T) %+[1]v, got: (%[2]T) %+[2]v", expected, l.Data) } l2 := L l2 = l2.WithFields(logrus.Fields{"hello1": "world1"}) l2 = l2.WithFields(Fields{"hello2": "world2"}) l2 = l2.WithFields(map[string]any{"hello3": "world3"}) if !reflect.DeepEqual(Fields(l2.Data), expected) { t.Errorf("expected: (%[1]T) %+[1]v, got: (%[2]T) %+[2]v", expected, l2.Data) } } log-0.1.0/go.mod000066400000000000000000000002671447673574300134300ustar00rootroot00000000000000module github.com/containerd/log go 1.20 require github.com/sirupsen/logrus v1.9.3 require ( github.com/stretchr/testify v1.8.2 // indirect golang.org/x/sys v0.7.0 // indirect ) log-0.1.0/go.sum000066400000000000000000000036201447673574300134510ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= log-0.1.0/logtest/000077500000000000000000000000001447673574300137765ustar00rootroot00000000000000log-0.1.0/logtest/context.go000066400000000000000000000030261447673574300160120ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package logtest import ( "context" "fmt" "io" "path/filepath" "runtime" "testing" "github.com/containerd/log" "github.com/sirupsen/logrus" ) // WithT adds a logging hook for the given test // Changes debug level to debug, clears output, and // outputs all log messages as test logs. func WithT(ctx context.Context, t testing.TB) context.Context { // Create a new logger to avoid adding hooks from multiple tests l := logrus.New() // Increase debug level for tests l.SetLevel(logrus.DebugLevel) l.SetOutput(io.Discard) l.SetReportCaller(true) // Add testing hook l.AddHook(&testHook{ t: t, fmt: &logrus.TextFormatter{ DisableColors: true, TimestampFormat: log.RFC3339NanoFixed, CallerPrettyfier: func(frame *runtime.Frame) (string, string) { return filepath.Base(frame.Function), fmt.Sprintf("%s:%d", frame.File, frame.Line) }, }, }) return log.WithLogger(ctx, logrus.NewEntry(l).WithField("testcase", t.Name())) } log-0.1.0/logtest/log_hook.go000066400000000000000000000021631447673574300161300ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package logtest import ( "bytes" "sync" "testing" "github.com/sirupsen/logrus" ) type testHook struct { t testing.TB fmt logrus.Formatter mu sync.Mutex } func (*testHook) Levels() []logrus.Level { return logrus.AllLevels } func (h *testHook) Fire(e *logrus.Entry) error { s, err := h.fmt.Format(e) if err != nil { return err } // Because the logger could be called from multiple goroutines, // but t.Log() is not designed for. h.mu.Lock() defer h.mu.Unlock() h.t.Log(string(bytes.TrimRight(s, "\n"))) return nil }