diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b74d96294..2406224e0 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -87,29 +87,15 @@ jobs: dirs: _integrations/nrmongo # v3 agent - - go-version: 1.7.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.8.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.9.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.10.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.11.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.12.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.15.x - dirs: v3/newrelic,v3/internal,v3/examples - - go-version: 1.16.x - dirs: v3/newrelic,v3/internal,v3/examples - go-version: 1.17.x dirs: v3/newrelic,v3/internal,v3/examples - go-version: 1.18.x dirs: v3/newrelic,v3/internal,v3/examples + - go-version: 1.19.x + dirs: v3/newrelic,v3/internal,v3/examples # v3 integrations - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/logcontext/nrlogrusplugin extratesting: go get -u github.com/sirupsen/logrus@master - go-version: 1.17.x @@ -118,13 +104,20 @@ jobs: - go-version: 1.17.x dirs: v3/integrations/logcontext-v2/nrzerolog extratesting: go get -u github.com/rs/zerolog@master - - go-version: 1.15.x + - go-version: 1.17.x + dirs: v3/internal/logcontext/nrWriter + - go-version: 1.17.x + dirs: v3/integrations/logcontext-v2/zerologWriter + extratesting: go get -u github.com/rs/zerolog@master + - go-version: 1.17.x + dirs: v3/integrations/logcontext-v2/logWriter + - go-version: 1.17.x dirs: v3/integrations/nrawssdk-v1 extratesting: go get -u github.com/aws/aws-sdk-go@main - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrawssdk-v2 extratesting: go get -u github.com/aws/aws-sdk-go-v2@main - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrecho-v3 # Test against the latest v3 Echo: extratesting: go get -u github.com/labstack/echo@v3 @@ -132,48 +125,48 @@ jobs: - go-version: 1.17.x dirs: v3/integrations/nrecho-v4 extratesting: go get -u github.com/labstack/echo/v4@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrelasticsearch-v7 extratesting: go get -u github.com/elastic/go-elasticsearch/v7@7.x - go-version: 1.18.x dirs: v3/integrations/nrgin extratesting: go get -u github.com/gin-gonic/gin@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrgorilla extratesting: go get -u github.com/gorilla/mux@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrgraphgophers extratesting: go get -u github.com/graph-gophers/graphql-go@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrlogrus extratesting: go get -u github.com/sirupsen/logrus@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrlogxi extratesting: go get -u github.com/mgutz/logxi@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrpkgerrors extratesting: go get -u github.com/pkg/errors@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrlambda extratesting: go get -u github.com/aws/aws-lambda-go@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrmysql extratesting: go get -u github.com/go-sql-driver/mysql@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrpq extratesting: go get -u github.com/lib/pq@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrpq/example/sqlx - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrredis-v7 extratesting: go get -u github.com/go-redis/redis/v7@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrsqlite3 extratesting: go get -u github.com/mattn/go-sqlite3@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrsnowflake extratesting: go get -u github.com/snowflakedb/gosnowflake@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrgrpc extratesting: go get -u google.golang.org/grpc@master - go-version: 1.17.x @@ -185,40 +178,40 @@ jobs: # As of June 2020, confirmed errors still result # extratesting: go get -u github.com/micro/go-micro@latest # If we are using the latest released version to test, we need to use a newer version of go - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrnats extratesting: go get -u github.com/nats-io/nats.go/@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrnats/test extratesting: go get -u github.com/nats-io/nats.go/@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrstan extratesting: go get -u github.com/nats-io/stan.go/@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrstan/test extratesting: go get -u github.com/nats-io/stan.go/@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrstan/examples extratesting: go get -u github.com/nats-io/stan.go/@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/logcontext extratesting: go get -u github.com/sirupsen/logrus@master # nrzap only supports the two most recent minor go releases - go-version: 1.17.x dirs: v3/integrations/nrzap extratesting: go get -u go.uber.org/zap@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrhttprouter extratesting: go get -u github.com/julienschmidt/httprouter@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrb3 - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrmongo extratesting: go get -u go.mongodb.org/mongo-driver@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrgraphqlgo,v3/integrations/nrgraphqlgo/example extratesting: go get -u github.com/graphql-go/graphql@master - - go-version: 1.15.x + - go-version: 1.17.x dirs: v3/integrations/nrmssql extratesting: go get -u github.com/denisenkom/go-mssqldb@master @@ -255,8 +248,9 @@ jobs: fail-fast: false matrix: include: - - go-version: 1.17.1 - - go-version: 1.16.8 + - go-version: 1.17.10 + - go-version: 1.18.6 + - go-version: 1.19.1 steps: - uses: actions/checkout@v1 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index de0f2c025..41f694d70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +## 3.19.0 + +### Added +* `logcontext-v2/logWriter` plugin: a new logs in context plugin that supports the standard library logging package. +* `logcontext-v2/zerologWriter` plugin: a new logs in context plugin for zerolog that will replace the old logcontext-v2/zerolog plugin. This plugin is more robust, and will be able to support a richer set of features than the previous plugin. +* see the updated [logs in context documentation](https://docs.newrelic.com/docs/logs/logs-context/configure-logs-context-go) for information about configuration and installation. + +### Changed +* the logcontext-v2/zerolog plugin will be deprecated once the 3.17.0 release EOLs. + +### Support Statement +New Relic recommends that you upgrade the agent regularly to ensure that you’re getting the latest features and performance benefits. Additionally, older releases will no longer be supported when they reach end-of-life. + +See the [Go Agent EOL Policy](https://docs.newrelic.com/docs/apm/agents/go-agent/get-started/go-agent-eol-policy/) for details about supported versions of the Go Agent and third-party components. + + ## 3.18.2 ### Added diff --git a/README.md b/README.md index 8c990327c..4773a45e4 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ package primitives can be found [here](GUIDE.md#datastore-segments). | [snowflakedb/gosnowflake](https://github.com/snowflakedb/gosnowflake) | [v3/integrations/nrsnowflake](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrsnowflake) | Instrument Snowflake driver | | [mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver) | [v3/integrations/nrmongo](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrmongo) | Instrument MongoDB calls | -#### Logging +#### Agent Logging | Project | Integration Package | | | ------------- | ------------- | - | @@ -109,6 +109,14 @@ package primitives can be found [here](GUIDE.md#datastore-segments). | [mgutz/logxi](https://github.com/mgutz/logxi) | [v3/integrations/nrlogxi](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrlogxi) | Send agent log messages to Logxi | | [uber-go/zap](https://github.com/uber-go/zap) | [v3/integrations/nrzap](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrzap) | Send agent log messages to Zap | +#### Logs in Context + +| Project | Integration Package | | +| ------------- | ------------- | - | +| [sirupsen/logrus](https://github.com/sirupsen/logrus) | [v3/integrations/logcontext-v2/nrlogrus](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/logcontext-v2/nrlogrus) | Send data collected from Logrus log messages to New Relic | +| [log](https://pkg.go.dev/log) | [v3/integrations/logcontext-v2/logWriter](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/logcontext-v2/logWriter) | Send data collected from the standard library logger log messages to New Relic | +| [rs/zerolog](https://github.com/rs/zerolog) | [v3/integrations/logcontext-v2/zerologWriter](https://godoc.org/github.com/newrelic/go-agent/v3/integrations/logcontext-v2/zerologWriter) | Send data collected from zerolog log messages to New Relic | + #### AWS | Project | Integration Package | | diff --git a/v3/integrations/logcontext-v2/logWriter/LICENSE.txt b/v3/integrations/logcontext-v2/logWriter/LICENSE.txt new file mode 100644 index 000000000..cee548c2d --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/LICENSE.txt @@ -0,0 +1,206 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + +Versions 3.8.0 and above for this project are licensed under Apache 2.0. For +prior versions of this project, please see the LICENCE.txt file in the root +directory of that version for more information. diff --git a/v3/integrations/logcontext-v2/logWriter/Readme.md b/v3/integrations/logcontext-v2/logWriter/Readme.md new file mode 100644 index 000000000..e38c5e144 --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/Readme.md @@ -0,0 +1,35 @@ +# New Relic Log Writer + +The logWriter library is an `io.Writer` that automatically integrates the latest New Relic Logs in Context features into the go standard library logger. When used as the `io.Writer` for log, this tool will collect log metrics, forward logs, and enrich logs depending on how your New Relic application is configured. This is the most complete and convenient way to to capture log data with New Relic in log. + +## Usage + +Once your New Relic application has been created, create a logWriter instance. It must be passed an io.Writer, which is where the final log content will be written to, and a pointer to New Relic application. + +```go +writer := logWriter.New(os.Stdout, app) +``` + +If any errors occor while trying to decorate your log with New Relic metadata, it will fail silently and print your log message in its original, unedited form. If you want to see the error messages, then enable debug logging. This will print an error message in a new line after the original log message is printed. + +```go +writer.DebugLogging(true) +``` + +To capture log data in the context of a transaction, make a new logWriter with the `WithTransaction` or `WithContext` methods. + +If you have a pointer to a transaction, use the `WithTransaction()` function. + +```go +txn := app.StartTransaction("my transaction") +defer txn.End() +txnWriter := writer.WithTransaction(txn) +``` + +If you have a context with a transaction pointer in it, use the `WithContext()` function. + +```go +func ExampleHandler(w http.ResponseWriter, r *http.Request) { + txnWriter := writer.WithContext(r.Context()) +} +``` diff --git a/v3/integrations/logcontext-v2/logWriter/example/main.go b/v3/integrations/logcontext-v2/logWriter/example/main.go new file mode 100644 index 000000000..a3cc98ae9 --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/example/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "log" + "os" + "time" + + "github.com/newrelic/go-agent/v3/integrations/logcontext-v2/logWriter" + "github.com/newrelic/go-agent/v3/newrelic" +) + +func main() { + app, err := newrelic.NewApplication( + newrelic.ConfigAppName("log writer example"), + newrelic.ConfigFromEnvironment(), + newrelic.ConfigInfoLogger(os.Stdout), + newrelic.ConfigAppLogForwardingEnabled(true), + ) + if err != nil { + panic(err) + } + + app.WaitForConnection(5 * time.Second) + + // Create a logWriter, then pass it to the log.Logger + writer := logWriter.New(os.Stdout, app) + logger := log.New(&writer, "Background: ", log.Default().Flags()) + + logger.Print("Hello world!") + + txnName := "Example Transaction" + txn := app.StartTransaction(txnName) + + // Always create a new log object in order to avoid changing the context of the logger for + // other threads that may be logging outside of this transaction + txnLogger := log.New(writer.WithTransaction(txn), "Transaction: ", log.Default().Flags()) + txnLogger.Printf("In transaction %s.", txnName) + + // simulate doing something + time.Sleep(time.Microsecond * 100) + + txnLogger.Printf("Ending transaction %s.", txnName) + txn.End() + + logger.Print("Goodbye!") + app.Shutdown(10 * time.Second) +} diff --git a/v3/integrations/logcontext-v2/logWriter/go.mod b/v3/integrations/logcontext-v2/logWriter/go.mod new file mode 100644 index 000000000..1956a0008 --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/go.mod @@ -0,0 +1,5 @@ +module github.com/newrelic/go-agent/v3/integrations/logcontext-v2/logWriter + +go 1.17 + +require github.com/newrelic/go-agent/v3 v3.19.0 diff --git a/v3/integrations/logcontext-v2/logWriter/log-writer.go b/v3/integrations/logcontext-v2/logWriter/log-writer.go new file mode 100644 index 000000000..403762aad --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/log-writer.go @@ -0,0 +1,44 @@ +package logWriter + +import ( + "context" + "io" + + "github.com/newrelic/go-agent/v3/internal/logcontext/nrwriter" + "github.com/newrelic/go-agent/v3/newrelic" +) + +type LogWriter struct { + w nrwriter.LogWriter +} + +func init() { internal.TrackUsage("integration", "logcontext-v2", "logWriter") } + +// New creates a new LogWriter +// output is the io.Writer destination that you want your log to be written to +// app must be a vaild, non nil new relic Application +func New(output io.Writer, app *newrelic.Application) LogWriter { + return LogWriter{ + w: nrwriter.New(output, app), + } +} + +// DebugLogging toggles whether error information should be printed to console. By default, this service +// will fail silently. Enabling debug logging will print error messages on a new line after your log message. +func (lw *LogWriter) DebugLogging(enabled bool) { lw.w.DebugLogging(enabled) } + +// WithTransaction creates a new LogWriter for a specific transactions +func (lw *LogWriter) WithTransaction(txn *newrelic.Transaction) LogWriter { + return LogWriter{w: lw.w.WithTransaction(txn)} +} + +// WithContext creates a new LogWriter for the transaction inside of a context +func (lw *LogWriter) WithContext(ctx context.Context) LogWriter { + return LogWriter{w: lw.w.WithContext(ctx)} +} + +// Write is a valid io.Writer method that will write the content of an enriched log to the output io.Writer +func (lw LogWriter) Write(p []byte) (n int, err error) { + enrichedLog := lw.w.EnrichLog(newrelic.LogData{Message: string(p)}, p) + return lw.w.Write(enrichedLog) +} diff --git a/v3/integrations/logcontext-v2/logWriter/log-writer_test.go b/v3/integrations/logcontext-v2/logWriter/log-writer_test.go new file mode 100644 index 000000000..6fa6a754f --- /dev/null +++ b/v3/integrations/logcontext-v2/logWriter/log-writer_test.go @@ -0,0 +1,70 @@ +package logWriter + +import ( + "bytes" + "log" + "testing" + + "github.com/newrelic/go-agent/v3/internal" + "github.com/newrelic/go-agent/v3/internal/integrationsupport" + "github.com/newrelic/go-agent/v3/internal/logcontext" + "github.com/newrelic/go-agent/v3/internal/sysinfo" + "github.com/newrelic/go-agent/v3/newrelic" +) + +var ( + host, _ = sysinfo.Hostname() +) + +func TestE2E(t *testing.T) { + app := integrationsupport.NewTestApp( + integrationsupport.SampleEverythingReplyFn, + newrelic.ConfigAppLogDecoratingEnabled(true), + newrelic.ConfigAppLogForwardingEnabled(true), + ) + + // Capture output in a buffer for testing + buf := bytes.NewBuffer([]byte{}) + + // set up logger + writer := New(buf, app.Application) + logger := log.New(&writer, "My Prefix: ", log.Lshortfile) + + // configure log writer + writer.DebugLogging(true) + + // create a log message + logger.Print("Hello World!") + + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + }) + + app.ExpectLogEvents(t, []internal.WantLog{ + { + Severity: logcontext.LogSeverityUnknown, + Message: "My Prefix: log-writer_test.go:37: Hello World!", + Timestamp: internal.MatchAnyUnixMilli, + }, + }) +} + +func BenchmarkWrite(b *testing.B) { + app := integrationsupport.NewTestApp( + integrationsupport.SampleEverythingReplyFn, + newrelic.ConfigAppLogDecoratingEnabled(true), + newrelic.ConfigAppLogForwardingEnabled(true), + ) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + + log := []byte(`{"time":1516134303,"level":"debug","message":"hello world"}`) + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + a.Write(log) + } +} diff --git a/v3/integrations/logcontext-v2/nrlogrus/LICENSE.txt b/v3/integrations/logcontext-v2/nrlogrus/LICENSE.txt new file mode 100644 index 000000000..cee548c2d --- /dev/null +++ b/v3/integrations/logcontext-v2/nrlogrus/LICENSE.txt @@ -0,0 +1,206 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + +Versions 3.8.0 and above for this project are licensed under Apache 2.0. For +prior versions of this project, please see the LICENCE.txt file in the root +directory of that version for more information. diff --git a/v3/integrations/logcontext-v2/nrzerolog/LICENSE.txt b/v3/integrations/logcontext-v2/nrzerolog/LICENSE.txt new file mode 100644 index 000000000..cee548c2d --- /dev/null +++ b/v3/integrations/logcontext-v2/nrzerolog/LICENSE.txt @@ -0,0 +1,206 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + +Versions 3.8.0 and above for this project are licensed under Apache 2.0. For +prior versions of this project, please see the LICENCE.txt file in the root +directory of that version for more information. diff --git a/v3/integrations/logcontext-v2/zerologWriter/LICENSE.txt b/v3/integrations/logcontext-v2/zerologWriter/LICENSE.txt new file mode 100644 index 000000000..cee548c2d --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/LICENSE.txt @@ -0,0 +1,206 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + +Versions 3.8.0 and above for this project are licensed under Apache 2.0. For +prior versions of this project, please see the LICENCE.txt file in the root +directory of that version for more information. diff --git a/v3/integrations/logcontext-v2/zerologWriter/Readme.md b/v3/integrations/logcontext-v2/zerologWriter/Readme.md new file mode 100644 index 000000000..7df80c1e3 --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/Readme.md @@ -0,0 +1,35 @@ +# New Relic Zerolog Writer + +The zerolog-writer library is an `io.Writer` that automatically integrates the latest New Relic Logs in Context features into Zerolog. When used as the `io.Writer` for zerolog, this tool will collect log metrics, forward logs, and enrich logs depending on how your New Relic application is configured. This is the most complete and convenient way to to capture log data with New Relic in Zerolog. + +## Usage + +Once your New Relic application has been created, create a ZerologWriter instance. It must be passed an io.Writer, which is where the final log content will be written to, and a pointer to New Relic application. + +```go +writer := zerologWriter.New(os.Stdout, app) +``` + +If any errors occor while trying to decorate your log with New Relic metadata, it will fail silently and print your log message in its original, unedited form. If you want to see the error messages, then enable debug logging. This will print an error message in a new line after the original log message is printed. + +```go +writer.DebugLogging(true) +``` + +To capture log data in the context of a transaction, make a new ZerologWriter with the `WithTransaction` or `WithContext` methods. + +If you have a pointer to a transaction, use the `WithTransaction()` function. + +```go +txn := app.StartTransaction("my transaction") +defer txn.End() +txnWriter := writer.WithTransaction(txn) +``` + +If you have a context with a transaction pointer in it, use the `WithContext()` function. + +```go +func ExampleHandler(w http.ResponseWriter, r *http.Request) { + txnWriter := writer.WithContext(r.Context()) +} +``` diff --git a/v3/integrations/logcontext-v2/zerologWriter/example/main.go b/v3/integrations/logcontext-v2/zerologWriter/example/main.go new file mode 100644 index 000000000..f37c65cbf --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/example/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "os" + "time" + + "github.com/newrelic/go-agent/v3/integrations/logcontext-v2/zerologWriter" + "github.com/newrelic/go-agent/v3/newrelic" + "github.com/rs/zerolog" +) + +func main() { + app, err := newrelic.NewApplication( + newrelic.ConfigAppName("nrwriter log writer example"), + newrelic.ConfigFromEnvironment(), + newrelic.ConfigInfoLogger(os.Stdout), + newrelic.ConfigAppLogDecoratingEnabled(true), + ) + if err != nil { + panic(err) + } + + app.WaitForConnection(5 * time.Second) + + writer := zerologWriter.New(os.Stdout, app) + logger := zerolog.New(writer) + + logger.Print("Application connected to New Relic.") + + txnName := "Example Transaction" + txn := app.StartTransaction(txnName) + + // Always create a new logger in order to avoid changing the context of the logger for + // other threads that may be logging outside of this transaction + txnLogger := logger.Output(writer.WithTransaction(txn)) + txnLogger.Printf("In transaction %s.", txnName) + + // simulate doing something + time.Sleep(time.Microsecond * 100) + + txnLogger.Printf("Ending transaction %s.", txnName) + txn.End() + + app.Shutdown(10 * time.Second) +} diff --git a/v3/integrations/logcontext-v2/zerologWriter/go.mod b/v3/integrations/logcontext-v2/zerologWriter/go.mod new file mode 100644 index 000000000..255d030d6 --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/go.mod @@ -0,0 +1,8 @@ +module github.com/newrelic/go-agent/v3/integrations/logcontext-v2/zerologWriter + +go 1.17 + +require ( + github.com/newrelic/go-agent/v3 v3.19.0 + github.com/rs/zerolog v1.27.0 +) diff --git a/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer.go b/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer.go new file mode 100644 index 000000000..0b625151b --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer.go @@ -0,0 +1,123 @@ +package zerologWriter + +import ( + "context" + "io" + "strings" + + "github.com/newrelic/go-agent/v3/internal/logcontext/nrwriter" + "github.com/newrelic/go-agent/v3/newrelic" + "github.com/rs/zerolog" +) + +type ZerologWriter struct { + w nrwriter.LogWriter +} + +func init() { internal.TrackUsage("integration", "logcontext-v2", "zerologWriter") } + +// New creates a new NewRelicWriter Object +// output is the io.Writer destination that you want your log to be written to +// app must be a vaild, non nil new relic Application +func New(output io.Writer, app *newrelic.Application) ZerologWriter { + return ZerologWriter{ + w: nrwriter.New(output, app), + } +} + +// DebugLogging toggles whether error information should be printed to console. By default, this service +// will fail silently. Enabling debug logging will print error messages on a new line after your log message. +func (zw *ZerologWriter) DebugLogging(enabled bool) { zw.w.DebugLogging(enabled) } + +// WithTransaction creates a new ZerologWriter for a specific transactions +func (zw *ZerologWriter) WithTransaction(txn *newrelic.Transaction) ZerologWriter { + return ZerologWriter{w: zw.w.WithTransaction(txn)} +} + +// WithContext creates a new ZerologWriter for the transaction inside of a context +func (zw *ZerologWriter) WithContext(ctx context.Context) ZerologWriter { + return ZerologWriter{w: zw.w.WithContext(ctx)} +} + +// Write is a valid io.Writer method that will write the content of an enriched log to the output io.Writer +func (zw ZerologWriter) Write(p []byte) (n int, err error) { + data := parseJSONLogData(p) + enrichedLog := zw.w.EnrichLog(data, p) + return zw.w.Write(enrichedLog) +} + +func parseJSONLogData(log []byte) newrelic.LogData { + // For this iteration of the tool, the entire log gets captured as the message + data := newrelic.LogData{} + data.Message = string(log) + + for i := 0; i < len(log)-1; { + // get key; always a string field + key, keyEnd := getStringField(log, i) + + // find index where value starts + valStart := getValueIndex(log, keyEnd) + valEnd := valStart + + // NOTE: depending on the key, the type of field the value is can differ + switch key { + case zerolog.LevelFieldName: + data.Severity, valEnd = getStringField(log, valStart) + } + + next := nextKeyIndex(log, valEnd) + if next == -1 { + return data + } + i = next + } + + return data +} + +func getValueIndex(p []byte, indx int) int { + // Find the index where the value begins + for i := indx; i < len(p)-1; i++ { + if p[i] == ':' { + return i + 1 + } + } + + return -1 +} + +func nextKeyIndex(p []byte, indx int) int { + // Find the index where the key begins + for i := indx; i < len(p)-1; i++ { + if p[i] == ',' { + return i + 1 + } + } + + return -1 +} + +func getStringField(p []byte, indx int) (string, int) { + value := strings.Builder{} + i := indx + + // find start of string field + for ; i < len(p)-1; i++ { + if p[i] == '"' { + i += 1 + break + } + } + + // parse value of string field + for ; i < len(p)-1; i++ { + if p[i] == '"' { + return value.String(), i + 1 + } else { + value.WriteByte(p[i]) + } + + } + + return "", -1 +} diff --git a/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer_test.go b/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer_test.go new file mode 100644 index 000000000..9d99a50fe --- /dev/null +++ b/v3/integrations/logcontext-v2/zerologWriter/zerolog-writer_test.go @@ -0,0 +1,116 @@ +package zerologWriter + +import ( + "bytes" + "testing" + + "github.com/newrelic/go-agent/v3/internal" + "github.com/newrelic/go-agent/v3/internal/integrationsupport" + "github.com/newrelic/go-agent/v3/internal/logcontext" + "github.com/newrelic/go-agent/v3/internal/sysinfo" + "github.com/newrelic/go-agent/v3/newrelic" + "github.com/rs/zerolog" +) + +var ( + host, _ = sysinfo.Hostname() +) + +func TestParseLogData(t *testing.T) { + type logTest struct { + log string + levelKey string + expect newrelic.LogData + } + tests := []logTest{ + { + `{"time":1516134303,"level":"debug","message":"hello world"}`, + "level", + newrelic.LogData{ + Message: `{"time":1516134303,"level":"debug","message":"hello world"}`, + Severity: "debug", + }, + }, + { + `{"time":1516134303,"level":"info","message":"hello world"}`, + "level", + newrelic.LogData{ + Message: `{"time":1516134303,"level":"info","message":"hello world"}`, + Severity: "info", + }, + }, + { + `{"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"}`, + "level", + newrelic.LogData{ + Message: `{"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"}`, + Severity: "fatal", + }, + }, + { + `{"time":1516134303,"hi":"info","message":"hello world"}`, + "hi", + newrelic.LogData{ + Message: `{"time":1516134303,"hi":"info","message":"hello world"}`, + Severity: "info", + }, + }, + } + for _, test := range tests { + if test.levelKey != "" { + zerolog.LevelFieldName = test.levelKey + } + val := parseJSONLogData([]byte(test.log)) + + if val.Message != test.expect.Message { + parserTestError(t, "Message", val.Message, test.expect.Message) + } + if val.Severity != test.expect.Severity { + parserTestError(t, "Severity", val.Severity, test.expect.Severity) + } + + zerolog.LevelFieldName = "level" + } +} + +func parserTestError(t *testing.T, field, actual, expect string) { + t.Errorf("The parsed %s does not match the expected message: parsed \"%s\" expected \"%s\"", field, actual, expect) +} + +func TestE2E(t *testing.T) { + app := integrationsupport.NewTestApp( + integrationsupport.SampleEverythingReplyFn, + newrelic.ConfigAppLogDecoratingEnabled(true), + newrelic.ConfigAppLogForwardingEnabled(true), + ) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + logger := zerolog.New(a) + logger.Info().Msg("Hello World!") + + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + }) + + app.ExpectLogEvents(t, []internal.WantLog{ + { + Severity: zerolog.LevelInfoValue, + Message: `{"level":"info","message":"Hello World!"}`, + Timestamp: internal.MatchAnyUnixMilli, + }, + }) +} + +func BenchmarkParseLogLevel(b *testing.B) { + log := []byte(`{"time":1516134303,"level":"debug","message":"hello world"}`) + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + parseJSONLogData(log) + } +} diff --git a/v3/internal/logcontext/decoratorTesting.go b/v3/internal/logcontext/decoratorTesting.go index 698687171..4d30770a5 100644 --- a/v3/internal/logcontext/decoratorTesting.go +++ b/v3/internal/logcontext/decoratorTesting.go @@ -9,11 +9,16 @@ import ( // DecorationExpect defines the expected values a log decorated by a logcontext v2 decorator should have type DecorationExpect struct { DecorationDisabled bool - EntityGUID string - EntityName string - Hostname string - TraceID string - SpanID string + + EntityGUID string + EntityName string + Hostname string + TraceID string + SpanID string + + // decorator errors will result in an undecorated log message being printed + // and an error message also being printed in a separate line + DecoratorError error } // metadata indexes @@ -45,6 +50,19 @@ func ValidateDecoratedOutput(t *testing.T, out *bytes.Buffer, expect *Decoration } } + if expect.DecoratorError != nil { + if strings.Contains(actual, "NR-LINKING") { + t.Fatal("logs should not be decorated when a decorator error occurs") + } + + msg := expect.DecoratorError.Error() + if !strings.Contains(actual, msg) { + t.Fatalf("an error message debug log was expected, \"%s\", but was not found: %s", msg, actual) + } else { + return + } + } + split := strings.Split(actual, "NR-LINKING") if len(split) != 2 { diff --git a/v3/internal/logcontext/nrWriter/nrwriter.go b/v3/internal/logcontext/nrWriter/nrwriter.go new file mode 100644 index 000000000..c0aa5b774 --- /dev/null +++ b/v3/internal/logcontext/nrWriter/nrwriter.go @@ -0,0 +1,84 @@ +package nrwriter + +import ( + "bytes" + "context" + "io" + + "github.com/newrelic/go-agent/v3/newrelic" +) + +// LogWriter is an io.Writer that captures log data for use with New Relic Logs in Context +type LogWriter struct { + debug bool + out io.Writer + app *newrelic.Application + txn *newrelic.Transaction +} + +// New creates a new NewRelicWriter Object +// output is the io.Writer destination that you want your log to be written to +// app must be a vaild, non nil new relic Application +func New(output io.Writer, app *newrelic.Application) LogWriter { + return LogWriter{ + out: output, + app: app, + } +} + +// DebugLogging enables or disables debug error messages being written in the IO output. +// By default, the nrwriter debug logging is set to false and will fail silently +func (b *LogWriter) DebugLogging(enabled bool) { + b.debug = enabled +} + +// WithTransaction duplicates the current NewRelicWriter and sets the transaction to txn +func (b *LogWriter) WithTransaction(txn *newrelic.Transaction) LogWriter { + return LogWriter{ + out: b.out, + app: b.app, + debug: b.debug, + txn: txn, + } +} + +// WithTransaction duplicates the current NewRelicWriter and sets the transaction to the transaction parsed from ctx +func (b *LogWriter) WithContext(ctx context.Context) LogWriter { + txn := newrelic.FromContext(ctx) + return LogWriter{ + out: b.out, + app: b.app, + debug: b.debug, + txn: txn, + } +} + +// EnrichLog attempts to enrich a log with New Relic linking metadata. If it fails, +// it will return the original log line unless debug=true, otherwise it will print +// an error on a following line. +func (b *LogWriter) EnrichLog(data newrelic.LogData, p []byte) []byte { + logLine := bytes.TrimRight(p, "\n") + buf := bytes.NewBuffer(logLine) + + var enrichErr error + if b.txn != nil { + b.txn.RecordLog(data) + enrichErr = newrelic.EnrichLog(buf, newrelic.FromTxn(b.txn)) + } else { + b.app.RecordLog(data) + enrichErr = newrelic.EnrichLog(buf, newrelic.FromApp(b.app)) + } + + if b.debug && enrichErr != nil { + buf.WriteString("\n") + buf.WriteString(enrichErr.Error()) + } + + buf.WriteString("\n") + return buf.Bytes() +} + +// Write implements io.Write +func (b LogWriter) Write(p []byte) (n int, err error) { + return b.out.Write(p) +} diff --git a/v3/internal/logcontext/nrWriter/nrwriter_test.go b/v3/internal/logcontext/nrWriter/nrwriter_test.go new file mode 100644 index 000000000..b997d74fe --- /dev/null +++ b/v3/internal/logcontext/nrWriter/nrwriter_test.go @@ -0,0 +1,175 @@ +package nrwriter + +import ( + "bytes" + "context" + "io" + "strings" + "testing" + + "github.com/newrelic/go-agent/v3/internal/integrationsupport" + "github.com/newrelic/go-agent/v3/internal/logcontext" + "github.com/newrelic/go-agent/v3/internal/sysinfo" + "github.com/newrelic/go-agent/v3/newrelic" +) + +var ( + host, _ = sysinfo.Hostname() +) + +const ( + benchmarkMsg = "This is a test log message" +) + +func BenchmarkEnrichLog(b *testing.B) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + a := New(io.Discard, app.Application) + a.DebugLogging(true) + + buf := bytes.NewBuffer([]byte(benchmarkMsg)) + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + a.EnrichLog(newrelic.LogData{}, buf.Bytes()) + } +} + +const ( + logMessageWithNewline = "This is a log message with a newline\n" + logMessageWithoutNewline = "This is a log message without a newline" + logMessageWithSpace = "This is a log message with a space at the end \n" + logMessageWithoutNewlineAndWithSpace = "This is a log message without a newline " + nrlinking = "NR-LINKING" +) + +func TestLogSpacingAndNewlines(t *testing.T) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + lines := []string{ + logMessageWithNewline, + logMessageWithSpace, + logMessageWithoutNewline, + logMessageWithoutNewlineAndWithSpace, + } + + for _, line := range lines { + buf.Write(a.EnrichLog(newrelic.LogData{}, []byte(line))) + log := buf.String() + // verify there is a single newline at the end of the log line + if strings.Count(log, "\n") != 1 { + t.Errorf("Expected a single log line ending with one newline, instead got: %s", log) + } + + substrings := strings.Split(log, nrlinking) + if len(substrings) != 2 { + t.Errorf("Expected %s metadata but log line was not decorated: %s", nrlinking, log) + } else { + whitespace := countTrailingWhitespace(substrings[0]) + if whitespace != 1 { + t.Errorf("Expecting a single whitespace separating log line from %s, got %d: %s", nrlinking, whitespace, log) + } + } + + buf.Reset() + } +} + +func countTrailingWhitespace(str string) int { + count := 0 + for i := len(str) - 1; i >= 0; i-- { + if str[i] == ' ' { + count++ + } else { + break + } + } + + return count +} + +func TestBackgroundLog(t *testing.T) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + a.Write(a.EnrichLog(newrelic.LogData{}, []byte(logMessageWithNewline))) + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + }) +} + +func TestTransactionLog(t *testing.T) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + txn := app.StartTransaction("test transaction") + b := a.WithTransaction(txn) + + b.Write(b.EnrichLog(newrelic.LogData{}, []byte(logMessageWithNewline))) + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + TraceID: txn.GetLinkingMetadata().TraceID, + SpanID: txn.GetLinkingMetadata().SpanID, + }) + txn.End() +} + +func TestContextLog(t *testing.T) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + txn := app.StartTransaction("test transaction") + ctx := newrelic.NewContext(context.Background(), txn) + b := a.WithContext(ctx) + + b.Write(b.EnrichLog(newrelic.LogData{}, []byte(logMessageWithNewline))) + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + TraceID: txn.GetLinkingMetadata().TraceID, + SpanID: txn.GetLinkingMetadata().SpanID, + }) + txn.End() +} + +func TestNilContextLog(t *testing.T) { + app := integrationsupport.NewTestApp(integrationsupport.SampleEverythingReplyFn, newrelic.ConfigAppLogDecoratingEnabled(true)) + buf := bytes.NewBuffer([]byte{}) + a := New(buf, app.Application) + a.DebugLogging(true) + + b := a.WithContext(nil) + + // verify that when context is nil, log is enriched with application data + b.Write(b.EnrichLog(newrelic.LogData{}, []byte(logMessageWithNewline))) + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + }) + + buf.Reset() + + // verify that when context is empty, log is enriched with application data + c := a.WithContext(context.Background()) + c.Write(c.EnrichLog(newrelic.LogData{}, []byte(logMessageWithNewline))) + logcontext.ValidateDecoratedOutput(t, buf, &logcontext.DecorationExpect{ + EntityGUID: integrationsupport.TestEntityGUID, + Hostname: host, + EntityName: integrationsupport.SampleAppName, + }) +} diff --git a/v3/newrelic/log_event.go b/v3/newrelic/log_event.go index d8eaeff62..7aa051d3e 100644 --- a/v3/newrelic/log_event.go +++ b/v3/newrelic/log_event.go @@ -102,8 +102,13 @@ const ( ) var ( - errNilLogBuffer = fmt.Errorf("%s: the EnrichLog() function must not be passed a nil byte buffer", logDecorationErrorHeader) - errNoApplication = fmt.Errorf("%s: either an application or transaction must be provided to enrich a log", logDecorationErrorHeader) + // ErrNilLogBuffer is a type of error that occurs when the New Relic log decorator is passed a nil object when it was + // expecting a valid, non nil pointer to a log bytes.Buffer object. + ErrNilLogBuffer = fmt.Errorf("%s: the EnrichLog() function must not be passed a nil byte buffer", logDecorationErrorHeader) + + // ErrNoApplication is a type of error that occurs when the New Relic log decorator is passed a nil New Relic Application + // when it was expecting a valid, non nil pointer to a New Relic application. + ErrNoApplication = fmt.Errorf("%s: a non nil application or transaction must be provided to enrich a log", logDecorationErrorHeader) ) type logEnricherConfig struct { @@ -139,7 +144,7 @@ func EnrichLog(buf *bytes.Buffer, opts EnricherOption) error { opts(&config) if buf == nil { - return errNilLogBuffer + return ErrNilLogBuffer } md := linkingMetadata{} @@ -157,11 +162,11 @@ func EnrichLog(buf *bytes.Buffer, opts EnricherOption) error { md.spanID = txnMD.SpanID md.traceID = txnMD.TraceID } else { - return errNoApplication + return ErrNoApplication } if app.app == nil { - return errNoApplication + return ErrNoApplication } reply, err := app.app.getState() @@ -184,7 +189,10 @@ func (md *linkingMetadata) appendLinkingMetadata(buf *bytes.Buffer) { if md.entityGUID == "" || md.entityName == "" || md.hostname == "" { return } - buf.WriteString(" NR-LINKING|") + + addDynamicSpacing(buf) + + buf.WriteString("NR-LINKING|") if md.traceID != "" && md.spanID != "" { buf.WriteString(md.entityGUID) buf.WriteByte('|') @@ -205,3 +213,14 @@ func (md *linkingMetadata) appendLinkingMetadata(buf *bytes.Buffer) { buf.WriteByte('|') } } + +func addDynamicSpacing(buf *bytes.Buffer) { + if buf.Len() == 0 { + return + } + + bytes := buf.Bytes() + if bytes[len(bytes)-1] != ' ' { + buf.WriteByte(' ') + } +} diff --git a/v3/newrelic/version.go b/v3/newrelic/version.go index 86af171ee..c33424a55 100644 --- a/v3/newrelic/version.go +++ b/v3/newrelic/version.go @@ -11,7 +11,7 @@ import ( const ( // Version is the full string version of this Go Agent. - Version = "3.18.2" + Version = "3.19.0" ) var (