pax_global_header 0000666 0000000 0000000 00000000064 14434524636 0014525 g ustar 00root root 0000000 0000000 52 comment=f7492144fd62fa2253eb88023239c59c7f3c4ca8 golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/ 0000775 0000000 0000000 00000000000 14434524636 0022553 5 ustar 00root root 0000000 0000000 golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/.gitignore 0000664 0000000 0000000 00000000423 14434524636 0024542 0 ustar 00root root 0000000 0000000 # Binaries for programs and plugins *.exe *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/.travis.yml 0000664 0000000 0000000 00000000544 14434524636 0024667 0 ustar 00root root 0000000 0000000 language: go sudo: false go: - 1.x - tip install: - go get github.com/golang/dep/cmd/dep - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls - dep ensure - go build script: - go vet - go test -v -covermode=count -coverprofile=coverage.out - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/Gopkg.lock 0000664 0000000 0000000 00000004457 14434524636 0024506 0 ustar 00root root 0000000 0000000 # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. [[projects]] branch = "master" name = "github.com/beorn7/perks" packages = ["quantile"] revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9" [[projects]] name = "github.com/davecgh/go-spew" packages = ["spew"] revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] branch = "master" name = "github.com/golang/protobuf" packages = ["proto"] revision = "130e6b02ab059e7b717a096f397c5b60111cae74" [[projects]] name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] revision = "3247c84500bff8d9fb6d579d800f20b3e091582c" version = "v1.0.0" [[projects]] name = "github.com/pmezard/go-difflib" packages = ["difflib"] revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] name = "github.com/prometheus/client_golang" packages = ["prometheus"] revision = "c5b7fccd204277076155f10851dad72b76a49317" version = "v0.8.0" [[projects]] branch = "master" name = "github.com/prometheus/client_model" packages = ["go"] revision = "6f3806018612930941127f2a7c6c453ba2c527d2" [[projects]] branch = "master" name = "github.com/prometheus/common" packages = ["expfmt","internal/bitbucket.org/ww/goautoneg","model"] revision = "2f17f4a9d485bf34b4bfaccc273805040e4f86c8" [[projects]] branch = "master" name = "github.com/prometheus/procfs" packages = [".","xfs"] revision = "e645f4e5aaa8506fc71d6edbc5c4ff02c04c46f2" [[projects]] name = "github.com/sirupsen/logrus" packages = ["."] revision = "f006c2ac4710855cf0f916dd6b77acf6b048dc6e" version = "v1.0.3" [[projects]] name = "github.com/stretchr/testify" packages = ["assert"] revision = "69483b4bd14f5845b5a1e55bca19e954e827f1d0" version = "v1.1.4" [[projects]] branch = "master" name = "golang.org/x/crypto" packages = ["ssh/terminal"] revision = "9419663f5a44be8b34ca85f08abc5fe1be11f8a3" [[projects]] branch = "master" name = "golang.org/x/sys" packages = ["unix","windows"] revision = "314a259e304ff91bd6985da2a7149bbf91237993" [solve-meta] analyzer-name = "dep" analyzer-version = 1 inputs-digest = "36d94413e5fdab027b84850df466089880bec5abaff8f69c5ad07c1532758f3d" solver-name = "gps-cdcl" solver-version = 1 golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/Gopkg.toml 0000664 0000000 0000000 00000000176 14434524636 0024523 0 ustar 00root root 0000000 0000000 # Gopkg.toml # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md # for detailed Gopkg.toml documentation. golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/LICENSE 0000664 0000000 0000000 00000026135 14434524636 0023567 0 ustar 00root root 0000000 0000000 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. golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/README.md 0000664 0000000 0000000 00000006077 14434524636 0024044 0 ustar 00root root 0000000 0000000
# promrus Logrus hook to expose the number of log messages as Prometheus metrics: ``` log_messages{level="debug"} log_messages{level="info"} log_messages{level="warning"} log_messages{level="error"} ``` ## Usage Sample code: ```go package main import ( "net/http" "time" "github.com/prometheus/client_golang/prometheus/promhttp" log "github.com/sirupsen/logrus" "github.com/weaveworks/promrus" ) func main() { // Create the Prometheus hook: hook := promrus.MustNewPrometheusHook() // Configure logrus to use the Prometheus hook: log.AddHook(hook) // Expose Prometheus metrics via HTTP, as you usually would: go http.ListenAndServe(":8080", promhttp.Handler()) // Log with logrus, as you usually would. // Every time the program generates a log message, a Prometheus counter is incremented for the corresponding level. for { log.Infof("foo") time.Sleep(1 * time.Second) } } ``` Run the above program: ``` $ go get -u github.com/golang/dep/cmd/dep $ dep ensure $ go run main.go INFO[0000] foo INFO[0001] foo INFO[0002] foo [...] INFO[0042] foo ``` Scrape the Prometheus metrics exposed by the hook: ``` $ curl -fsS localhost:8080 | grep log_messages # HELP log_messages Total number of log messages. # TYPE log_messages counter log_messages{level="debug"} 0 log_messages{level="error"} 0 log_messages{level="info"} 42 log_messages{level="warning"} 0 ``` ## Setup development environment ``` $ go get github.com/golang/dep/cmd/dep $ dep ensure ``` ## Compile ``` $ go build ``` ## Test ``` $ go test DEBU[0000] this is at debug level! INFO[0000] this is at info level! WARN[0000] this is at warning level! ERRO[0000] this is at error level! PASS ok github.com/weaveworks/promrus 0.011s ``` ## Getting Help If you have any questions about, feedback for or problems with `promrus`: - Invite yourself to the Weave Users Slack. - Ask a question on the [#general](https://weave-community.slack.com/messages/general/) slack channel. - [File an issue](https://github.com/weaveworks/promrus/issues/new). Weaveworks follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a Weaveworks project maintainer, or Alexis Richardson (alexis@weave.works). Your feedback is always welcome! golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/promrus.go 0000664 0000000 0000000 00000004473 14434524636 0024621 0 ustar 00root root 0000000 0000000 package promrus import ( "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) // PrometheusHook exposes Prometheus counters for each of logrus' log levels. type PrometheusHook struct { counterVec *prometheus.CounterVec } var supportedLevels = []logrus.Level{logrus.DebugLevel, logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel} // NewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels. // Contrarily to MustNewPrometheusHook, it returns an error to the caller in case of issue. // Use NewPrometheusHook if you want more control. Use MustNewPrometheusHook if you want a less verbose hook creation. func NewPrometheusHook() (*PrometheusHook, error) { counterVec := prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "log_messages_total", Help: "Total number of log messages.", }, []string{"level"}) // Initialise counters for all supported levels: for _, level := range supportedLevels { counterVec.WithLabelValues(level.String()) } // Try to unregister the counter vector, in case already registered for some reason, // e.g. double initialisation/configuration done by mistake by the end-user. prometheus.Unregister(counterVec) // Try to register the counter vector: err := prometheus.Register(counterVec) if err != nil { return nil, err } return &PrometheusHook{ counterVec: counterVec, }, nil } // MustNewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels. // Contrarily to NewPrometheusHook, it does not return any error to the caller, but panics instead. // Use MustNewPrometheusHook if you want a less verbose hook creation. Use NewPrometheusHook if you want more control. func MustNewPrometheusHook() *PrometheusHook { hook, err := NewPrometheusHook() if err != nil { panic(err) } return hook } // Fire increments the appropriate Prometheus counter depending on the entry's log level. func (hook *PrometheusHook) Fire(entry *logrus.Entry) error { hook.counterVec.WithLabelValues(entry.Level.String()).Inc() return nil } // Levels returns all supported log levels, i.e.: Debug, Info, Warn and Error, as // there is no point incrementing a counter just before exiting/panicking. func (hook *PrometheusHook) Levels() []logrus.Level { return supportedLevels } golang-github-weaveworks-promrus-1.2.0+git20210208.77c195c/promrus_test.go 0000664 0000000 0000000 00000007752 14434524636 0025663 0 ustar 00root root 0000000 0000000 package promrus_test import ( "fmt" "io/ioutil" "net/http" "strconv" "strings" "testing" "github.com/prometheus/client_golang/prometheus/promhttp" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/weaveworks/promrus" ) const ( addr string = ":8080" endpoint string = "/metrics" ) func TestRegisteringHookMultipleTimesShouldBeSafe(t *testing.T) { log.AddHook(promrus.MustNewPrometheusHook()) log.AddHook(promrus.MustNewPrometheusHook()) // Initialising twice in a row should NOT raise any error. server := httpServePrometheusMetrics(t) lines := httpGetMetrics(t) assert.Equal(t, 0, countFor(t, log.InfoLevel, lines)) log.Info("this is at info level!") lines = httpGetMetrics(t) assert.Equal(t, 1, countFor(t, log.InfoLevel, lines)) log.AddHook(promrus.MustNewPrometheusHook()) // Initialising again here should NOT raise any error, but will reset counters. lines = httpGetMetrics(t) assert.Equal(t, 0, countFor(t, log.InfoLevel, lines)) server.Close() } func TestExposeAndQueryLogrusCounters(t *testing.T) { // Create Prometheus hook and configure logrus to use it: hook := promrus.MustNewPrometheusHook() log.AddHook(hook) log.SetLevel(log.DebugLevel) server := httpServePrometheusMetrics(t) lines := httpGetMetrics(t) assert.Equal(t, 0, countFor(t, log.DebugLevel, lines)) assert.Equal(t, 0, countFor(t, log.InfoLevel, lines)) assert.Equal(t, 0, countFor(t, log.WarnLevel, lines)) assert.Equal(t, 0, countFor(t, log.ErrorLevel, lines)) log.Debug("this is at debug level!") lines = httpGetMetrics(t) assert.Equal(t, 1, countFor(t, log.DebugLevel, lines)) assert.Equal(t, 0, countFor(t, log.InfoLevel, lines)) assert.Equal(t, 0, countFor(t, log.WarnLevel, lines)) assert.Equal(t, 0, countFor(t, log.ErrorLevel, lines)) log.Info("this is at info level!") lines = httpGetMetrics(t) assert.Equal(t, 1, countFor(t, log.DebugLevel, lines)) assert.Equal(t, 1, countFor(t, log.InfoLevel, lines)) assert.Equal(t, 0, countFor(t, log.WarnLevel, lines)) assert.Equal(t, 0, countFor(t, log.ErrorLevel, lines)) log.Warn("this is at warning level!") lines = httpGetMetrics(t) assert.Equal(t, 1, countFor(t, log.DebugLevel, lines)) assert.Equal(t, 1, countFor(t, log.InfoLevel, lines)) assert.Equal(t, 1, countFor(t, log.WarnLevel, lines)) assert.Equal(t, 0, countFor(t, log.ErrorLevel, lines)) log.Error("this is at error level!") lines = httpGetMetrics(t) assert.Equal(t, 1, countFor(t, log.DebugLevel, lines)) assert.Equal(t, 1, countFor(t, log.InfoLevel, lines)) assert.Equal(t, 1, countFor(t, log.WarnLevel, lines)) assert.Equal(t, 1, countFor(t, log.ErrorLevel, lines)) server.Close() } // httpServePrometheusMetrics exposes the Prometheus metrics over HTTP, in a different go routine. func httpServePrometheusMetrics(t *testing.T) *http.Server { server := &http.Server{ Addr: addr, Handler: promhttp.Handler(), } go server.ListenAndServe() return server } // httpGetMetrics queries the local HTTP server for the exposed metrics and parses the response. func httpGetMetrics(t *testing.T) []string { resp, err := http.Get(fmt.Sprintf("http://localhost%v%v", addr, endpoint)) assert.Nil(t, err) body, err := ioutil.ReadAll(resp.Body) assert.Nil(t, err) lines := strings.Split(string(body), "\n") assert.True(t, len(lines) > 0) return lines } // countFor is a helper function to get the counter's value for the provided level. func countFor(t *testing.T, level log.Level, lines []string) int { // Metrics are exposed as per the below example: // # HELP test_debug Number of log statements at debug level. // # TYPE test_debug counter // test_debug 0 metric := fmt.Sprintf("log_messages_total{level=\"%v\"}", level) for _, line := range lines { items := strings.Split(line, " ") if len(items) != 2 { // e.g. {"test_debug", "0"} continue } if items[0] == metric { count, err := strconv.ParseInt(items[1], 10, 32) assert.Nil(t, err) return int(count) } } panic(fmt.Sprintf("Could not find %v in %v", metric, lines)) }