├── .gitignore ├── LICENSE ├── README.md ├── buffer.go ├── buffer_test.go ├── context.go ├── context_test.go ├── go.mod └── tag.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # logtags: key/value annotations for Go contexts 2 | 3 | This package provides a way to attach key/value annotations 4 | to a Go `context.Context`. 5 | 6 | This feature is used e.g. in CockroachDB to annotate contexts with 7 | user-facing details from the call stack, for use in logging output. 8 | 9 | **How to use:** 10 | 11 | - adding k/v data to a context: 12 | 13 | ```go 14 | func AddTag(ctx context.Context, key string, value interface{}) context.Context 15 | ``` 16 | 17 | For example: 18 | 19 | ```go 20 | func foo(ctx context.Context) { 21 | ctx = logtags.AddTag(ctx, "foo", 123) 22 | bar(ctx) 23 | } 24 | ``` 25 | 26 | - retrieving k/v data from a context: 27 | 28 | ```go 29 | func FromContext(ctx context.Context) *Buffer 30 | func (b *Buffer) Get() []Tag 31 | func (t *Tag) Key() string 32 | func (t *Tag) Value() interface{} 33 | ``` 34 | 35 | **How it works:** 36 | 37 | `logtags` stores the provided key/value pairs into an object of type 38 | `Buffer`, then uses Go's standard `context.WithValue` to attach the 39 | buffer. 40 | 41 | An instance of `Buffer` inside a context is immutable. When adding a 42 | new k/v pair to a context that already carries a `Buffer`, a new one 43 | is created with all previous k/v pair, and the new k/v pair is added 44 | to that. 45 | 46 | The `FromContext()` function retrieves the topmost (most recent) 47 | `Buffer`. 48 | 49 | **Advanced uses:** 50 | 51 | To add multiple k/v pairs in one go, without using quadratic space in 52 | `Buffer` instances: 53 | 54 | 1. manually instantiate a `Buffer`. 55 | 2. use `func (*Buffer) Add(key string, value interface{})` to populate the buffer. 56 | 3. use `func AddTags(ctx context.Context, tags *Buffer) context.Context` to embark 57 | all the k/v pairs at once. 58 | 59 | To format all the contained k/v pairs in a `Buffer`, use its 60 | `String()` or `FormatToString(*strings.Builder)` methods: 61 | - when the `value` part is `nil`, only the key is displayed. 62 | - when the `value` part is non-nil, and the key is just one character 63 | long, the key and value are concatenated for display. This enables e.g. 64 | printing k=`"n"`, v=123 as `n123`. 65 | - otherwise, the key and value are printed with `=` as separator. 66 | 67 | For example: 68 | 69 | ```go 70 | ctx = logtags.AddTag(ctx, "foo", 123) 71 | ctx = logtags.AddTag(ctx, "x", 456) 72 | ctx = logtags.AddTag(ctx, "bar", nil) 73 | fmt.Println(logtags.FromContext(ctx).String()) 74 | // prints foo=123,x456,bar 75 | ``` 76 | 77 | -------------------------------------------------------------------------------- /buffer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Cockroach Authors. 2 | // 3 | // Use of this software is governed by the Business Source License included 4 | // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. 5 | // 6 | // Change Date: 2022-10-01 7 | // 8 | // On the date above, in accordance with the Business Source License, use 9 | // of this software will be governed by the Apache License, Version 2.0, 10 | // included in the file licenses/APL.txt and at 11 | // https://www.apache.org/licenses/LICENSE-2.0 12 | 13 | package logtags 14 | 15 | import ( 16 | "fmt" 17 | "strings" 18 | ) 19 | 20 | const staticSlots = 4 21 | 22 | // Buffer is an immutable list of Tags. 23 | type Buffer struct { 24 | tags []Tag 25 | prealloc [staticSlots]Tag 26 | } 27 | 28 | // SingleTagBuffer returns a Buffer with a single tag. 29 | func SingleTagBuffer(key string, value any) *Buffer { 30 | b := &Buffer{} 31 | b.init(1, 1) 32 | b.tags[0] = Tag{key: key, value: value} 33 | return b 34 | } 35 | 36 | // BuildBuffer is used to build a *Buffer that contains an arbitrary number 37 | // of tags. Sample usage: 38 | // 39 | // bld := BuildBuffer() 40 | // bld.Add("a", 1) 41 | // bld.Add("b", 2) 42 | // buf := bld.Finish() 43 | // 44 | // It is equivalent to using SingleTagBuffer() followed by Buffer.Add() calls, 45 | // but avoids allocating each intermediate buffer. 46 | func BuildBuffer() BufferBuilder { 47 | bld := BufferBuilder{b: &Buffer{}} 48 | bld.b.init(0, 0) 49 | return bld 50 | } 51 | 52 | // BufferBuilder is returned by BuildBuffer. 53 | type BufferBuilder struct { 54 | b *Buffer 55 | } 56 | 57 | // Add a log tag to the buffer. If the key was added already, the value is 58 | // replaced. 59 | func (bld *BufferBuilder) Add(key string, value any) { 60 | bld.b.addOrReplace(key, value) 61 | } 62 | 63 | // Finish returns the buffer with the tags that were added to the builder. 64 | func (bld *BufferBuilder) Finish() *Buffer { 65 | b := bld.b 66 | bld.b = nil 67 | return b 68 | } 69 | 70 | // Get returns the tags, as a slice. This slice must not be modified. 71 | func (b *Buffer) Get() []Tag { 72 | return b.tags 73 | } 74 | 75 | // GetTag returns the tag corresponding to the given key. If the tag doesn't 76 | // exist, the bool return value will be false. 77 | func (b *Buffer) GetTag(key string) (Tag, bool) { 78 | if b == nil { 79 | return Tag{}, false 80 | } 81 | for _, t := range b.tags { 82 | if t.Key() == key { 83 | return t, true 84 | } 85 | } 86 | return Tag{}, false 87 | } 88 | 89 | // Add returns a new buffer with one more tag. If the tag has the same key as an 90 | // earlier tag, that tag is overwritten. 91 | // The receiver can be nil. 92 | func (b *Buffer) Add(key string, value any) *Buffer { 93 | if b == nil { 94 | return SingleTagBuffer(key, value) 95 | } 96 | res := &Buffer{} 97 | res.init(len(b.tags), len(b.tags)+1) 98 | copy(res.tags, b.tags) 99 | res.addOrReplace(key, value) 100 | return res 101 | } 102 | 103 | // Remove returns a new Buffer with the tag with key `key` removed. If the tag 104 | // does not exist, the receiver is returned (unchanged). The bool return value 105 | // is true if the tag existed. 106 | func (b *Buffer) Remove(key string) (*Buffer, bool) { 107 | if b == nil { 108 | return nil, false 109 | } 110 | for i, t := range b.tags { 111 | if t.Key() == key { 112 | res := &Buffer{} 113 | res.init(len(b.tags)-1, 0 /* capacityHint */) 114 | copy(res.tags, b.tags[:i]) 115 | copy(res.tags[i:], b.tags[i+1:]) 116 | return res, true 117 | } 118 | } 119 | return b, false 120 | } 121 | 122 | // Merge returns a new buffer which contains tags from the receiver, followed by 123 | // the tags from . 124 | // 125 | // If both buffers have the same tag, the tag will appear only one time, with 126 | // the value it has in . It can appear either in the place of the tag in 127 | // or the tag in (depending on which is deemed more efficient). 128 | // 129 | // The method can return or if the result is identical with one of 130 | // them. 131 | // 132 | // The receiver can be nil. 133 | func (b *Buffer) Merge(other *Buffer) *Buffer { 134 | if b == nil || len(b.tags) == 0 { 135 | return other 136 | } 137 | if other == nil || len(other.tags) == 0 { 138 | return b 139 | } 140 | 141 | // Check for a common case where b's tags are a subsequence of the 142 | // other tags. In practice this happens when we start with an annotated 143 | // context and we annotate it again at a lower level (with more specific 144 | // information). Frequent examples seen in practice are when b has a node ID 145 | // tag and other has both a node and a store ID tag; and when b has a node ID 146 | // and store ID tag and other has node, store, and replica tags. 147 | if diff := len(other.tags) - len(b.tags); diff >= 0 { 148 | i, j := 0, 0 149 | for i < len(b.tags) && j-i <= diff { 150 | if b.tags[i].key == other.tags[j].key { 151 | i++ 152 | } 153 | j++ 154 | } 155 | if i == len(b.tags) { 156 | return other 157 | } 158 | } 159 | 160 | // Another common case is when we aren't adding any new tags or values; find 161 | // and ignore the longest prefix of redundant tags. 162 | i := 0 163 | for ; i < len(other.tags); i++ { 164 | idx := b.find(other.tags[i].key) 165 | if idx == -1 || b.tags[idx].value != other.tags[i].value { 166 | break 167 | } 168 | } 169 | if i == len(other.tags) { 170 | return b 171 | } 172 | 173 | res := &Buffer{} 174 | res.init(len(b.tags), len(b.tags)+len(other.tags)-i) 175 | copy(res.tags, b.tags) 176 | 177 | for ; i < len(other.tags); i++ { 178 | res.addOrReplace(other.tags[i].key, other.tags[i].value) 179 | } 180 | return res 181 | } 182 | 183 | // String returns a string representation of the tags. 184 | func (b *Buffer) String() string { 185 | var buf strings.Builder 186 | b.FormatToString(&buf) 187 | return buf.String() 188 | } 189 | 190 | // FormatToString emits the k/v pairs to a strings.Builder. 191 | // - the k/v pairs are separated by commas (& no spaces). 192 | // - if there is no value, only the key is printed. 193 | // - if there is a value, and the key is just 1 character long, 194 | // the key and the value are concatenated. 195 | // This supports e.g. printing k="n", v=123 as "n123". 196 | // - otherwise, it prints "k=v". 197 | func (b *Buffer) FormatToString(buf *strings.Builder) { 198 | comma := "" 199 | for _, t := range b.Get() { 200 | buf.WriteString(comma) 201 | buf.WriteString(t.Key()) 202 | if v := t.Value(); v != nil && v != "" { 203 | if len(t.Key()) > 1 { 204 | buf.WriteByte('=') 205 | } 206 | fmt.Fprint(buf, v) 207 | } 208 | comma = "," 209 | } 210 | } 211 | 212 | // init initializes b.tags to a slice of len `length` (filled with zero values). 213 | // The slice may have capacity capacityHint. If capacityHint is less than 214 | // length, it is ignored. 215 | func (b *Buffer) init(length, capacityHint int) { 216 | if length <= staticSlots { 217 | // Even if capacityHint is larger that staticSlots, we still want to try to 218 | // avoid the allocation (especially since tags frequently get deduplicated). 219 | b.tags = b.prealloc[:length] 220 | } else { 221 | if capacityHint < length { 222 | capacityHint = length 223 | } 224 | b.tags = make([]Tag, length, capacityHint) 225 | } 226 | } 227 | 228 | func (b *Buffer) addOrReplace(key string, value any) { 229 | for i := range b.tags { 230 | if b.tags[i].key == key { 231 | b.tags[i].value = value 232 | return 233 | } 234 | } 235 | b.tags = append(b.tags, Tag{key: key, value: value}) 236 | } 237 | 238 | // find returns the position of the tag with the given key, or -1 if 239 | // it is not found. 240 | func (b *Buffer) find(key string) int { 241 | for i := range b.tags { 242 | if b.tags[i].key == key { 243 | return i 244 | } 245 | } 246 | return -1 247 | } 248 | -------------------------------------------------------------------------------- /buffer_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Cockroach Authors. 2 | // 3 | // Use of this software is governed by the Business Source License included 4 | // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. 5 | // 6 | // Change Date: 2022-10-01 7 | // 8 | // On the date above, in accordance with the Business Source License, use 9 | // of this software will be governed by the Apache License, Version 2.0, 10 | // included in the file licenses/APL.txt and at 11 | // https://www.apache.org/licenses/LICENSE-2.0 12 | 13 | package logtags 14 | 15 | import ( 16 | "context" 17 | "strings" 18 | "testing" 19 | ) 20 | 21 | func buffer(str string) *Buffer { 22 | f := &Buffer{} 23 | for _, t := range strings.Split(str, ",") { 24 | s := strings.SplitN(t, "=", 2) 25 | val := "" 26 | if len(s) > 1 { 27 | val = s[1] 28 | } 29 | f = f.Add(s[0], val) 30 | } 31 | return f 32 | } 33 | 34 | func TestBufferMerge(t *testing.T) { 35 | cases := []struct{ left, right, expected string }{ 36 | {"a=1", "b=2", "a1,b2"}, 37 | {"a=1,b=2", "c=3,d=4", "a1,b2,c3,d4"}, 38 | 39 | {"a=1", "a=2", "a2"}, 40 | 41 | {"a=1,b=2,c=3", "b=4,d=5", "a1,b4,c3,d5"}, 42 | {"b=2,d=3", "a=4,b=5,c=6,d=7,e=8", "a4,b5,c6,d7,e8"}, 43 | {"b=2,d=3", "a=4,b=5,c=6,d=7", "a4,b5,c6,d7"}, 44 | {"b=2,d=3", "b=5,c=6,d=7,e=8", "b5,c6,d7,e8"}, 45 | } 46 | for _, tc := range cases { 47 | l := buffer(tc.left) 48 | r := buffer(tc.right) 49 | if res := l.Merge(r).String(); res != tc.expected { 50 | t.Errorf("merge %s with %s: got %s expected %s", tc.left, tc.right, res, tc.expected) 51 | } 52 | } 53 | } 54 | 55 | func TestBufferAdd(t *testing.T) { 56 | b := buffer("a=1") 57 | ctx := AddTags(context.Background(), b) 58 | if expected, res := "a1", FromContext(ctx).String(); res != expected { 59 | t.Errorf("AddTags failed: expected %q, got %q", expected, res) 60 | } 61 | 62 | ctx = AddTags(ctx, FromContext(context.Background())) 63 | if expected, res := "a1", FromContext(ctx).String(); res != expected { 64 | t.Errorf("AddTags failed: expected %q, got %q", expected, res) 65 | } 66 | } 67 | 68 | func TestBufferBuild(t *testing.T) { 69 | bld := BuildBuffer() 70 | bld.Add("a", 1) 71 | bld.Add("b", 2) 72 | b := bld.Finish() 73 | if expected := "a1,b2"; b.String() != expected { 74 | t.Fatalf("expected %q, got %q", expected, b.String()) 75 | } 76 | 77 | bld = BuildBuffer() 78 | bld.Add("a", 1) 79 | bld.Add("b", 2) 80 | bld.Add("a", 10) 81 | bld.Add("c", 3) 82 | b = bld.Finish() 83 | if expected := "a10,b2,c3"; b.String() != expected { 84 | t.Fatalf("expected %q, got %q", expected, b.String()) 85 | } 86 | } 87 | 88 | func BenchmarkBuffer(b *testing.B) { 89 | // This benchmark uses a set of tag operations that have been observed to be 90 | // the most common during a mixed KV workload: 91 | // 92 | // Left tags Right tags 93 | // ----------------------------- 94 | // n,client,user n 95 | // n,s n,s,r 96 | // n n,s 97 | // client,user,n,txn n 98 | 99 | l1, r1 := buffer("n,client,user"), buffer("n") 100 | l2, r2 := buffer("n,s"), buffer("n,s,r") 101 | l3, r3 := buffer("n"), buffer("n,s") 102 | l4, r4 := buffer("client,user,n,txn"), buffer("n") 103 | 104 | b.ResetTimer() 105 | for i := 0; i < b.N; i++ { 106 | _ = l1.Merge(r1) 107 | _ = l2.Merge(r2) 108 | _ = l3.Merge(r3) 109 | _ = l4.Merge(r4) 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /context.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Cockroach Authors. 2 | // 3 | // Use of this software is governed by the Business Source License included 4 | // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. 5 | // 6 | // Change Date: 2022-10-01 7 | // 8 | // On the date above, in accordance with the Business Source License, use 9 | // of this software will be governed by the Apache License, Version 2.0, 10 | // included in the file licenses/APL.txt and at 11 | // https://www.apache.org/licenses/LICENSE-2.0 12 | 13 | package logtags 14 | 15 | import "context" 16 | 17 | // contextLogTagsKey is an empty type for the handle associated with the log 18 | // tags (*Buffer) value (see context.Value). 19 | type contextLogTagsKey struct{} 20 | 21 | // FromContext returns the tags stored in the context (by WithTags, AddTag, or 22 | // AddTags). 23 | func FromContext(ctx context.Context) *Buffer { 24 | if fromContextFn != nil { 25 | return fromContextFn(ctx) 26 | } 27 | val := ctx.Value(contextLogTagsKey{}) 28 | if val == nil { 29 | return nil 30 | } 31 | return val.(*Buffer) 32 | } 33 | 34 | // WithTags returns a context with the given tags. Any existing tags are 35 | // ignored. 36 | func WithTags(ctx context.Context, tags *Buffer) context.Context { 37 | if withTagsFn != nil { 38 | return withTagsFn(ctx, tags) 39 | } 40 | return context.WithValue(ctx, contextLogTagsKey{}, tags) 41 | } 42 | 43 | // AddTag returns a context that has the tags in the given context plus another 44 | // tag. Tags are deduplicated (see Buffer.AddTag). 45 | func AddTag(ctx context.Context, key string, value interface{}) context.Context { 46 | b := FromContext(ctx) 47 | return WithTags(ctx, b.Add(key, value)) 48 | } 49 | 50 | // RemoveTag returns a context that has the tags in the given context except the 51 | // tag with key `key`. If such a tag does not exist, the given context is 52 | // returned. 53 | func RemoveTag(ctx context.Context, key string) context.Context { 54 | b := FromContext(ctx) 55 | newB, ok := b.Remove(key) 56 | if !ok { 57 | return ctx 58 | } 59 | return WithTags(ctx, newB) 60 | } 61 | 62 | // AddTags returns a context that has the tags in the given context plus another 63 | // set of tags. Tags are deduplicated (see Buffer.AddTags). 64 | func AddTags(ctx context.Context, tags *Buffer) context.Context { 65 | b := FromContext(ctx) 66 | newB := b.Merge(tags) 67 | if newB == b { 68 | return ctx 69 | } 70 | return WithTags(ctx, newB) 71 | } 72 | 73 | // OverrideContextFuncs can be used to override the implementation of 74 | // FromContext and WithTags. This is useful if we have a more efficient 75 | // implementation of context-associated values. 76 | // 77 | // Must be called before WithTags or FromContext are called. 78 | func OverrideContextFuncs( 79 | fromContext func(ctx context.Context) *Buffer, 80 | withTags func(ctx context.Context, tags *Buffer) context.Context, 81 | ) { 82 | fromContextFn = fromContext 83 | withTagsFn = withTags 84 | } 85 | 86 | var fromContextFn func(ctx context.Context) *Buffer 87 | var withTagsFn func(ctx context.Context, tags *Buffer) context.Context 88 | -------------------------------------------------------------------------------- /context_test.go: -------------------------------------------------------------------------------- 1 | package logtags 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | ) 7 | 8 | func TestRemove(t *testing.T) { 9 | b := &Buffer{} 10 | b = b.Add("1", nil) 11 | b = b.Add("2", nil) 12 | b = b.Add("3", nil) 13 | ctx := WithTags(context.Background(), b) 14 | rctx := RemoveTag(ctx, "2") 15 | if FromContext(rctx).String() != "1,3" { 16 | t.Fatalf("expected 1,3 got: %s", FromContext(rctx).String()) 17 | } 18 | rctx = RemoveTag(ctx, "3") 19 | if FromContext(rctx).String() != "1,2" { 20 | t.Fatalf("expected 1,2 got: %s", FromContext(rctx).String()) 21 | } 22 | rctx = RemoveTag(ctx, "4") 23 | if FromContext(rctx).String() != "1,2,3" { 24 | t.Fatalf("expected 1,2 got: %s", FromContext(rctx).String()) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cockroachdb/logtags 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /tag.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Cockroach Authors. 2 | // 3 | // Use of this software is governed by the Business Source License included 4 | // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. 5 | // 6 | // Change Date: 2022-10-01 7 | // 8 | // On the date above, in accordance with the Business Source License, use 9 | // of this software will be governed by the Apache License, Version 2.0, 10 | // included in the file licenses/APL.txt and at 11 | // https://www.apache.org/licenses/LICENSE-2.0 12 | 13 | package logtags 14 | 15 | import "fmt" 16 | 17 | // Tag is a log tag, which has a string key and an arbitrary value. 18 | // The value must support testing for equality. It can be nil. 19 | type Tag struct { 20 | key string 21 | value interface{} 22 | } 23 | 24 | // Key returns the key. 25 | func (t *Tag) Key() string { 26 | return t.key 27 | } 28 | 29 | // Value returns the value. 30 | func (t *Tag) Value() interface{} { 31 | return t.value 32 | } 33 | 34 | // ValueStr returns the value as a string. 35 | func (t *Tag) ValueStr() string { 36 | if t.value == nil { 37 | return "" 38 | } 39 | switch v := t.value.(type) { 40 | case string: 41 | return v 42 | case fmt.Stringer: 43 | return v.String() 44 | default: 45 | return fmt.Sprint(t.value) 46 | } 47 | } 48 | --------------------------------------------------------------------------------