├── LICENSE ├── README.md ├── glog.go ├── glog_bench_test.go ├── glog_context_test.go ├── glog_file.go ├── glog_file_linux.go ├── glog_file_nonwindows.go ├── glog_file_other.go ├── glog_file_posix.go ├── glog_file_windows.go ├── glog_flags.go ├── glog_test.go ├── glog_vmodule_test.go ├── go.mod ├── go.sum └── internal ├── logsink ├── logsink.go ├── logsink_fatal.go └── logsink_test.go └── stackdump ├── stackdump.go └── stackdump_test.go /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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # glog 2 | 3 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/golang/glog)](https://pkg.go.dev/github.com/golang/glog) 4 | 5 | Leveled execution logs for Go. 6 | 7 | This is an efficient pure Go implementation of leveled logs in the 8 | manner of the open source C++ package [_glog_](https://github.com/google/glog). 9 | 10 | By binding methods to booleans it is possible to use the log package without paying the expense of evaluating the arguments to the log. Through the `-vmodule` flag, the package also provides fine-grained 11 | control over logging at the file level. 12 | 13 | The comment from `glog.go` introduces the ideas: 14 | 15 | Package _glog_ implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. It provides the functions Info, Warning, Error, Fatal, plus formatting variants such as Infof. It also provides V-style loggingcontrolled by the `-v` and `-vmodule=file=2` flags. 16 | 17 | Basic examples: 18 | 19 | ```go 20 | glog.Info("Prepare to repel boarders") 21 | 22 | glog.Fatalf("Initialization failed: %s", err) 23 | ``` 24 | 25 | See the documentation for the V function for an explanation of these examples: 26 | 27 | ```go 28 | if glog.V(2) { 29 | glog.Info("Starting transaction...") 30 | } 31 | glog.V(2).Infoln("Processed", nItems, "elements") 32 | ``` 33 | 34 | The repository contains an open source version of the log package used inside Google. The master copy of the source lives inside Google, not here. The code in this repo is for export only and is not itself under development. Feature requests will be ignored. 35 | 36 | Send bug reports to golang-nuts@googlegroups.com. 37 | -------------------------------------------------------------------------------- /glog.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. 18 | // It provides functions that have a name matched by regex: 19 | // 20 | // (Info|Warning|Error|Fatal)(Context)?(Depth)?(f)? 21 | // 22 | // If Context is present, function takes context.Context argument. The 23 | // context is used to pass through the Trace Context to log sinks that can make use 24 | // of it. 25 | // It is recommended to use the context variant of the functions over the non-context 26 | // variants if a context is available to make sure the Trace Contexts are present 27 | // in logs. 28 | // 29 | // If Depth is present, this function calls log from a different depth in the call stack. 30 | // This enables a callee to emit logs that use the callsite information of its caller 31 | // or any other callers in the stack. When depth == 0, the original callee's line 32 | // information is emitted. When depth > 0, depth frames are skipped in the call stack 33 | // and the final frame is treated like the original callee to Info. 34 | // 35 | // If 'f' is present, function formats according to a format specifier. 36 | // 37 | // This package also provides V-style logging controlled by the -v and -vmodule=file=2 flags. 38 | // 39 | // Basic examples: 40 | // 41 | // glog.Info("Prepare to repel boarders") 42 | // 43 | // glog.Fatalf("Initialization failed: %s", err) 44 | // 45 | // See the documentation for the V function for an explanation of these examples: 46 | // 47 | // if glog.V(2) { 48 | // glog.Info("Starting transaction...") 49 | // } 50 | // 51 | // glog.V(2).Infoln("Processed", nItems, "elements") 52 | // 53 | // Log output is buffered and written periodically using Flush. Programs 54 | // should call Flush before exiting to guarantee all log output is written. 55 | // 56 | // By default, all log statements write to files in a temporary directory. 57 | // This package provides several flags that modify this behavior. 58 | // As a result, flag.Parse must be called before any logging is done. 59 | // 60 | // -logtostderr=false 61 | // Logs are written to standard error instead of to files. 62 | // -alsologtostderr=false 63 | // Logs are written to standard error as well as to files. 64 | // -stderrthreshold=ERROR 65 | // Log events at or above this severity are logged to standard 66 | // error as well as to files. 67 | // -log_dir="" 68 | // Log files will be written to this directory instead of the 69 | // default temporary directory. 70 | // 71 | // Other flags provide aids to debugging. 72 | // 73 | // -log_backtrace_at="" 74 | // A comma-separated list of file and line numbers holding a logging 75 | // statement, such as 76 | // -log_backtrace_at=gopherflakes.go:234 77 | // A stack trace will be written to the Info log whenever execution 78 | // hits one of these statements. (Unlike with -vmodule, the ".go" 79 | // must be present.) 80 | // -v=0 81 | // Enable V-leveled logging at the specified level. 82 | // -vmodule="" 83 | // The syntax of the argument is a comma-separated list of pattern=N, 84 | // where pattern is a literal file name (minus the ".go" suffix) or 85 | // "glob" pattern and N is a V level. For instance, 86 | // -vmodule=gopher*=3 87 | // sets the V level to 3 in all Go files whose names begin with "gopher", 88 | // and 89 | // -vmodule=/path/to/glog/glog_test=1 90 | // sets the V level to 1 in the Go file /path/to/glog/glog_test.go. 91 | // If a glob pattern contains a slash, it is matched against the full path, 92 | // and the file name. Otherwise, the pattern is 93 | // matched only against the file's basename. When both -vmodule and -v 94 | // are specified, the -vmodule values take precedence for the specified 95 | // modules. 96 | package glog 97 | 98 | // This file contains the parts of the log package that are shared among all 99 | // implementations (file, envelope, and appengine). 100 | 101 | import ( 102 | "bytes" 103 | "context" 104 | "errors" 105 | "fmt" 106 | stdLog "log" 107 | "os" 108 | "reflect" 109 | "runtime" 110 | "runtime/pprof" 111 | "strconv" 112 | "sync" 113 | "sync/atomic" 114 | "time" 115 | 116 | "github.com/golang/glog/internal/logsink" 117 | "github.com/golang/glog/internal/stackdump" 118 | ) 119 | 120 | var timeNow = time.Now // Stubbed out for testing. 121 | 122 | // MaxSize is the maximum size of a log file in bytes. 123 | var MaxSize uint64 = 1024 * 1024 * 1800 124 | 125 | // ErrNoLog is the error we return if no log file has yet been created 126 | // for the specified log type. 127 | var ErrNoLog = errors.New("log file not yet created") 128 | 129 | // OutputStats tracks the number of output lines and bytes written. 130 | type OutputStats struct { 131 | lines int64 132 | bytes int64 133 | } 134 | 135 | // Lines returns the number of lines written. 136 | func (s *OutputStats) Lines() int64 { 137 | return atomic.LoadInt64(&s.lines) 138 | } 139 | 140 | // Bytes returns the number of bytes written. 141 | func (s *OutputStats) Bytes() int64 { 142 | return atomic.LoadInt64(&s.bytes) 143 | } 144 | 145 | // Stats tracks the number of lines of output and number of bytes 146 | // per severity level. Values must be read with atomic.LoadInt64. 147 | var Stats struct { 148 | Info, Warning, Error OutputStats 149 | } 150 | 151 | var severityStats = [...]*OutputStats{ 152 | logsink.Info: &Stats.Info, 153 | logsink.Warning: &Stats.Warning, 154 | logsink.Error: &Stats.Error, 155 | logsink.Fatal: nil, 156 | } 157 | 158 | // Level specifies a level of verbosity for V logs. The -v flag is of type 159 | // Level and should be modified only through the flag.Value interface. 160 | type Level int32 161 | 162 | var metaPool sync.Pool // Pool of *logsink.Meta. 163 | 164 | // metaPoolGet returns a *logsink.Meta from metaPool as both an interface and a 165 | // pointer, allocating a new one if necessary. (Returning the interface value 166 | // directly avoids an allocation if there was an existing pointer in the pool.) 167 | func metaPoolGet() (any, *logsink.Meta) { 168 | if metai := metaPool.Get(); metai != nil { 169 | return metai, metai.(*logsink.Meta) 170 | } 171 | meta := new(logsink.Meta) 172 | return meta, meta 173 | } 174 | 175 | type stack bool 176 | 177 | const ( 178 | noStack = stack(false) 179 | withStack = stack(true) 180 | ) 181 | 182 | func appendBacktrace(depth int, format string, args []any) (string, []any) { 183 | // Capture a backtrace as a stackdump.Stack (both text and PC slice). 184 | // Structured log sinks can extract the backtrace in whichever format they 185 | // prefer (PCs or text), and Text sinks will include it as just another part 186 | // of the log message. 187 | // 188 | // Use depth instead of depth+1 so that the backtrace always includes the 189 | // log function itself - otherwise the reason for the trace appearing in the 190 | // log may not be obvious to the reader. 191 | dump := stackdump.Caller(depth) 192 | 193 | // Add an arg and an entry in the format string for the stack dump. 194 | // 195 | // Copy the "args" slice to avoid a rare but serious aliasing bug 196 | // (corrupting the caller's slice if they passed it to a non-Fatal call 197 | // using "..."). 198 | format = format + "\n\n%v\n" 199 | args = append(append([]any(nil), args...), dump) 200 | 201 | return format, args 202 | } 203 | 204 | // logf acts as ctxlogf, but doesn't expect a context. 205 | func logf(depth int, severity logsink.Severity, verbose bool, stack stack, format string, args ...any) { 206 | ctxlogf(nil, depth+1, severity, verbose, stack, format, args...) 207 | } 208 | 209 | // ctxlogf writes a log message for a log function call (or log function wrapper) 210 | // at the given depth in the current goroutine's stack. 211 | func ctxlogf(ctx context.Context, depth int, severity logsink.Severity, verbose bool, stack stack, format string, args ...any) { 212 | now := timeNow() 213 | _, file, line, ok := runtime.Caller(depth + 1) 214 | if !ok { 215 | file = "???" 216 | line = 1 217 | } 218 | 219 | if stack == withStack || backtraceAt(file, line) { 220 | format, args = appendBacktrace(depth+1, format, args) 221 | } 222 | 223 | metai, meta := metaPoolGet() 224 | *meta = logsink.Meta{ 225 | Context: ctx, 226 | Time: now, 227 | File: file, 228 | Line: line, 229 | Depth: depth + 1, 230 | Severity: severity, 231 | Verbose: verbose, 232 | Thread: int64(pid), 233 | } 234 | sinkf(meta, format, args...) 235 | // Clear pointer fields so they can be garbage collected early. 236 | meta.Context = nil 237 | meta.Stack = nil 238 | metaPool.Put(metai) 239 | } 240 | 241 | var sinkErrOnce sync.Once 242 | 243 | func sinkf(meta *logsink.Meta, format string, args ...any) { 244 | meta.Depth++ 245 | n, err := logsink.Printf(meta, format, args...) 246 | if stats := severityStats[meta.Severity]; stats != nil { 247 | atomic.AddInt64(&stats.lines, 1) 248 | atomic.AddInt64(&stats.bytes, int64(n)) 249 | } 250 | 251 | if err != nil { 252 | // Best-effort to generate a reasonable Fatalf-like 253 | // error message in all sinks that are still here for 254 | // the first goroutine that comes here and terminate 255 | // the process. 256 | sinkErrOnce.Do(func() { 257 | m := &logsink.Meta{} 258 | m.Time = timeNow() 259 | m.Severity = logsink.Fatal 260 | m.Thread = int64(pid) 261 | _, m.File, m.Line, _ = runtime.Caller(0) 262 | format, args := appendBacktrace(1, "log: exiting because of error writing previous log to sinks: %v", []any{err}) 263 | logsink.Printf(m, format, args...) 264 | flushAndAbort() 265 | }) 266 | } 267 | } 268 | 269 | // CopyStandardLogTo arranges for messages written to the Go "log" package's 270 | // default logs to also appear in the Google logs for the named and lower 271 | // severities. Subsequent changes to the standard log's default output location 272 | // or format may break this behavior. 273 | // 274 | // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not 275 | // recognized, CopyStandardLogTo panics. 276 | func CopyStandardLogTo(name string) { 277 | sev, err := logsink.ParseSeverity(name) 278 | if err != nil { 279 | panic(fmt.Sprintf("log.CopyStandardLogTo(%q): %v", name, err)) 280 | } 281 | // Set a log format that captures the user's file and line: 282 | // d.go:23: message 283 | stdLog.SetFlags(stdLog.Lshortfile) 284 | stdLog.SetOutput(logBridge(sev)) 285 | } 286 | 287 | // NewStandardLogger returns a Logger that writes to the Google logs for the 288 | // named and lower severities. 289 | // 290 | // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not 291 | // recognized, NewStandardLogger panics. 292 | func NewStandardLogger(name string) *stdLog.Logger { 293 | sev, err := logsink.ParseSeverity(name) 294 | if err != nil { 295 | panic(fmt.Sprintf("log.NewStandardLogger(%q): %v", name, err)) 296 | } 297 | return stdLog.New(logBridge(sev), "", stdLog.Lshortfile) 298 | } 299 | 300 | // logBridge provides the Write method that enables CopyStandardLogTo to connect 301 | // Go's standard logs to the logs provided by this package. 302 | type logBridge logsink.Severity 303 | 304 | // Write parses the standard logging line and passes its components to the 305 | // logger for severity(lb). 306 | func (lb logBridge) Write(b []byte) (n int, err error) { 307 | var ( 308 | file = "???" 309 | line = 1 310 | text string 311 | ) 312 | // Split "d.go:23: message" into "d.go", "23", and "message". 313 | if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { 314 | text = fmt.Sprintf("bad log format: %s", b) 315 | } else { 316 | file = string(parts[0]) 317 | text = string(parts[2][1:]) // skip leading space 318 | line, err = strconv.Atoi(string(parts[1])) 319 | if err != nil { 320 | text = fmt.Sprintf("bad line number: %s", b) 321 | line = 1 322 | } 323 | } 324 | 325 | // The depth below hard-codes details of how stdlog gets here. The alternative would be to walk 326 | // up the stack looking for src/log/log.go but that seems like it would be 327 | // unfortunately slow. 328 | const stdLogDepth = 4 329 | 330 | metai, meta := metaPoolGet() 331 | *meta = logsink.Meta{ 332 | Time: timeNow(), 333 | File: file, 334 | Line: line, 335 | Depth: stdLogDepth, 336 | Severity: logsink.Severity(lb), 337 | Thread: int64(pid), 338 | } 339 | 340 | format := "%s" 341 | args := []any{text} 342 | if backtraceAt(file, line) { 343 | format, args = appendBacktrace(meta.Depth, format, args) 344 | } 345 | 346 | sinkf(meta, format, args...) 347 | metaPool.Put(metai) 348 | 349 | return len(b), nil 350 | } 351 | 352 | // defaultFormat returns a fmt.Printf format specifier that formats its 353 | // arguments as if they were passed to fmt.Print. 354 | func defaultFormat(args []any) string { 355 | n := len(args) 356 | switch n { 357 | case 0: 358 | return "" 359 | case 1: 360 | return "%v" 361 | } 362 | 363 | b := make([]byte, 0, n*3-1) 364 | wasString := true // Suppress leading space. 365 | for _, arg := range args { 366 | isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String 367 | if wasString || isString { 368 | b = append(b, "%v"...) 369 | } else { 370 | b = append(b, " %v"...) 371 | } 372 | wasString = isString 373 | } 374 | return string(b) 375 | } 376 | 377 | // lnFormat returns a fmt.Printf format specifier that formats its arguments 378 | // as if they were passed to fmt.Println. 379 | func lnFormat(args []any) string { 380 | if len(args) == 0 { 381 | return "\n" 382 | } 383 | 384 | b := make([]byte, 0, len(args)*3) 385 | for range args { 386 | b = append(b, "%v "...) 387 | } 388 | b[len(b)-1] = '\n' // Replace the last space with a newline. 389 | return string(b) 390 | } 391 | 392 | // Verbose is a boolean type that implements Infof (like Printf) etc. 393 | // See the documentation of V for more information. 394 | type Verbose bool 395 | 396 | // V reports whether verbosity at the call site is at least the requested level. 397 | // The returned value is a boolean of type Verbose, which implements Info, Infoln 398 | // and Infof. These methods will write to the Info log if called. 399 | // Thus, one may write either 400 | // 401 | // if glog.V(2) { glog.Info("log this") } 402 | // 403 | // or 404 | // 405 | // glog.V(2).Info("log this") 406 | // 407 | // The second form is shorter but the first is cheaper if logging is off because it does 408 | // not evaluate its arguments. 409 | // 410 | // Whether an individual call to V generates a log record depends on the setting of 411 | // the -v and --vmodule flags; both are off by default. If the level in the call to 412 | // V is at most the value of -v, or of -vmodule for the source file containing the 413 | // call, the V call will log. 414 | func V(level Level) Verbose { 415 | return VDepth(1, level) 416 | } 417 | 418 | // VDepth acts as V but uses depth to determine which call frame to check vmodule for. 419 | // VDepth(0, level) is the same as V(level). 420 | func VDepth(depth int, level Level) Verbose { 421 | return Verbose(verboseEnabled(depth+1, level)) 422 | } 423 | 424 | // Info is equivalent to the global Info function, guarded by the value of v. 425 | // See the documentation of V for usage. 426 | func (v Verbose) Info(args ...any) { 427 | v.InfoDepth(1, args...) 428 | } 429 | 430 | // InfoDepth is equivalent to the global InfoDepth function, guarded by the value of v. 431 | // See the documentation of V for usage. 432 | func (v Verbose) InfoDepth(depth int, args ...any) { 433 | if v { 434 | logf(depth+1, logsink.Info, true, noStack, defaultFormat(args), args...) 435 | } 436 | } 437 | 438 | // InfoDepthf is equivalent to the global InfoDepthf function, guarded by the value of v. 439 | // See the documentation of V for usage. 440 | func (v Verbose) InfoDepthf(depth int, format string, args ...any) { 441 | if v { 442 | logf(depth+1, logsink.Info, true, noStack, format, args...) 443 | } 444 | } 445 | 446 | // Infoln is equivalent to the global Infoln function, guarded by the value of v. 447 | // See the documentation of V for usage. 448 | func (v Verbose) Infoln(args ...any) { 449 | if v { 450 | logf(1, logsink.Info, true, noStack, lnFormat(args), args...) 451 | } 452 | } 453 | 454 | // Infof is equivalent to the global Infof function, guarded by the value of v. 455 | // See the documentation of V for usage. 456 | func (v Verbose) Infof(format string, args ...any) { 457 | if v { 458 | logf(1, logsink.Info, true, noStack, format, args...) 459 | } 460 | } 461 | 462 | // InfoContext is equivalent to the global InfoContext function, guarded by the value of v. 463 | // See the documentation of V for usage. 464 | func (v Verbose) InfoContext(ctx context.Context, args ...any) { 465 | v.InfoContextDepth(ctx, 1, args...) 466 | } 467 | 468 | // InfoContextf is equivalent to the global InfoContextf function, guarded by the value of v. 469 | // See the documentation of V for usage. 470 | func (v Verbose) InfoContextf(ctx context.Context, format string, args ...any) { 471 | if v { 472 | ctxlogf(ctx, 1, logsink.Info, true, noStack, format, args...) 473 | } 474 | } 475 | 476 | // InfoContextDepth is equivalent to the global InfoContextDepth function, guarded by the value of v. 477 | // See the documentation of V for usage. 478 | func (v Verbose) InfoContextDepth(ctx context.Context, depth int, args ...any) { 479 | if v { 480 | ctxlogf(ctx, depth+1, logsink.Info, true, noStack, defaultFormat(args), args...) 481 | } 482 | } 483 | 484 | // InfoContextDepthf is equivalent to the global InfoContextDepthf function, guarded by the value of v. 485 | // See the documentation of V for usage. 486 | func (v Verbose) InfoContextDepthf(ctx context.Context, depth int, format string, args ...any) { 487 | if v { 488 | ctxlogf(ctx, depth+1, logsink.Info, true, noStack, format, args...) 489 | } 490 | } 491 | 492 | // Info logs to the INFO log. 493 | // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. 494 | func Info(args ...any) { 495 | InfoDepth(1, args...) 496 | } 497 | 498 | // InfoDepth calls Info from a different depth in the call stack. 499 | // This enables a callee to emit logs that use the callsite information of its caller 500 | // or any other callers in the stack. When depth == 0, the original callee's line 501 | // information is emitted. When depth > 0, depth frames are skipped in the call stack 502 | // and the final frame is treated like the original callee to Info. 503 | func InfoDepth(depth int, args ...any) { 504 | logf(depth+1, logsink.Info, false, noStack, defaultFormat(args), args...) 505 | } 506 | 507 | // InfoDepthf acts as InfoDepth but with format string. 508 | func InfoDepthf(depth int, format string, args ...any) { 509 | logf(depth+1, logsink.Info, false, noStack, format, args...) 510 | } 511 | 512 | // Infoln logs to the INFO log. 513 | // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. 514 | func Infoln(args ...any) { 515 | logf(1, logsink.Info, false, noStack, lnFormat(args), args...) 516 | } 517 | 518 | // Infof logs to the INFO log. 519 | // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. 520 | func Infof(format string, args ...any) { 521 | logf(1, logsink.Info, false, noStack, format, args...) 522 | } 523 | 524 | // InfoContext is like [Info], but with an extra [context.Context] parameter. The 525 | // context is used to pass the Trace Context to log sinks. 526 | func InfoContext(ctx context.Context, args ...any) { 527 | InfoContextDepth(ctx, 1, args...) 528 | } 529 | 530 | // InfoContextf is like [Infof], but with an extra [context.Context] parameter. The 531 | // context is used to pass the Trace Context to log sinks. 532 | func InfoContextf(ctx context.Context, format string, args ...any) { 533 | ctxlogf(ctx, 1, logsink.Info, false, noStack, format, args...) 534 | } 535 | 536 | // InfoContextDepth is like [InfoDepth], but with an extra [context.Context] parameter. The 537 | // context is used to pass the Trace Context to log sinks. 538 | func InfoContextDepth(ctx context.Context, depth int, args ...any) { 539 | ctxlogf(ctx, depth+1, logsink.Info, false, noStack, defaultFormat(args), args...) 540 | } 541 | 542 | // InfoContextDepthf is like [InfoDepthf], but with an extra [context.Context] parameter. The 543 | // context is used to pass the Trace Context to log sinks. 544 | func InfoContextDepthf(ctx context.Context, depth int, format string, args ...any) { 545 | ctxlogf(ctx, depth+1, logsink.Info, false, noStack, format, args...) 546 | } 547 | 548 | // Warning logs to the WARNING and INFO logs. 549 | // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. 550 | func Warning(args ...any) { 551 | WarningDepth(1, args...) 552 | } 553 | 554 | // WarningDepth acts as Warning but uses depth to determine which call frame to log. 555 | // WarningDepth(0, "msg") is the same as Warning("msg"). 556 | func WarningDepth(depth int, args ...any) { 557 | logf(depth+1, logsink.Warning, false, noStack, defaultFormat(args), args...) 558 | } 559 | 560 | // WarningDepthf acts as Warningf but uses depth to determine which call frame to log. 561 | // WarningDepthf(0, "msg") is the same as Warningf("msg"). 562 | func WarningDepthf(depth int, format string, args ...any) { 563 | logf(depth+1, logsink.Warning, false, noStack, format, args...) 564 | } 565 | 566 | // Warningln logs to the WARNING and INFO logs. 567 | // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. 568 | func Warningln(args ...any) { 569 | logf(1, logsink.Warning, false, noStack, lnFormat(args), args...) 570 | } 571 | 572 | // Warningf logs to the WARNING and INFO logs. 573 | // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. 574 | func Warningf(format string, args ...any) { 575 | logf(1, logsink.Warning, false, noStack, format, args...) 576 | } 577 | 578 | // WarningContext is like [Warning], but with an extra [context.Context] parameter. The 579 | // context is used to pass the Trace Context to log sinks. 580 | func WarningContext(ctx context.Context, args ...any) { 581 | WarningContextDepth(ctx, 1, args...) 582 | } 583 | 584 | // WarningContextf is like [Warningf], but with an extra [context.Context] parameter. The 585 | // context is used to pass the Trace Context to log sinks. 586 | func WarningContextf(ctx context.Context, format string, args ...any) { 587 | ctxlogf(ctx, 1, logsink.Warning, false, noStack, format, args...) 588 | } 589 | 590 | // WarningContextDepth is like [WarningDepth], but with an extra [context.Context] parameter. The 591 | // context is used to pass the Trace Context to log sinks. 592 | func WarningContextDepth(ctx context.Context, depth int, args ...any) { 593 | ctxlogf(ctx, depth+1, logsink.Warning, false, noStack, defaultFormat(args), args...) 594 | } 595 | 596 | // WarningContextDepthf is like [WarningDepthf], but with an extra [context.Context] parameter. The 597 | // context is used to pass the Trace Context to log sinks. 598 | func WarningContextDepthf(ctx context.Context, depth int, format string, args ...any) { 599 | ctxlogf(ctx, depth+1, logsink.Warning, false, noStack, format, args...) 600 | } 601 | 602 | // Error logs to the ERROR, WARNING, and INFO logs. 603 | // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. 604 | func Error(args ...any) { 605 | ErrorDepth(1, args...) 606 | } 607 | 608 | // ErrorDepth acts as Error but uses depth to determine which call frame to log. 609 | // ErrorDepth(0, "msg") is the same as Error("msg"). 610 | func ErrorDepth(depth int, args ...any) { 611 | logf(depth+1, logsink.Error, false, noStack, defaultFormat(args), args...) 612 | } 613 | 614 | // ErrorDepthf acts as Errorf but uses depth to determine which call frame to log. 615 | // ErrorDepthf(0, "msg") is the same as Errorf("msg"). 616 | func ErrorDepthf(depth int, format string, args ...any) { 617 | logf(depth+1, logsink.Error, false, noStack, format, args...) 618 | } 619 | 620 | // Errorln logs to the ERROR, WARNING, and INFO logs. 621 | // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. 622 | func Errorln(args ...any) { 623 | logf(1, logsink.Error, false, noStack, lnFormat(args), args...) 624 | } 625 | 626 | // Errorf logs to the ERROR, WARNING, and INFO logs. 627 | // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. 628 | func Errorf(format string, args ...any) { 629 | logf(1, logsink.Error, false, noStack, format, args...) 630 | } 631 | 632 | // ErrorContext is like [Error], but with an extra [context.Context] parameter. The 633 | // context is used to pass the Trace Context to log sinks. 634 | func ErrorContext(ctx context.Context, args ...any) { 635 | ErrorContextDepth(ctx, 1, args...) 636 | } 637 | 638 | // ErrorContextf is like [Errorf], but with an extra [context.Context] parameter. The 639 | // context is used to pass the Trace Context to log sinks. 640 | func ErrorContextf(ctx context.Context, format string, args ...any) { 641 | ctxlogf(ctx, 1, logsink.Error, false, noStack, format, args...) 642 | } 643 | 644 | // ErrorContextDepth is like [ErrorDepth], but with an extra [context.Context] parameter. The 645 | // context is used to pass the Trace Context to log sinks. 646 | func ErrorContextDepth(ctx context.Context, depth int, args ...any) { 647 | ctxlogf(ctx, depth+1, logsink.Error, false, noStack, defaultFormat(args), args...) 648 | } 649 | 650 | // ErrorContextDepthf is like [ErrorDepthf], but with an extra [context.Context] parameter. The 651 | // context is used to pass the Trace Context to log sinks. 652 | func ErrorContextDepthf(ctx context.Context, depth int, format string, args ...any) { 653 | ctxlogf(ctx, depth+1, logsink.Error, false, noStack, format, args...) 654 | } 655 | 656 | func ctxfatalf(ctx context.Context, depth int, format string, args ...any) { 657 | ctxlogf(ctx, depth+1, logsink.Fatal, false, withStack, format, args...) 658 | flushAndAbort() 659 | } 660 | 661 | func flushAndAbort() { 662 | sinks.file.Flush() 663 | 664 | err := abortProcess() // Should not return. 665 | 666 | // Failed to abort the process using signals. Dump a stack trace and exit. 667 | Errorf("abortProcess returned unexpectedly: %v", err) 668 | sinks.file.Flush() 669 | pprof.Lookup("goroutine").WriteTo(os.Stderr, 1) 670 | os.Exit(2) // Exit with the same code as the default SIGABRT handler. 671 | } 672 | 673 | func fatalf(depth int, format string, args ...any) { 674 | ctxfatalf(nil, depth+1, format, args...) 675 | } 676 | 677 | // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, 678 | // including a stack trace of all running goroutines, then calls os.Exit(2). 679 | // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. 680 | func Fatal(args ...any) { 681 | FatalDepth(1, args...) 682 | } 683 | 684 | // FatalDepth acts as Fatal but uses depth to determine which call frame to log. 685 | // FatalDepth(0, "msg") is the same as Fatal("msg"). 686 | func FatalDepth(depth int, args ...any) { 687 | fatalf(depth+1, defaultFormat(args), args...) 688 | } 689 | 690 | // FatalDepthf acts as Fatalf but uses depth to determine which call frame to log. 691 | // FatalDepthf(0, "msg") is the same as Fatalf("msg"). 692 | func FatalDepthf(depth int, format string, args ...any) { 693 | fatalf(depth+1, format, args...) 694 | } 695 | 696 | // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, 697 | // including a stack trace of all running goroutines, then calls os.Exit(2). 698 | // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. 699 | func Fatalln(args ...any) { 700 | fatalf(1, lnFormat(args), args...) 701 | } 702 | 703 | // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, 704 | // including a stack trace of all running goroutines, then calls os.Exit(2). 705 | // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. 706 | func Fatalf(format string, args ...any) { 707 | fatalf(1, format, args...) 708 | } 709 | 710 | // FatalContext is like [Fatal], but with an extra [context.Context] parameter. The 711 | // context is used to pass the Trace Context to log sinks. 712 | func FatalContext(ctx context.Context, args ...any) { 713 | FatalContextDepth(ctx, 1, args...) 714 | } 715 | 716 | // FatalContextf is like [Fatalf], but with an extra [context.Context] parameter. The 717 | // context is used to pass the Trace Context to log sinks. 718 | func FatalContextf(ctx context.Context, format string, args ...any) { 719 | ctxfatalf(ctx, 1, format, args...) 720 | } 721 | 722 | // FatalContextDepth is like [FatalDepth], but with an extra [context.Context] parameter. The 723 | // context is used to pass the Trace Context to log sinks. 724 | func FatalContextDepth(ctx context.Context, depth int, args ...any) { 725 | ctxfatalf(ctx, depth+1, defaultFormat(args), args...) 726 | } 727 | 728 | // FatalContextDepthf is like [FatalDepthf], but with an extra [context.Context] parameter. 729 | func FatalContextDepthf(ctx context.Context, depth int, format string, args ...any) { 730 | ctxfatalf(ctx, depth+1, format, args...) 731 | } 732 | 733 | func ctxexitf(ctx context.Context, depth int, format string, args ...any) { 734 | ctxlogf(ctx, depth+1, logsink.Fatal, false, noStack, format, args...) 735 | sinks.file.Flush() 736 | os.Exit(1) 737 | } 738 | 739 | func exitf(depth int, format string, args ...any) { 740 | ctxexitf(nil, depth+1, format, args...) 741 | } 742 | 743 | // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). 744 | // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. 745 | func Exit(args ...any) { 746 | ExitDepth(1, args...) 747 | } 748 | 749 | // ExitDepth acts as Exit but uses depth to determine which call frame to log. 750 | // ExitDepth(0, "msg") is the same as Exit("msg"). 751 | func ExitDepth(depth int, args ...any) { 752 | exitf(depth+1, defaultFormat(args), args...) 753 | } 754 | 755 | // ExitDepthf acts as Exitf but uses depth to determine which call frame to log. 756 | // ExitDepthf(0, "msg") is the same as Exitf("msg"). 757 | func ExitDepthf(depth int, format string, args ...any) { 758 | exitf(depth+1, format, args...) 759 | } 760 | 761 | // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). 762 | func Exitln(args ...any) { 763 | exitf(1, lnFormat(args), args...) 764 | } 765 | 766 | // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). 767 | // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. 768 | func Exitf(format string, args ...any) { 769 | exitf(1, format, args...) 770 | } 771 | 772 | // ExitContext is like [Exit], but with an extra [context.Context] parameter. The 773 | // context is used to pass the Trace Context to log sinks. 774 | func ExitContext(ctx context.Context, args ...any) { 775 | ExitContextDepth(ctx, 1, args...) 776 | } 777 | 778 | // ExitContextf is like [Exitf], but with an extra [context.Context] parameter. The 779 | // context is used to pass the Trace Context to log sinks. 780 | func ExitContextf(ctx context.Context, format string, args ...any) { 781 | ctxexitf(ctx, 1, format, args...) 782 | } 783 | 784 | // ExitContextDepth is like [ExitDepth], but with an extra [context.Context] parameter. The 785 | // context is used to pass the Trace Context to log sinks. 786 | func ExitContextDepth(ctx context.Context, depth int, args ...any) { 787 | ctxexitf(ctx, depth+1, defaultFormat(args), args...) 788 | } 789 | 790 | // ExitContextDepthf is like [ExitDepthf], but with an extra [context.Context] parameter. The 791 | // context is used to pass the Trace Context to log sinks. 792 | func ExitContextDepthf(ctx context.Context, depth int, format string, args ...any) { 793 | ctxexitf(ctx, depth+1, format, args...) 794 | } 795 | -------------------------------------------------------------------------------- /glog_bench_test.go: -------------------------------------------------------------------------------- 1 | package glog 2 | 3 | import ( 4 | "flag" 5 | "io/ioutil" 6 | "runtime" 7 | "sync" 8 | "sync/atomic" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | // discarder is a flushSyncWriter that discards all data. 14 | // Sync sleeps for 10ms to simulate a disk seek. 15 | type discarder struct { 16 | } 17 | 18 | func (d *discarder) Write(data []byte) (int, error) { 19 | return len(data), nil 20 | } 21 | 22 | func (d *discarder) Flush() error { 23 | return nil 24 | } 25 | 26 | func (d *discarder) Sync() error { 27 | time.Sleep(10 * time.Millisecond) 28 | return nil 29 | } 30 | 31 | func (d *discarder) filenames() []string { 32 | return nil 33 | } 34 | 35 | // newDiscard sets the log writers to all new byte buffers and returns the old array. 36 | func (s *fileSink) newDiscarders() severityWriters { 37 | return s.swap(severityWriters{new(discarder), new(discarder), new(discarder), new(discarder)}) 38 | } 39 | 40 | func discardStderr() func() { 41 | se := sinks.stderr.w 42 | sinks.stderr.w = ioutil.Discard 43 | return func() { sinks.stderr.w = se } 44 | } 45 | 46 | const message = "benchmark log message" 47 | 48 | func benchmarkLog(b *testing.B, log func(...any)) { 49 | defer sinks.file.swap(sinks.file.newDiscarders()) 50 | defer discardStderr()() 51 | b.ResetTimer() 52 | for i := 0; i < b.N; i++ { 53 | log(message) 54 | } 55 | b.StopTimer() 56 | } 57 | 58 | func benchmarkLogConcurrent(b *testing.B, log func(...any)) { 59 | defer sinks.file.swap(sinks.file.newDiscarders()) 60 | defer discardStderr()() 61 | b.ResetTimer() 62 | concurrency := runtime.GOMAXPROCS(0) 63 | var wg sync.WaitGroup 64 | wg.Add(concurrency) 65 | for i := 0; i < concurrency; i++ { 66 | go func() { 67 | for i := 0; i < b.N; i++ { 68 | log(message) 69 | } 70 | wg.Done() 71 | }() 72 | } 73 | wg.Wait() 74 | b.StopTimer() 75 | } 76 | 77 | func BenchmarkInfo(b *testing.B) { 78 | benchmarkLog(b, Info) 79 | } 80 | 81 | func BenchmarkInfoConcurrent(b *testing.B) { 82 | benchmarkLogConcurrent(b, Info) 83 | } 84 | 85 | func BenchmarkWarning(b *testing.B) { 86 | benchmarkLog(b, Warning) 87 | } 88 | 89 | func BenchmarkWarningConcurrent(b *testing.B) { 90 | benchmarkLogConcurrent(b, Warning) 91 | } 92 | 93 | func BenchmarkError(b *testing.B) { 94 | benchmarkLog(b, Error) 95 | } 96 | 97 | func BenchmarkErrorConcurrent(b *testing.B) { 98 | benchmarkLogConcurrent(b, Error) 99 | } 100 | 101 | func mixer() func(...any) { 102 | var i int64 103 | return func(args ...any) { 104 | n := atomic.AddInt64(&i, 1) 105 | switch { 106 | case n%10000 == 0: 107 | Error(args...) 108 | case n%1000 == 0: 109 | Warning(args...) 110 | default: 111 | Info(args...) 112 | } 113 | } 114 | } 115 | 116 | func BenchmarkMix(b *testing.B) { 117 | benchmarkLog(b, mixer()) 118 | } 119 | 120 | func BenchmarkMixConcurrent(b *testing.B) { 121 | benchmarkLogConcurrent(b, mixer()) 122 | } 123 | 124 | func BenchmarkVLogDisabled(b *testing.B) { 125 | benchmarkLog(b, vlog) 126 | } 127 | 128 | func BenchmarkVLogDisabledConcurrent(b *testing.B) { 129 | benchmarkLogConcurrent(b, vlog) 130 | } 131 | 132 | func BenchmarkVLogModuleFlagSet(b *testing.B) { 133 | defer withVmodule("nonexistant=5")() 134 | benchmarkLog(b, vlog) 135 | } 136 | 137 | func BenchmarkVLogModuleFlagSetConcurrent(b *testing.B) { 138 | defer withVmodule("nonexistant=5")() 139 | benchmarkLogConcurrent(b, vlog) 140 | } 141 | 142 | func BenchmarkVLogEnabled(b *testing.B) { 143 | defer withVmodule("glog_bench_test=5")() 144 | if got := bool(V(3)); got != true { 145 | b.Fatalf("V(3) == %v, want %v", got, true) 146 | } 147 | benchmarkLog(b, vlog) 148 | } 149 | 150 | func BenchmarkVLogEnabledConcurrent(b *testing.B) { 151 | defer withVmodule("glog_bench_test=5")() 152 | benchmarkLogConcurrent(b, vlog) 153 | } 154 | 155 | func vlog(args ...any) { 156 | V(3).Info(args) 157 | } 158 | 159 | func withVmodule(val string) func() { 160 | if err := flag.Set("vmodule", val); err != nil { 161 | panic(err) 162 | } 163 | return func() { flag.Set("vmodule", "") } 164 | } 165 | -------------------------------------------------------------------------------- /glog_context_test.go: -------------------------------------------------------------------------------- 1 | package glog 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "testing" 7 | 8 | "github.com/golang/glog/internal/logsink" 9 | ) 10 | 11 | type contextKey string 12 | type fakeLogSink struct { 13 | context context.Context 14 | } 15 | 16 | var ctxKey = contextKey("key") 17 | var ctxValue = "some-value" 18 | var originalSinks = logsink.StructuredSinks 19 | 20 | func (s *fakeLogSink) Printf(meta *logsink.Meta, format string, args ...any) (int, error) { 21 | s.context = meta.Context 22 | return 0, nil 23 | } 24 | 25 | // Test that log.(Info|Error|Warning)Context functions behave the same as non context variants 26 | // and pass right context. 27 | func TestLogContext(t *testing.T) { 28 | fakeLogSink := &fakeLogSink{} 29 | logsink.StructuredSinks = append([]logsink.Structured{fakeLogSink}, originalSinks...) 30 | 31 | funcs := map[string]func(ctx context.Context, args ...any){ 32 | "InfoContext": InfoContext, 33 | "InfoContextDepth": func(ctx context.Context, args ...any) { InfoContextDepth(ctx, 2, args) }, 34 | "ErrorContext": ErrorContext, 35 | "WarningContext": WarningContext, 36 | } 37 | 38 | ctx := context.WithValue(context.Background(), ctxKey, ctxValue) 39 | for name, f := range funcs { 40 | f(ctx, "test") 41 | want := ctxValue 42 | if got := fakeLogSink.context.Value(ctxKey); got != want { 43 | t.Errorf("%s: context value unexpectedly missing: got %q, want %q", name, got, want) 44 | } 45 | } 46 | } 47 | 48 | // Test that V.InfoContext behaves the same as V.Info and passes right context. 49 | func TestVInfoContext(t *testing.T) { 50 | fakeLogSink := &fakeLogSink{} 51 | logsink.StructuredSinks = append([]logsink.Structured{fakeLogSink}, originalSinks...) 52 | if err := flag.Lookup("v").Value.Set("2"); err != nil { 53 | t.Fatalf("Failed to set -v=2: %v", err) 54 | } 55 | defer flag.Lookup("v").Value.Set("0") 56 | ctx := context.WithValue(context.Background(), ctxKey, ctxValue) 57 | V(2).InfoContext(ctx, "test") 58 | want := ctxValue 59 | if got := fakeLogSink.context.Value(ctxKey); got != want { 60 | t.Errorf("V.InfoContext: context value unexpectedly missing: got %q, want %q", got, want) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /glog_file.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // File I/O for logs. 18 | 19 | package glog 20 | 21 | import ( 22 | "bufio" 23 | "bytes" 24 | "errors" 25 | "flag" 26 | "fmt" 27 | "io" 28 | "os" 29 | "path/filepath" 30 | "runtime" 31 | "strings" 32 | "sync" 33 | "time" 34 | 35 | "github.com/golang/glog/internal/logsink" 36 | ) 37 | 38 | // logDirs lists the candidate directories for new log files. 39 | var logDirs []string 40 | 41 | var ( 42 | // If non-empty, overrides the choice of directory in which to write logs. 43 | // See createLogDirs for the full list of possible destinations. 44 | logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") 45 | logLink = flag.String("log_link", "", "If non-empty, add symbolic links in this directory to the log files") 46 | logBufLevel = flag.Int("logbuflevel", int(logsink.Info), "Buffer log messages logged at this level or lower"+ 47 | " (-1 means don't buffer; 0 means buffer INFO only; ...). Has limited applicability on non-prod platforms.") 48 | ) 49 | 50 | func createLogDirs() { 51 | if *logDir != "" { 52 | logDirs = append(logDirs, *logDir) 53 | } 54 | logDirs = append(logDirs, os.TempDir()) 55 | } 56 | 57 | var ( 58 | pid = os.Getpid() 59 | program = filepath.Base(os.Args[0]) 60 | host = "unknownhost" 61 | userName = "unknownuser" 62 | ) 63 | 64 | func init() { 65 | h, err := os.Hostname() 66 | if err == nil { 67 | host = shortHostname(h) 68 | } 69 | 70 | if u := lookupUser(); u != "" { 71 | userName = u 72 | } 73 | // Sanitize userName since it is used to construct file paths. 74 | userName = strings.Map(func(r rune) rune { 75 | switch { 76 | case r >= 'a' && r <= 'z': 77 | case r >= 'A' && r <= 'Z': 78 | case r >= '0' && r <= '9': 79 | default: 80 | return '_' 81 | } 82 | return r 83 | }, userName) 84 | } 85 | 86 | // shortHostname returns its argument, truncating at the first period. 87 | // For instance, given "www.google.com" it returns "www". 88 | func shortHostname(hostname string) string { 89 | if i := strings.Index(hostname, "."); i >= 0 { 90 | return hostname[:i] 91 | } 92 | return hostname 93 | } 94 | 95 | // logName returns a new log file name containing tag, with start time t, and 96 | // the name for the symlink for tag. 97 | func logName(tag string, t time.Time) (name, link string) { 98 | name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", 99 | program, 100 | host, 101 | userName, 102 | tag, 103 | t.Year(), 104 | t.Month(), 105 | t.Day(), 106 | t.Hour(), 107 | t.Minute(), 108 | t.Second(), 109 | pid) 110 | return name, program + "." + tag 111 | } 112 | 113 | var onceLogDirs sync.Once 114 | 115 | // create creates a new log file and returns the file and its filename, which 116 | // contains tag ("INFO", "FATAL", etc.) and t. If the file is created 117 | // successfully, create also attempts to update the symlink for that tag, ignoring 118 | // errors. 119 | func create(tag string, t time.Time, dir string) (f *os.File, filename string, err error) { 120 | if dir != "" { 121 | f, name, err := createInDir(dir, tag, t) 122 | if err == nil { 123 | return f, name, err 124 | } 125 | return nil, "", fmt.Errorf("log: cannot create log: %v", err) 126 | } 127 | 128 | onceLogDirs.Do(createLogDirs) 129 | if len(logDirs) == 0 { 130 | return nil, "", errors.New("log: no log dirs") 131 | } 132 | var lastErr error 133 | for _, dir := range logDirs { 134 | f, name, err := createInDir(dir, tag, t) 135 | if err == nil { 136 | return f, name, err 137 | } 138 | lastErr = err 139 | } 140 | return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) 141 | } 142 | 143 | func createInDir(dir, tag string, t time.Time) (f *os.File, name string, err error) { 144 | name, link := logName(tag, t) 145 | fname := filepath.Join(dir, name) 146 | // O_EXCL is important here, as it prevents a vulnerability. The general idea is that logs often 147 | // live in an insecure directory (like /tmp), so an unprivileged attacker could create fname in 148 | // advance as a symlink to a file the logging process can access, but the attacker cannot. O_EXCL 149 | // fails the open if it already exists, thus prevent our this code from opening the existing file 150 | // the attacker points us to. 151 | f, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) 152 | if err == nil { 153 | symlink := filepath.Join(dir, link) 154 | os.Remove(symlink) // ignore err 155 | os.Symlink(name, symlink) // ignore err 156 | if *logLink != "" { 157 | lsymlink := filepath.Join(*logLink, link) 158 | os.Remove(lsymlink) // ignore err 159 | os.Symlink(fname, lsymlink) // ignore err 160 | } 161 | return f, fname, nil 162 | } 163 | return nil, "", err 164 | } 165 | 166 | // flushSyncWriter is the interface satisfied by logging destinations. 167 | type flushSyncWriter interface { 168 | Flush() error 169 | Sync() error 170 | io.Writer 171 | filenames() []string 172 | } 173 | 174 | var sinks struct { 175 | stderr stderrSink 176 | file fileSink 177 | } 178 | 179 | func init() { 180 | // Register stderr first: that way if we crash during file-writing at least 181 | // the log will have gone somewhere. 182 | if shouldRegisterStderrSink() { 183 | logsink.TextSinks = append(logsink.TextSinks, &sinks.stderr) 184 | } 185 | logsink.TextSinks = append(logsink.TextSinks, &sinks.file) 186 | 187 | sinks.file.flushChan = make(chan logsink.Severity, 1) 188 | go sinks.file.flushDaemon() 189 | } 190 | 191 | // stderrSink is a logsink.Text that writes log entries to stderr 192 | // if they meet certain conditions. 193 | type stderrSink struct { 194 | mu sync.Mutex 195 | w io.Writer // if nil Emit uses os.Stderr directly 196 | } 197 | 198 | // Enabled implements logsink.Text.Enabled. It returns true if any of the 199 | // various stderr flags are enabled for logs of the given severity, if the log 200 | // message is from the standard "log" package, or if google.Init has not yet run 201 | // (and hence file logging is not yet initialized). 202 | func (s *stderrSink) Enabled(m *logsink.Meta) bool { 203 | return toStderr || alsoToStderr || m.Severity >= stderrThreshold.get() 204 | } 205 | 206 | // Emit implements logsink.Text.Emit. 207 | func (s *stderrSink) Emit(m *logsink.Meta, data []byte) (n int, err error) { 208 | s.mu.Lock() 209 | defer s.mu.Unlock() 210 | w := s.w 211 | if w == nil { 212 | w = os.Stderr 213 | } 214 | dn, err := w.Write(data) 215 | n += dn 216 | return n, err 217 | } 218 | 219 | // severityWriters is an array of flushSyncWriter with a value for each 220 | // logsink.Severity. 221 | type severityWriters [4]flushSyncWriter 222 | 223 | // fileSink is a logsink.Text that prints to a set of Google log files. 224 | type fileSink struct { 225 | mu sync.Mutex 226 | // file holds writer for each of the log types. 227 | file severityWriters 228 | flushChan chan logsink.Severity 229 | } 230 | 231 | // Enabled implements logsink.Text.Enabled. It returns true if google.Init 232 | // has run and both --disable_log_to_disk and --logtostderr are false. 233 | func (s *fileSink) Enabled(m *logsink.Meta) bool { 234 | return !toStderr 235 | } 236 | 237 | // Emit implements logsink.Text.Emit 238 | func (s *fileSink) Emit(m *logsink.Meta, data []byte) (n int, err error) { 239 | s.mu.Lock() 240 | defer s.mu.Unlock() 241 | 242 | if err = s.createMissingFiles(m.Severity); err != nil { 243 | return 0, err 244 | } 245 | for sev := m.Severity; sev >= logsink.Info; sev-- { 246 | if _, fErr := s.file[sev].Write(data); fErr != nil && err == nil { 247 | err = fErr // Take the first error. 248 | } 249 | } 250 | n = len(data) 251 | if int(m.Severity) > *logBufLevel { 252 | select { 253 | case s.flushChan <- m.Severity: 254 | default: 255 | } 256 | } 257 | 258 | return n, err 259 | } 260 | 261 | // syncBuffer joins a bufio.Writer to its underlying file, providing access to the 262 | // file's Sync method and providing a wrapper for the Write method that provides log 263 | // file rotation. There are conflicting methods, so the file cannot be embedded. 264 | // s.mu is held for all its methods. 265 | type syncBuffer struct { 266 | sink *fileSink 267 | *bufio.Writer 268 | file *os.File 269 | names []string 270 | sev logsink.Severity 271 | nbytes uint64 // The number of bytes written to this file 272 | madeAt time.Time 273 | } 274 | 275 | func (sb *syncBuffer) Sync() error { 276 | return sb.file.Sync() 277 | } 278 | 279 | func (sb *syncBuffer) Write(p []byte) (n int, err error) { 280 | // Rotate the file if it is too large, but ensure we only do so, 281 | // if rotate doesn't create a conflicting filename. 282 | if sb.nbytes+uint64(len(p)) >= MaxSize { 283 | now := timeNow() 284 | if now.After(sb.madeAt.Add(1*time.Second)) || now.Second() != sb.madeAt.Second() { 285 | if err := sb.rotateFile(now); err != nil { 286 | return 0, err 287 | } 288 | } 289 | } 290 | n, err = sb.Writer.Write(p) 291 | sb.nbytes += uint64(n) 292 | return n, err 293 | } 294 | 295 | func (sb *syncBuffer) filenames() []string { 296 | return sb.names 297 | } 298 | 299 | const footer = "\nCONTINUED IN NEXT FILE\n" 300 | 301 | // rotateFile closes the syncBuffer's file and starts a new one. 302 | func (sb *syncBuffer) rotateFile(now time.Time) error { 303 | var err error 304 | pn := "" 305 | file, name, err := create(sb.sev.String(), now, "") 306 | sb.madeAt = now 307 | 308 | if sb.file != nil { 309 | // The current log file becomes the previous log at the end of 310 | // this block, so save its name for use in the header of the next 311 | // file. 312 | pn = sb.file.Name() 313 | sb.Flush() 314 | // If there's an existing file, write a footer with the name of 315 | // the next file in the chain, followed by the constant string 316 | // \nCONTINUED IN NEXT FILE\n to make continuation detection simple. 317 | sb.file.Write([]byte("Next log: ")) 318 | sb.file.Write([]byte(name)) 319 | sb.file.Write([]byte(footer)) 320 | sb.file.Close() 321 | } 322 | 323 | sb.file = file 324 | sb.names = append(sb.names, name) 325 | sb.nbytes = 0 326 | if err != nil { 327 | return err 328 | } 329 | 330 | sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) 331 | 332 | // Write header. 333 | var buf bytes.Buffer 334 | fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) 335 | fmt.Fprintf(&buf, "Running on machine: %s\n", host) 336 | fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) 337 | fmt.Fprintf(&buf, "Previous log: %s\n", pn) 338 | fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") 339 | n, err := sb.file.Write(buf.Bytes()) 340 | sb.nbytes += uint64(n) 341 | return err 342 | } 343 | 344 | // bufferSize sizes the buffer associated with each log file. It's large 345 | // so that log records can accumulate without the logging thread blocking 346 | // on disk I/O. The flushDaemon will block instead. 347 | const bufferSize = 256 * 1024 348 | 349 | // createMissingFiles creates all the log files for severity from infoLog up to 350 | // upTo that have not already been created. 351 | // s.mu is held. 352 | func (s *fileSink) createMissingFiles(upTo logsink.Severity) error { 353 | if s.file[upTo] != nil { 354 | return nil 355 | } 356 | now := time.Now() 357 | // Files are created in increasing severity order, so we can be assured that 358 | // if a high severity logfile exists, then so do all of lower severity. 359 | for sev := logsink.Info; sev <= upTo; sev++ { 360 | if s.file[sev] != nil { 361 | continue 362 | } 363 | sb := &syncBuffer{ 364 | sink: s, 365 | sev: sev, 366 | } 367 | if err := sb.rotateFile(now); err != nil { 368 | return err 369 | } 370 | s.file[sev] = sb 371 | } 372 | return nil 373 | } 374 | 375 | // flushDaemon periodically flushes the log file buffers. 376 | func (s *fileSink) flushDaemon() { 377 | tick := time.NewTicker(30 * time.Second) 378 | defer tick.Stop() 379 | for { 380 | select { 381 | case <-tick.C: 382 | s.Flush() 383 | case sev := <-s.flushChan: 384 | s.flush(sev) 385 | } 386 | } 387 | } 388 | 389 | // Flush flushes all pending log I/O. 390 | func Flush() { 391 | sinks.file.Flush() 392 | } 393 | 394 | // Flush flushes all the logs and attempts to "sync" their data to disk. 395 | func (s *fileSink) Flush() error { 396 | return s.flush(logsink.Info) 397 | } 398 | 399 | // flush flushes all logs of severity threshold or greater. 400 | func (s *fileSink) flush(threshold logsink.Severity) error { 401 | var firstErr error 402 | updateErr := func(err error) { 403 | if err != nil && firstErr == nil { 404 | firstErr = err 405 | } 406 | } 407 | 408 | // Remember where we flushed, so we can call sync without holding 409 | // the lock. 410 | var files []flushSyncWriter 411 | func() { 412 | s.mu.Lock() 413 | defer s.mu.Unlock() 414 | // Flush from fatal down, in case there's trouble flushing. 415 | for sev := logsink.Fatal; sev >= threshold; sev-- { 416 | if file := s.file[sev]; file != nil { 417 | updateErr(file.Flush()) 418 | files = append(files, file) 419 | } 420 | } 421 | }() 422 | 423 | for _, file := range files { 424 | updateErr(file.Sync()) 425 | } 426 | 427 | return firstErr 428 | } 429 | 430 | // Names returns the names of the log files holding the FATAL, ERROR, 431 | // WARNING, or INFO logs. Returns ErrNoLog if the log for the given 432 | // level doesn't exist (e.g. because no messages of that level have been 433 | // written). This may return multiple names if the log type requested 434 | // has rolled over. 435 | func Names(s string) ([]string, error) { 436 | severity, err := logsink.ParseSeverity(s) 437 | if err != nil { 438 | return nil, err 439 | } 440 | 441 | sinks.file.mu.Lock() 442 | defer sinks.file.mu.Unlock() 443 | f := sinks.file.file[severity] 444 | if f == nil { 445 | return nil, ErrNoLog 446 | } 447 | 448 | return f.filenames(), nil 449 | } 450 | -------------------------------------------------------------------------------- /glog_file_linux.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | //go:build linux 18 | 19 | package glog 20 | 21 | import ( 22 | "errors" 23 | "runtime" 24 | "syscall" 25 | ) 26 | 27 | // abortProcess attempts to kill the current process in a way that will dump the 28 | // currently-running goroutines someplace useful (like stderr). 29 | // 30 | // It does this by sending SIGABRT to the current thread. 31 | // 32 | // If successful, abortProcess does not return. 33 | func abortProcess() error { 34 | runtime.LockOSThread() 35 | if err := syscall.Tgkill(syscall.Getpid(), syscall.Gettid(), syscall.SIGABRT); err != nil { 36 | return err 37 | } 38 | return errors.New("log: killed current thread with SIGABRT, but still running") 39 | } 40 | -------------------------------------------------------------------------------- /glog_file_nonwindows.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | 3 | package glog 4 | 5 | import "os/user" 6 | 7 | // shouldRegisterStderrSink determines whether we should register a log sink that writes to stderr. 8 | // Today, this always returns true on non-Windows platforms, as it specifically checks for a 9 | // condition that is only present on Windows. 10 | func shouldRegisterStderrSink() bool { 11 | return true 12 | } 13 | 14 | func lookupUser() string { 15 | if current, err := user.Current(); err == nil { 16 | return current.Username 17 | } 18 | return "" 19 | } 20 | -------------------------------------------------------------------------------- /glog_file_other.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | //go:build !(unix || windows) 18 | 19 | package glog 20 | 21 | import ( 22 | "fmt" 23 | "runtime" 24 | ) 25 | 26 | // abortProcess returns an error on platforms that presumably don't support signals. 27 | func abortProcess() error { 28 | return fmt.Errorf("not sending SIGABRT (%s/%s does not support signals), falling back", runtime.GOOS, runtime.GOARCH) 29 | 30 | } 31 | -------------------------------------------------------------------------------- /glog_file_posix.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | //go:build (unix || windows) && !linux 18 | 19 | package glog 20 | 21 | import ( 22 | "os" 23 | "syscall" 24 | "time" 25 | ) 26 | 27 | // abortProcess attempts to kill the current process in a way that will dump the 28 | // currently-running goroutines someplace useful (like stderr). 29 | // 30 | // It does this by sending SIGABRT to the current process. Unfortunately, the 31 | // signal may or may not be delivered to the current thread; in order to do that 32 | // portably, we would need to add a cgo dependency and call pthread_kill. 33 | // 34 | // If successful, abortProcess does not return. 35 | func abortProcess() error { 36 | p, err := os.FindProcess(os.Getpid()) 37 | if err != nil { 38 | return err 39 | } 40 | if err := p.Signal(syscall.SIGABRT); err != nil { 41 | return err 42 | } 43 | 44 | // Sent the signal. Now we wait for it to arrive and any SIGABRT handlers to 45 | // run (and eventually terminate the process themselves). 46 | // 47 | // We could just "select{}" here, but there's an outside chance that would 48 | // trigger the runtime's deadlock detector if there happen not to be any 49 | // background goroutines running. So we'll sleep a while first to give 50 | // the signal some time. 51 | time.Sleep(10 * time.Second) 52 | select {} 53 | } 54 | -------------------------------------------------------------------------------- /glog_file_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | 3 | package glog 4 | 5 | import ( 6 | "os" 7 | "syscall" 8 | ) 9 | 10 | // shouldRegisterStderrSink determines whether we should register a log sink that writes to stderr. 11 | // Today, this checks if stderr is "valid", in that it maps to a non-NULL Handle. 12 | // Windows Services are spawned without Stdout and Stderr, so any attempt to use them equates to 13 | // referencing an invalid file Handle. 14 | // os.Stderr's FD is derived from a call to `syscall.GetStdHandle(syscall.STD_ERROR_HANDLE)`. 15 | // Documentation[1] for the GetStdHandle function indicates the return value may be NULL if the 16 | // application lacks the standard handle, so consider Stderr valid if its FD is non-NULL. 17 | // [1]: https://learn.microsoft.com/en-us/windows/console/getstdhandle 18 | func shouldRegisterStderrSink() bool { 19 | return os.Stderr.Fd() != 0 20 | } 21 | 22 | // This follows the logic in the standard library's user.Current() function, except 23 | // that it leaves out the potentially expensive calls required to look up the user's 24 | // display name in Active Directory. 25 | func lookupUser() string { 26 | token, err := syscall.OpenCurrentProcessToken() 27 | if err != nil { 28 | return "" 29 | } 30 | defer token.Close() 31 | tokenUser, err := token.GetTokenUser() 32 | if err != nil { 33 | return "" 34 | } 35 | username, _, accountType, err := tokenUser.User.Sid.LookupAccount("") 36 | if err != nil { 37 | return "" 38 | } 39 | if accountType != syscall.SidTypeUser { 40 | return "" 41 | } 42 | return username 43 | } 44 | -------------------------------------------------------------------------------- /glog_flags.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://github.com/google/glog. 2 | // 3 | // Copyright 2023 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | package glog 18 | 19 | import ( 20 | "bytes" 21 | "errors" 22 | "flag" 23 | "fmt" 24 | "path/filepath" 25 | "runtime" 26 | "strconv" 27 | "strings" 28 | "sync" 29 | "sync/atomic" 30 | 31 | "github.com/golang/glog/internal/logsink" 32 | ) 33 | 34 | // modulePat contains a filter for the -vmodule flag. 35 | // It holds a verbosity level and a file pattern to match. 36 | type modulePat struct { 37 | pattern string 38 | literal bool // The pattern is a literal string 39 | full bool // The pattern wants to match the full path 40 | level Level 41 | } 42 | 43 | // match reports whether the file matches the pattern. It uses a string 44 | // comparison if the pattern contains no metacharacters. 45 | func (m *modulePat) match(full, file string) bool { 46 | if m.literal { 47 | if m.full { 48 | return full == m.pattern 49 | } 50 | return file == m.pattern 51 | } 52 | if m.full { 53 | match, _ := filepath.Match(m.pattern, full) 54 | return match 55 | } 56 | match, _ := filepath.Match(m.pattern, file) 57 | return match 58 | } 59 | 60 | // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters 61 | // that require filepath.Match to be called to match the pattern. 62 | func isLiteral(pattern string) bool { 63 | return !strings.ContainsAny(pattern, `\*?[]`) 64 | } 65 | 66 | // isFull reports whether the pattern matches the full file path, that is, 67 | // whether it contains /. 68 | func isFull(pattern string) bool { 69 | return strings.ContainsRune(pattern, '/') 70 | } 71 | 72 | // verboseFlags represents the setting of the -v and -vmodule flags. 73 | type verboseFlags struct { 74 | // moduleLevelCache is a sync.Map storing the -vmodule Level for each V() 75 | // call site, identified by PC. If there is no matching -vmodule filter, 76 | // the cached value is exactly v. moduleLevelCache is replaced with a new 77 | // Map whenever the -vmodule or -v flag changes state. 78 | moduleLevelCache atomic.Value 79 | 80 | // mu guards all fields below. 81 | mu sync.Mutex 82 | 83 | // v stores the value of the -v flag. It may be read safely using 84 | // sync.LoadInt32, but is only modified under mu. 85 | v Level 86 | 87 | // module stores the parsed -vmodule flag. 88 | module []modulePat 89 | 90 | // moduleLength caches len(module). If greater than zero, it 91 | // means vmodule is enabled. It may be read safely using sync.LoadInt32, but 92 | // is only modified under mu. 93 | moduleLength int32 94 | } 95 | 96 | // NOTE: For compatibility with the open-sourced v1 version of this 97 | // package (github.com/golang/glog) we need to retain that flag.Level 98 | // implements the flag.Value interface. See also go/log-vs-glog. 99 | 100 | // String is part of the flag.Value interface. 101 | func (l *Level) String() string { 102 | return strconv.FormatInt(int64(l.Get().(Level)), 10) 103 | } 104 | 105 | // Get is part of the flag.Value interface. 106 | func (l *Level) Get() any { 107 | if l == &vflags.v { 108 | // l is the value registered for the -v flag. 109 | return Level(atomic.LoadInt32((*int32)(l))) 110 | } 111 | return *l 112 | } 113 | 114 | // Set is part of the flag.Value interface. 115 | func (l *Level) Set(value string) error { 116 | v, err := strconv.Atoi(value) 117 | if err != nil { 118 | return err 119 | } 120 | if l == &vflags.v { 121 | // l is the value registered for the -v flag. 122 | vflags.mu.Lock() 123 | defer vflags.mu.Unlock() 124 | vflags.moduleLevelCache.Store(&sync.Map{}) 125 | atomic.StoreInt32((*int32)(l), int32(v)) 126 | return nil 127 | } 128 | *l = Level(v) 129 | return nil 130 | } 131 | 132 | // vModuleFlag is the flag.Value for the --vmodule flag. 133 | type vModuleFlag struct{ *verboseFlags } 134 | 135 | func (f vModuleFlag) String() string { 136 | // Do not panic on the zero value. 137 | // https://groups.google.com/g/golang-nuts/c/Atlr8uAjn6U/m/iId17Td5BQAJ. 138 | if f.verboseFlags == nil { 139 | return "" 140 | } 141 | f.mu.Lock() 142 | defer f.mu.Unlock() 143 | 144 | var b bytes.Buffer 145 | for i, f := range f.module { 146 | if i > 0 { 147 | b.WriteRune(',') 148 | } 149 | fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) 150 | } 151 | return b.String() 152 | } 153 | 154 | // Get returns nil for this flag type since the struct is not exported. 155 | func (f vModuleFlag) Get() any { return nil } 156 | 157 | var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") 158 | 159 | // Syntax: -vmodule=recordio=2,foo/bar/baz=1,gfs*=3 160 | func (f vModuleFlag) Set(value string) error { 161 | var filter []modulePat 162 | for _, pat := range strings.Split(value, ",") { 163 | if len(pat) == 0 { 164 | // Empty strings such as from a trailing comma can be ignored. 165 | continue 166 | } 167 | patLev := strings.Split(pat, "=") 168 | if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { 169 | return errVmoduleSyntax 170 | } 171 | pattern := patLev[0] 172 | v, err := strconv.Atoi(patLev[1]) 173 | if err != nil { 174 | return errors.New("syntax error: expect comma-separated list of filename=N") 175 | } 176 | // TODO: check syntax of filter? 177 | filter = append(filter, modulePat{pattern, isLiteral(pattern), isFull(pattern), Level(v)}) 178 | } 179 | 180 | f.mu.Lock() 181 | defer f.mu.Unlock() 182 | f.module = filter 183 | atomic.StoreInt32((*int32)(&f.moduleLength), int32(len(f.module))) 184 | f.moduleLevelCache.Store(&sync.Map{}) 185 | return nil 186 | } 187 | 188 | func (f *verboseFlags) levelForPC(pc uintptr) Level { 189 | if level, ok := f.moduleLevelCache.Load().(*sync.Map).Load(pc); ok { 190 | return level.(Level) 191 | } 192 | 193 | f.mu.Lock() 194 | defer f.mu.Unlock() 195 | level := Level(f.v) 196 | fn := runtime.FuncForPC(pc) 197 | file, _ := fn.FileLine(pc) 198 | // The file is something like /a/b/c/d.go. We want just the d for 199 | // regular matches, /a/b/c/d for full matches. 200 | file = strings.TrimSuffix(file, ".go") 201 | full := file 202 | if slash := strings.LastIndex(file, "/"); slash >= 0 { 203 | file = file[slash+1:] 204 | } 205 | for _, filter := range f.module { 206 | if filter.match(full, file) { 207 | level = filter.level 208 | break // Use the first matching level. 209 | } 210 | } 211 | f.moduleLevelCache.Load().(*sync.Map).Store(pc, level) 212 | return level 213 | } 214 | 215 | func (f *verboseFlags) enabled(callerDepth int, level Level) bool { 216 | if atomic.LoadInt32(&f.moduleLength) == 0 { 217 | // No vmodule values specified, so compare against v level. 218 | return Level(atomic.LoadInt32((*int32)(&f.v))) >= level 219 | } 220 | 221 | pcs := [1]uintptr{} 222 | if runtime.Callers(callerDepth+2, pcs[:]) < 1 { 223 | return false 224 | } 225 | frame, _ := runtime.CallersFrames(pcs[:]).Next() 226 | return f.levelForPC(frame.Entry) >= level 227 | } 228 | 229 | // traceLocation represents an entry in the -log_backtrace_at flag. 230 | type traceLocation struct { 231 | file string 232 | line int 233 | } 234 | 235 | var errTraceSyntax = errors.New("syntax error: expect file.go:234") 236 | 237 | func parseTraceLocation(value string) (traceLocation, error) { 238 | fields := strings.Split(value, ":") 239 | if len(fields) != 2 { 240 | return traceLocation{}, errTraceSyntax 241 | } 242 | file, lineStr := fields[0], fields[1] 243 | if !strings.Contains(file, ".") { 244 | return traceLocation{}, errTraceSyntax 245 | } 246 | line, err := strconv.Atoi(lineStr) 247 | if err != nil { 248 | return traceLocation{}, errTraceSyntax 249 | } 250 | if line < 0 { 251 | return traceLocation{}, errors.New("negative value for line") 252 | } 253 | return traceLocation{file, line}, nil 254 | } 255 | 256 | // match reports whether the specified file and line matches the trace location. 257 | // The argument file name is the full path, not the basename specified in the flag. 258 | func (t traceLocation) match(file string, line int) bool { 259 | if t.line != line { 260 | return false 261 | } 262 | if i := strings.LastIndex(file, "/"); i >= 0 { 263 | file = file[i+1:] 264 | } 265 | return t.file == file 266 | } 267 | 268 | func (t traceLocation) String() string { 269 | return fmt.Sprintf("%s:%d", t.file, t.line) 270 | } 271 | 272 | // traceLocations represents the -log_backtrace_at flag. 273 | // Syntax: -log_backtrace_at=recordio.go:234,sstable.go:456 274 | // Note that unlike vmodule the file extension is included here. 275 | type traceLocations struct { 276 | mu sync.Mutex 277 | locsLen int32 // Safe for atomic read without mu. 278 | locs []traceLocation 279 | } 280 | 281 | func (t *traceLocations) String() string { 282 | t.mu.Lock() 283 | defer t.mu.Unlock() 284 | 285 | var buf bytes.Buffer 286 | for i, tl := range t.locs { 287 | if i > 0 { 288 | buf.WriteString(",") 289 | } 290 | buf.WriteString(tl.String()) 291 | } 292 | return buf.String() 293 | } 294 | 295 | // Get always returns nil for this flag type since the struct is not exported 296 | func (t *traceLocations) Get() any { return nil } 297 | 298 | func (t *traceLocations) Set(value string) error { 299 | var locs []traceLocation 300 | for _, s := range strings.Split(value, ",") { 301 | if s == "" { 302 | continue 303 | } 304 | loc, err := parseTraceLocation(s) 305 | if err != nil { 306 | return err 307 | } 308 | locs = append(locs, loc) 309 | } 310 | 311 | t.mu.Lock() 312 | defer t.mu.Unlock() 313 | atomic.StoreInt32(&t.locsLen, int32(len(locs))) 314 | t.locs = locs 315 | return nil 316 | } 317 | 318 | func (t *traceLocations) match(file string, line int) bool { 319 | if atomic.LoadInt32(&t.locsLen) == 0 { 320 | return false 321 | } 322 | 323 | t.mu.Lock() 324 | defer t.mu.Unlock() 325 | for _, tl := range t.locs { 326 | if tl.match(file, line) { 327 | return true 328 | } 329 | } 330 | return false 331 | } 332 | 333 | // severityFlag is an atomic flag.Value implementation for logsink.Severity. 334 | type severityFlag int32 335 | 336 | func (s *severityFlag) get() logsink.Severity { 337 | return logsink.Severity(atomic.LoadInt32((*int32)(s))) 338 | } 339 | func (s *severityFlag) String() string { return strconv.FormatInt(int64(*s), 10) } 340 | func (s *severityFlag) Get() any { return s.get() } 341 | func (s *severityFlag) Set(value string) error { 342 | threshold, err := logsink.ParseSeverity(value) 343 | if err != nil { 344 | // Not a severity name. Try a raw number. 345 | v, err := strconv.Atoi(value) 346 | if err != nil { 347 | return err 348 | } 349 | threshold = logsink.Severity(v) 350 | if threshold < logsink.Info || threshold > logsink.Fatal { 351 | return fmt.Errorf("Severity %d out of range (min %d, max %d).", v, logsink.Info, logsink.Fatal) 352 | } 353 | } 354 | atomic.StoreInt32((*int32)(s), int32(threshold)) 355 | return nil 356 | } 357 | 358 | var ( 359 | vflags verboseFlags // The -v and -vmodule flags. 360 | 361 | logBacktraceAt traceLocations // The -log_backtrace_at flag. 362 | 363 | // Boolean flags. Not handled atomically because the flag.Value interface 364 | // does not let us avoid the =true, and that shorthand is necessary for 365 | // compatibility. TODO: does this matter enough to fix? Seems unlikely. 366 | toStderr bool // The -logtostderr flag. 367 | alsoToStderr bool // The -alsologtostderr flag. 368 | 369 | stderrThreshold severityFlag // The -stderrthreshold flag. 370 | ) 371 | 372 | // verboseEnabled returns whether the caller at the given depth should emit 373 | // verbose logs at the given level, with depth 0 identifying the caller of 374 | // verboseEnabled. 375 | func verboseEnabled(callerDepth int, level Level) bool { 376 | return vflags.enabled(callerDepth+1, level) 377 | } 378 | 379 | // backtraceAt returns whether the logging call at the given function and line 380 | // should also emit a backtrace of the current call stack. 381 | func backtraceAt(file string, line int) bool { 382 | return logBacktraceAt.match(file, line) 383 | } 384 | 385 | func init() { 386 | vflags.moduleLevelCache.Store(&sync.Map{}) 387 | 388 | flag.Var(&vflags.v, "v", "log level for V logs") 389 | flag.Var(vModuleFlag{&vflags}, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") 390 | 391 | flag.Var(&logBacktraceAt, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") 392 | 393 | stderrThreshold = severityFlag(logsink.Error) 394 | 395 | flag.BoolVar(&toStderr, "logtostderr", false, "log to standard error instead of files") 396 | flag.BoolVar(&alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") 397 | flag.Var(&stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") 398 | } 399 | -------------------------------------------------------------------------------- /glog_test.go: -------------------------------------------------------------------------------- 1 | package glog 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "flag" 7 | "fmt" 8 | "io/ioutil" 9 | stdLog "log" 10 | "path/filepath" 11 | "runtime" 12 | "strconv" 13 | "strings" 14 | "testing" 15 | "time" 16 | 17 | "github.com/golang/glog/internal/logsink" 18 | ) 19 | 20 | // Test that shortHostname works as advertised. 21 | func TestShortHostname(t *testing.T) { 22 | for hostname, expect := range map[string]string{ 23 | "": "", 24 | "host": "host", 25 | "host.google.com": "host", 26 | "host.corp.google.com": "host", 27 | } { 28 | if got := shortHostname(hostname); expect != got { 29 | t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) 30 | } 31 | } 32 | } 33 | 34 | // flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. 35 | type flushBuffer struct { 36 | bytes.Buffer 37 | } 38 | 39 | func (f *flushBuffer) Flush() error { 40 | f.Buffer.Reset() 41 | return nil 42 | } 43 | 44 | func (f *flushBuffer) Sync() error { 45 | return nil 46 | } 47 | 48 | func (f *flushBuffer) filenames() []string { 49 | return []string{""} 50 | } 51 | 52 | // swap sets the log writers and returns the old array. 53 | func (s *fileSink) swap(writers severityWriters) (old severityWriters) { 54 | s.mu.Lock() 55 | defer s.mu.Unlock() 56 | old = s.file 57 | for i, w := range writers { 58 | s.file[i] = w 59 | } 60 | return 61 | } 62 | 63 | // newBuffers sets the log writers to all new byte buffers and returns the old array. 64 | func (s *fileSink) newBuffers() severityWriters { 65 | return s.swap(severityWriters{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) 66 | } 67 | 68 | func (s *fileSink) resetBuffers() { 69 | s.mu.Lock() 70 | defer s.mu.Unlock() 71 | for _, buf := range s.file { 72 | if buf != nil { 73 | buf.Flush() 74 | } 75 | } 76 | } 77 | 78 | // contents returns the specified log value as a string. 79 | func contents(s logsink.Severity) string { 80 | return sinks.file.file[s].(*flushBuffer).String() 81 | } 82 | 83 | // contains reports whether the string is contained in the log. 84 | func contains(s logsink.Severity, str string, t *testing.T) bool { 85 | return strings.Contains(contents(s), str) 86 | } 87 | 88 | // setFlags configures the logging flags how the test expects them. 89 | func setFlags() { 90 | toStderr = false 91 | } 92 | 93 | // Test that Info works as advertised. 94 | func TestInfo(t *testing.T) { 95 | setFlags() 96 | defer sinks.file.swap(sinks.file.newBuffers()) 97 | funcs := []func(args ...any){ 98 | Info, 99 | func(args ...any) { InfoContext(context.Background(), args) }, 100 | } 101 | 102 | for _, f := range funcs { 103 | sinks.file.resetBuffers() 104 | f("test") 105 | if !contains(logsink.Info, "I", t) { 106 | t.Errorf("Info has wrong character: %q", contents(logsink.Info)) 107 | } 108 | if !contains(logsink.Info, "test", t) { 109 | t.Error("Info failed") 110 | } 111 | } 112 | } 113 | 114 | func TestInfoDepth(t *testing.T) { 115 | setFlags() 116 | defer sinks.file.swap(sinks.file.newBuffers()) 117 | 118 | funcs := []func(d int, args ...any){ 119 | InfoDepth, 120 | func(d int, args ...any) { InfoContextDepth(context.Background(), d+1, args) }, 121 | } 122 | 123 | for _, infoDepth := range funcs { 124 | sinks.file.resetBuffers() 125 | f := func() { infoDepth(1, "depth-test1") } 126 | 127 | // The next three lines must stay together 128 | _, _, wantLine, _ := runtime.Caller(0) 129 | infoDepth(0, "depth-test0") 130 | f() 131 | 132 | msgs := strings.Split(strings.TrimSuffix(contents(logsink.Info), "\n"), "\n") 133 | if len(msgs) != 2 { 134 | t.Fatalf("Got %d lines, expected 2", len(msgs)) 135 | } 136 | 137 | for i, m := range msgs { 138 | if !strings.HasPrefix(m, "I") { 139 | t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) 140 | } 141 | w := fmt.Sprintf("depth-test%d", i) 142 | if !strings.Contains(m, w) { 143 | t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) 144 | } 145 | 146 | // pull out the line number (between : and ]) 147 | msg := m[strings.LastIndex(m, ":")+1:] 148 | x := strings.Index(msg, "]") 149 | if x < 0 { 150 | t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) 151 | continue 152 | } 153 | line, err := strconv.Atoi(msg[:x]) 154 | if err != nil { 155 | t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) 156 | continue 157 | } 158 | wantLine++ 159 | if wantLine != line { 160 | t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) 161 | } 162 | } 163 | } 164 | } 165 | 166 | func init() { 167 | CopyStandardLogTo("INFO") 168 | } 169 | 170 | // Test that CopyStandardLogTo panics on bad input. 171 | func TestCopyStandardLogToPanic(t *testing.T) { 172 | defer func() { 173 | if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { 174 | t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) 175 | } 176 | }() 177 | CopyStandardLogTo("LOG") 178 | } 179 | 180 | // Test that using the standard log package logs to INFO. 181 | func TestStandardLog(t *testing.T) { 182 | setFlags() 183 | defer sinks.file.swap(sinks.file.newBuffers()) 184 | stdLog.Print("test") 185 | if !contains(logsink.Info, "I", t) { 186 | t.Errorf("Info has wrong character: %q", contents(logsink.Info)) 187 | } 188 | if !contains(logsink.Info, "test", t) { 189 | t.Error("Info failed") 190 | } 191 | } 192 | 193 | // Test that the header has the correct format. 194 | func TestHeader(t *testing.T) { 195 | setFlags() 196 | defer func(previous func() time.Time) { timeNow = previous }(timeNow) 197 | timeNow = func() time.Time { 198 | return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) 199 | } 200 | 201 | oldPID := pid 202 | defer func() { pid = oldPID }() 203 | pid = 1234 204 | 205 | defer sinks.file.swap(sinks.file.newBuffers()) 206 | 207 | Info("testHeader") 208 | var line int 209 | format := "I0102 15:04:05.067890 %7d glog_test.go:%d] testHeader\n" 210 | var gotPID int64 211 | n, err := fmt.Sscanf(contents(logsink.Info), format, &gotPID, &line) 212 | if n != 2 || err != nil { 213 | t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(logsink.Info)) 214 | } 215 | 216 | if want := int64(pid); gotPID != want { 217 | t.Errorf("expected log line to be logged with process ID %d, got %d", want, gotPID) 218 | } 219 | 220 | // Scanf treats multiple spaces as equivalent to a single space, 221 | // so check for correct space-padding also. 222 | want := fmt.Sprintf(format, gotPID, line) 223 | if contents(logsink.Info) != want { 224 | t.Errorf("log format error: got:\n\t%q\nwant:\n\t%q", contents(logsink.Info), want) 225 | } 226 | 227 | } 228 | 229 | // Test that an Error log goes to Warning and Info. 230 | // Even in the Info log, the source character will be E, so the data should 231 | // all be identical. 232 | func TestError(t *testing.T) { 233 | setFlags() 234 | defer sinks.file.swap(sinks.file.newBuffers()) 235 | 236 | funcs := []func(args ...any){ 237 | Error, 238 | func(args ...any) { ErrorContext(context.Background(), args) }, 239 | } 240 | 241 | for _, error := range funcs { 242 | sinks.file.resetBuffers() 243 | error("test") 244 | if !contains(logsink.Error, "E", t) { 245 | t.Errorf("Error has wrong character: %q", contents(logsink.Error)) 246 | } 247 | if !contains(logsink.Error, "test", t) { 248 | t.Error("Error failed") 249 | } 250 | str := contents(logsink.Error) 251 | if !contains(logsink.Warning, str, t) { 252 | t.Error("Warning failed") 253 | } 254 | if !contains(logsink.Info, str, t) { 255 | t.Error("Info failed") 256 | } 257 | } 258 | } 259 | 260 | // Test that a Warning log goes to Info. 261 | // Even in the Info log, the source character will be W, so the data should 262 | // all be identical. 263 | func TestWarning(t *testing.T) { 264 | setFlags() 265 | defer sinks.file.swap(sinks.file.newBuffers()) 266 | 267 | funcs := []func(args ...any){ 268 | Warning, 269 | func(args ...any) { WarningContext(context.Background(), args) }, 270 | } 271 | 272 | for _, warning := range funcs { 273 | sinks.file.resetBuffers() 274 | warning("test") 275 | if !contains(logsink.Warning, "W", t) { 276 | t.Errorf("Warning has wrong character: %q", contents(logsink.Warning)) 277 | } 278 | if !contains(logsink.Warning, "test", t) { 279 | t.Error("Warning failed") 280 | } 281 | str := contents(logsink.Warning) 282 | if !contains(logsink.Info, str, t) { 283 | t.Error("Info failed") 284 | } 285 | } 286 | } 287 | 288 | // Test that a V log goes to Info. 289 | func TestV(t *testing.T) { 290 | setFlags() 291 | defer sinks.file.swap(sinks.file.newBuffers()) 292 | if err := flag.Lookup("v").Value.Set("2"); err != nil { 293 | t.Fatalf("Failed to set -v=2: %v", err) 294 | } 295 | defer flag.Lookup("v").Value.Set("0") 296 | 297 | funcs := []func(args ...any){ 298 | V(2).Info, 299 | func(args ...any) { V(2).InfoContext(context.Background(), args) }, 300 | } 301 | for _, info := range funcs { 302 | sinks.file.resetBuffers() 303 | info("test") 304 | if !contains(logsink.Info, "I", t) { 305 | t.Errorf("Info has wrong character: %q", contents(logsink.Info)) 306 | } 307 | if !contains(logsink.Info, "test", t) { 308 | t.Error("Info failed") 309 | } 310 | } 311 | } 312 | 313 | // Test that updating -v at runtime, while -vmodule is set to a non-empty 314 | // value, resets the modules cache correctly. 315 | func TestVFlagUpdates(t *testing.T) { 316 | setFlags() 317 | defer sinks.file.swap(sinks.file.newBuffers()) 318 | // Set -vmodule to some arbitrary value to make values read from cache. 319 | // See log_flags.go:/func .* enabled/. 320 | if err := flag.Lookup("vmodule").Value.Set("non_existent_module=3"); err != nil { 321 | t.Fatalf("Failed to set -vmodule=log_test=3: %v", err) 322 | } 323 | defer flag.Lookup("vmodule").Value.Set("") 324 | if err := flag.Lookup("v").Value.Set("3"); err != nil { 325 | t.Fatalf("Failed to set -v=3: %v", err) 326 | } 327 | defer flag.Lookup("v").Value.Set("0") 328 | 329 | if !V(2) { 330 | t.Error("V(2) not enabled for 2") 331 | } 332 | if !V(3) { 333 | t.Error("V(3) not enabled for 3") 334 | } 335 | 336 | // Setting a lower level should reset the modules cache. 337 | if err := flag.Lookup("v").Value.Set("2"); err != nil { 338 | t.Fatalf("Failed to set -v=2: %v", err) 339 | } 340 | if !V(2) { 341 | t.Error("V(2) not enabled for 2") 342 | } 343 | if V(3) { 344 | t.Error("V(3) enabled for 3") 345 | } 346 | } 347 | 348 | // Test that an arbitrary log.Level value does not modify -v. 349 | func TestLevel(t *testing.T) { 350 | setFlags() 351 | defer sinks.file.swap(sinks.file.newBuffers()) 352 | if err := flag.Lookup("v").Value.Set("3"); err != nil { 353 | t.Fatalf("Failed to set -v=3: %v", err) 354 | } 355 | defer flag.Lookup("v").Value.Set("0") 356 | 357 | var l Level 358 | if got, want := l.String(), "0"; got != want { 359 | t.Errorf("l.String() = %q, want %q", got, want) 360 | } 361 | if err := l.Set("2"); err != nil { 362 | t.Fatalf("l.Set(2) failed: %v", err) 363 | } 364 | if got, want := l.String(), "2"; got != want { 365 | t.Errorf("l.String() = %q, want %q", got, want) 366 | } 367 | // -v flag should still be "3". 368 | if got, want := flag.Lookup("v").Value.String(), "3"; got != want { 369 | t.Errorf("-v=%v, want %v", got, want) 370 | } 371 | } 372 | 373 | // Test that a vmodule enables a log in this file. 374 | func TestVmoduleOn(t *testing.T) { 375 | setFlags() 376 | defer sinks.file.swap(sinks.file.newBuffers()) 377 | if err := flag.Lookup("vmodule").Value.Set("glog_test=2"); err != nil { 378 | t.Fatalf("Failed to set -vmodule=log_test=2: %v", err) 379 | } 380 | defer flag.Lookup("vmodule").Value.Set("") 381 | 382 | if !V(1) { 383 | t.Error("V not enabled for 1") 384 | } 385 | if !V(2) { 386 | t.Error("V not enabled for 2") 387 | } 388 | if V(3) { 389 | t.Error("V enabled for 3") 390 | } 391 | V(2).Info("test") 392 | if !contains(logsink.Info, "I", t) { 393 | t.Errorf("Info has wrong character: %q", contents(logsink.Info)) 394 | } 395 | if !contains(logsink.Info, "test", t) { 396 | t.Error("Info failed") 397 | } 398 | } 399 | 400 | // Test that a VDepth calculates the depth correctly. 401 | func TestVDepth(t *testing.T) { 402 | setFlags() 403 | defer sinks.file.swap(sinks.file.newBuffers()) 404 | if err := flag.Lookup("vmodule").Value.Set("glog_test=3"); err != nil { 405 | t.Fatalf("Failed to set -vmodule=glog_test=3: %v", err) 406 | } 407 | defer flag.Lookup("vmodule").Value.Set("") 408 | 409 | if !V(3) { 410 | t.Error("V not enabled for 3") 411 | } 412 | if !VDepth(0, 2) { 413 | t.Error("VDepth(0) not enabled for 2") 414 | } 415 | if !VDepth(0, 3) { 416 | t.Error("VDepth(0) not enabled for 3") 417 | } 418 | if VDepth(0, 4) { 419 | t.Error("VDepth(0) enabled for 4") 420 | } 421 | 422 | // Since vmodule is set to glog_test=3, V(3) is true only for frames in 423 | // glog_test. runInAnotherModule's stack frame is in log_vmodule_test, whereas 424 | // this test and the provided closures are in glog_test. Therefore VDepth(0, 3) 425 | // and VDepth(2, 3) are true, while VDepth(1, 3) is false. 426 | if !runInAnotherModule(func() bool { return bool(VDepth(0, 3)) }) { 427 | t.Error("VDepth(0) in closure not enabled for 3") 428 | } 429 | if runInAnotherModule(func() bool { return bool(VDepth(1, 3)) }) { 430 | t.Error("VDepth(1) in closure enabled for 3") 431 | } 432 | if !runInAnotherModule(func() bool { return bool(VDepth(2, 3)) }) { 433 | t.Error("VDepth(2) in closure not enabled for 3") 434 | } 435 | } 436 | 437 | // Test that a vmodule of another file does not enable a log in this file. 438 | func TestVmoduleOff(t *testing.T) { 439 | setFlags() 440 | defer sinks.file.swap(sinks.file.newBuffers()) 441 | if err := flag.Lookup("vmodule").Value.Set("notthisfile=2"); err != nil { 442 | t.Fatalf("Failed to set -vmodule=notthisfile=2: %v", err) 443 | } 444 | defer flag.Lookup("vmodule").Value.Set("") 445 | 446 | for i := 1; i <= 3; i++ { 447 | if V(Level(i)) { 448 | t.Errorf("V enabled for %d", i) 449 | } 450 | } 451 | V(2).Info("test") 452 | if contents(logsink.Info) != "" { 453 | t.Error("V logged incorrectly") 454 | } 455 | } 456 | 457 | // vGlobs are patterns that match/don't match this file at V=2. 458 | var vGlobs = map[string]bool{ 459 | // Easy to test the numeric match here. 460 | "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. 461 | "glog_test=2": true, 462 | "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. 463 | // These all use 2 and check the patterns. All are true. 464 | "*=2": true, 465 | "?l*=2": true, 466 | "????_*=2": true, 467 | "??[mno]?_*t=2": true, 468 | // These all use 2 and check the patterns. All are false. 469 | "*x=2": false, 470 | "m*=2": false, 471 | "??_*=2": false, 472 | "?[abc]?_*t=2": false, 473 | } 474 | 475 | // Test that vmodule globbing works as advertised. 476 | func testVmoduleGlob(pat string, match bool, t *testing.T) { 477 | t.Helper() 478 | setFlags() 479 | defer sinks.file.swap(sinks.file.newBuffers()) 480 | if err := flag.Lookup("vmodule").Value.Set(pat); err != nil { 481 | t.Errorf("Failed to set -vmodule=%s: %v", pat, err) 482 | } 483 | defer flag.Lookup("vmodule").Value.Set("") 484 | 485 | if V(2) != Verbose(match) { 486 | t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) 487 | } 488 | } 489 | 490 | // Test that a vmodule globbing works as advertised. 491 | func TestVmoduleGlob(t *testing.T) { 492 | for glob, match := range vGlobs { 493 | testVmoduleGlob(glob, match, t) 494 | } 495 | } 496 | 497 | // Test that a vmodule globbing on a full path works as advertised. 498 | func TestVmoduleFullGlob(t *testing.T) { 499 | _, file, _, _ := runtime.Caller(0) 500 | for glob, match := range vGlobs { 501 | testVmoduleGlob(filepath.Join(filepath.Dir(file), glob), match, t) 502 | } 503 | } 504 | 505 | // Test that a vmodule globbing across multiple directories works as advertised. 506 | func TestVmoduleFullGlobMultipleDirectories(t *testing.T) { 507 | // Note: only covering here what 508 | // TestVmoduleGlob does not. 509 | _, file, _, _ := runtime.Caller(0) 510 | dir := filepath.Dir(filepath.Dir(file)) 511 | testVmoduleGlob(filepath.Join(dir, "*/glog_test=2"), true, t) 512 | testVmoduleGlob(filepath.Join(dir, "*/glog_????=2"), true, t) 513 | } 514 | 515 | func logAtVariousLevels() { 516 | V(3).Infof("level 3 message") 517 | V(2).Infof("level 2 message") 518 | V(1).Infof("level 1 message") 519 | Infof("default level message") 520 | } 521 | 522 | func TestRollover(t *testing.T) { 523 | setFlags() 524 | defer func(previous func() time.Time) { timeNow = previous }(timeNow) 525 | 526 | // Initialize a fake clock that can be advanced with the tick func. 527 | fakeNow := time.Date(2024, 12, 23, 1, 23, 45, 0, time.Local) 528 | timeNow = func() time.Time { 529 | return fakeNow 530 | } 531 | 532 | tick := func(d time.Duration) { 533 | fakeNow = fakeNow.Add(d) 534 | } 535 | 536 | Info("x") // Be sure we have a file. 537 | info, ok := sinks.file.file[logsink.Info].(*syncBuffer) 538 | if !ok { 539 | t.Fatal("info wasn't created") 540 | } 541 | 542 | // Measure the current size of the log file. 543 | info.Flush() 544 | fi, err := info.file.Stat() 545 | if err != nil { 546 | t.Fatalf("Unable to stat log file %s: %v", info.file.Name(), err) 547 | } 548 | 549 | // Set MaxSize to a value that will accept one longMessage, but not two. 550 | longMessage := strings.Repeat("x", 1024) 551 | defer func(previous uint64) { MaxSize = previous }(MaxSize) 552 | MaxSize = uint64(fi.Size()) + uint64(2*len(longMessage)) - 1 553 | 554 | fname0 := info.file.Name() 555 | 556 | // Advance clock by 1.5 seconds to force rotation by size. 557 | // (The .5 will be important for the last test as well). 558 | tick(1500 * time.Millisecond) 559 | Info(longMessage) 560 | Info(longMessage) 561 | info.Flush() 562 | 563 | fname1 := info.file.Name() 564 | if fname0 == fname1 { 565 | t.Errorf("info.f.Name did not change: %v", fname0) 566 | } 567 | if info.nbytes >= MaxSize { 568 | t.Errorf("file size was not reset: %d", info.nbytes) 569 | } 570 | 571 | // Check to see if the original file has the continued footer. 572 | f0, err := ioutil.ReadFile(fname0) 573 | if err != nil { 574 | t.Fatalf("Unable to read file %s: %v", fname0, err) 575 | } 576 | if !bytes.HasSuffix(f0, []byte(footer)) { 577 | t.Errorf("%v: Missing footer %q", fname0, footer) 578 | } 579 | found := false 580 | for _, l := range bytes.Split(f0, []byte("\n")) { 581 | var file string 582 | _, err = fmt.Sscanf(string(l), "Next log: %s\n", &file) 583 | if err != nil { 584 | continue 585 | } 586 | if file != fname1 { 587 | t.Errorf("%v: Wanted next filename %s, got %s", fname0, fname1, file) 588 | } 589 | found = true 590 | } 591 | if !found { 592 | t.Errorf("%v: Next log footer not found", fname0) 593 | } 594 | 595 | // Check to see if the previous file header is there in the new file 596 | f1, err := ioutil.ReadFile(fname1) 597 | if err != nil { 598 | t.Fatalf("Unable to read file %s: %v", fname1, err) 599 | } 600 | found = false 601 | for _, l := range bytes.Split(f1, []byte("\n")) { 602 | var file string 603 | _, err = fmt.Sscanf(string(l), "Previous log: %s\n", &file) 604 | if err != nil { 605 | continue 606 | } 607 | if file != fname0 { 608 | t.Errorf("%v: Wanted previous filename %s, got %s", fname1, fname0, file) 609 | } 610 | found = true 611 | } 612 | if !found { 613 | t.Errorf("%v: Previous log header not found", fname1) 614 | } 615 | 616 | // Make sure Names returned the right names. 617 | n, err := Names("INFO") 618 | if (len(n) != 2 || err != nil) && n[0] != fname0 && n[1] != fname1 { 619 | t.Errorf("Names(INFO) wanted [%s, %s]/nil, got %v/%v", fname0, fname1, n, err) 620 | } 621 | 622 | // The following tests assume that previous test left clock at .5 seconds. 623 | if fakeNow.Nanosecond() != 5e8 { 624 | t.Fatalf("BUG: fake clock should be exactly at .5 seconds") 625 | } 626 | 627 | // Same second would create conflicting filename, no rotation expected. 628 | tick(499 * time.Millisecond) 629 | Info(longMessage) 630 | Info(longMessage) 631 | n, err = Names("INFO") 632 | if got, want := len(n), 2; got != want || err != nil { 633 | t.Errorf("Names(INFO) = %v (len=%v), %v, want %d names: expected no rotation within same second", n, got, err, want) 634 | } 635 | 636 | // Trigger a subsecond rotation in next fakeClock second. 637 | tick(1 * time.Millisecond) 638 | Info(longMessage) 639 | Info(longMessage) 640 | n, err = Names("INFO") 641 | if got, want := len(n), 3; got != want || err != nil { 642 | t.Errorf("Names(INFO) = %v (len=%v), %v, want %d names: expected a rotation after under a second when filename does not conflict", n, got, err, want) 643 | } 644 | 645 | // Trigger a rotation within a minute since the last rotation. 646 | tick(time.Minute) 647 | Info(longMessage) 648 | Info(longMessage) 649 | n, err = Names("INFO") 650 | if got, want := len(n), 4; got != want || err != nil { 651 | t.Errorf("Names(INFO) = %v (len=%v), %v, want %d names: expected a rotation after one minute since last rotation", n, got, err, want) 652 | } 653 | 654 | if t.Failed() { 655 | t.Logf("========================================================") 656 | t.Logf("%s:\n%s", fname0, f0) 657 | t.Logf("========================================================") 658 | t.Logf("%s:\n%s", fname1, f1) 659 | } 660 | 661 | } 662 | 663 | func TestLogBacktraceAt(t *testing.T) { 664 | setFlags() 665 | defer sinks.file.swap(sinks.file.newBuffers()) 666 | // The peculiar style of this code simplifies line counting and maintenance of the 667 | // tracing block below. 668 | var infoLine string 669 | setTraceLocation := func(file string, line int, ok bool, delta int) { 670 | if !ok { 671 | t.Fatal("could not get file:line") 672 | } 673 | _, file = filepath.Split(file) 674 | infoLine = fmt.Sprintf("%s:%d", file, line+delta) 675 | err := logBacktraceAt.Set(infoLine) 676 | if err != nil { 677 | t.Fatal("error setting log_backtrace_at: ", err) 678 | } 679 | } 680 | { 681 | // Start of tracing block. These lines know about each other's relative position. 682 | _, file, line, ok := runtime.Caller(0) 683 | setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. 684 | Info("we want a stack trace here") 685 | } 686 | numAppearances := strings.Count(contents(logsink.Info), infoLine) 687 | if numAppearances < 2 { 688 | // Need 2 appearances, one in the log header and one in the trace: 689 | // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here 690 | // ... 691 | // .../glog/glog_test.go:280 (0x41ba91) 692 | // ... 693 | // We could be more precise but that would require knowing the details 694 | // of the traceback format, which may not be dependable. 695 | t.Fatal("got no trace back; log is ", contents(logsink.Info)) 696 | } 697 | } 698 | 699 | func TestNewStandardLoggerLogBacktraceAt(t *testing.T) { 700 | setFlags() 701 | defer sinks.file.swap(sinks.file.newBuffers()) 702 | s := NewStandardLogger("INFO") 703 | // The peculiar style of this code simplifies line counting and maintenance of the 704 | // tracing block below. 705 | var infoLine string 706 | setTraceLocation := func(file string, line int, ok bool, delta int) { 707 | if !ok { 708 | t.Fatal("could not get file:line") 709 | } 710 | _, file = filepath.Split(file) 711 | infoLine = fmt.Sprintf("%s:%d", file, line+delta) 712 | err := logBacktraceAt.Set(infoLine) 713 | if err != nil { 714 | t.Fatal("error setting log_backtrace_at: ", err) 715 | } 716 | } 717 | { 718 | // Start of tracing block. These lines know about each other's relative position. 719 | _, file, line, ok := runtime.Caller(0) 720 | setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. 721 | s.Printf("we want a stack trace here") 722 | } 723 | infoContents := contents(logsink.Info) 724 | if strings.Contains(infoContents, infoLine+"] [") { 725 | t.Fatal("got extra bracketing around log line contents; log is ", infoContents) 726 | } 727 | numAppearances := strings.Count(infoContents, infoLine) 728 | if numAppearances < 2 { 729 | // Need 2 appearances, one in the log header and one in the trace: 730 | // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here 731 | // ... 732 | // .../glog/glog_test.go:280 (0x41ba91) 733 | // ... 734 | // We could be more precise but that would require knowing the details 735 | // of the traceback format, which may not be dependable. 736 | t.Fatal("got no trace back; log is ", infoContents) 737 | } 738 | } 739 | 740 | // Test to make sure the log naming function works properly. 741 | func TestLogNames(t *testing.T) { 742 | setFlags() 743 | defer sinks.file.swap(sinks.file.newBuffers()) 744 | n, e := Names("FOO") 745 | if e == nil { 746 | t.Errorf("Names(FOO) was %v/nil, should be []/error", n) 747 | } 748 | 749 | // Set the infoLog to nil to simulate "log not yet written to" 750 | h := sinks.file.file[logsink.Info] 751 | sinks.file.file[logsink.Info] = nil 752 | n, e = Names("INFO") 753 | if e != ErrNoLog { 754 | t.Errorf("Names(INFO) was %v/%v, should be [], ErrNoLog", n, e) 755 | } 756 | sinks.file.file[logsink.Info] = h 757 | 758 | // Get the name; testing has a fixed fake name for these. 759 | Info("test") 760 | n, e = Names("INFO") 761 | if len(n) != 1 && n[0] != "" { 762 | t.Errorf("Names(INFO) got %s, want ", n) 763 | } 764 | } 765 | 766 | func TestLogLength(t *testing.T) { 767 | setFlags() 768 | defer sinks.file.swap(sinks.file.newBuffers()) 769 | Info(strings.Repeat("X", logsink.MaxLogMessageLen*2)) 770 | if c := contents(logsink.Info); len(c) != logsink.MaxLogMessageLen { 771 | t.Errorf("Info was not truncated: got length %d, want %d, contents %q", 772 | len(c), logsink.MaxLogMessageLen, c) 773 | } 774 | } 775 | 776 | func TestCreateFailsIfExists(t *testing.T) { 777 | tmp := t.TempDir() 778 | now := time.Now() 779 | if _, _, err := create("INFO", now, tmp); err != nil { 780 | t.Errorf("create() failed on first call: %v", err) 781 | } 782 | if _, _, err := create("INFO", now, tmp); err == nil { 783 | t.Errorf("create() succeeded on second call, want error") 784 | } 785 | } 786 | -------------------------------------------------------------------------------- /glog_vmodule_test.go: -------------------------------------------------------------------------------- 1 | package glog 2 | 3 | // runInAnotherModule is a simple wrapper that, being defined in another file, 4 | // provides a different vmodule stack frame on the stack for use with 5 | // glog.*Depth testing. 6 | // 7 | //go:noinline 8 | func runInAnotherModule(f func() bool) bool { 9 | return f() 10 | } 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/golang/glog 2 | 3 | go 1.19 4 | 5 | require github.com/google/go-cmp v0.6.0 // indirect 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 2 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 3 | -------------------------------------------------------------------------------- /internal/logsink/logsink.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package logsink 16 | 17 | import ( 18 | "bytes" 19 | "context" 20 | "fmt" 21 | "strconv" 22 | "strings" 23 | "sync" 24 | "time" 25 | 26 | "github.com/golang/glog/internal/stackdump" 27 | ) 28 | 29 | // MaxLogMessageLen is the limit on length of a formatted log message, including 30 | // the standard line prefix and trailing newline. 31 | // 32 | // Chosen to match C++ glog. 33 | const MaxLogMessageLen = 15000 34 | 35 | // A Severity is a severity at which a message can be logged. 36 | type Severity int8 37 | 38 | // These constants identify the log levels in order of increasing severity. 39 | // A message written to a high-severity log file is also written to each 40 | // lower-severity log file. 41 | const ( 42 | Info Severity = iota 43 | Warning 44 | Error 45 | 46 | // Fatal contains logs written immediately before the process terminates. 47 | // 48 | // Sink implementations should not terminate the process themselves: the log 49 | // package will perform any necessary cleanup and terminate the process as 50 | // appropriate. 51 | Fatal 52 | ) 53 | 54 | func (s Severity) String() string { 55 | switch s { 56 | case Info: 57 | return "INFO" 58 | case Warning: 59 | return "WARNING" 60 | case Error: 61 | return "ERROR" 62 | case Fatal: 63 | return "FATAL" 64 | } 65 | return fmt.Sprintf("%T(%d)", s, s) 66 | } 67 | 68 | // ParseSeverity returns the case-insensitive Severity value for the given string. 69 | func ParseSeverity(name string) (Severity, error) { 70 | name = strings.ToUpper(name) 71 | for s := Info; s <= Fatal; s++ { 72 | if s.String() == name { 73 | return s, nil 74 | } 75 | } 76 | return -1, fmt.Errorf("logsink: invalid severity %q", name) 77 | } 78 | 79 | // Meta is metadata about a logging call. 80 | type Meta struct { 81 | // The context with which the log call was made (or nil). If set, the context 82 | // is only valid during the logsink.Structured.Printf call, it should not be 83 | // retained. 84 | Context context.Context 85 | 86 | // Time is the time at which the log call was made. 87 | Time time.Time 88 | 89 | // File is the source file from which the log entry originates. 90 | File string 91 | // Line is the line offset within the source file. 92 | Line int 93 | // Depth is the number of stack frames between the logsink and the log call. 94 | Depth int 95 | 96 | Severity Severity 97 | 98 | // Verbose indicates whether the call was made via "log.V". Log entries below 99 | // the current verbosity threshold are not sent to the sink. 100 | Verbose bool 101 | 102 | // Thread ID. This can be populated with a thread ID from another source, 103 | // such as a system we are importing logs from. In the normal case, this 104 | // will be set to the process ID (PID), since Go doesn't have threads. 105 | Thread int64 106 | 107 | // Stack trace starting in the logging function. May be nil. 108 | // A logsink should implement the StackWanter interface to request this. 109 | // 110 | // Even if WantStack returns false, this field may be set (e.g. if another 111 | // sink wants a stack trace). 112 | Stack *stackdump.Stack 113 | } 114 | 115 | // Structured is a logging destination that accepts structured data as input. 116 | type Structured interface { 117 | // Printf formats according to a fmt.Printf format specifier and writes a log 118 | // entry. The precise result of formatting depends on the sink, but should 119 | // aim for consistency with fmt.Printf. 120 | // 121 | // Printf returns the number of bytes occupied by the log entry, which 122 | // may not be equal to the total number of bytes written. 123 | // 124 | // Printf returns any error encountered *if* it is severe enough that the log 125 | // package should terminate the process. 126 | // 127 | // The sink must not modify the *Meta parameter, nor reference it after 128 | // Printf has returned: it may be reused in subsequent calls. 129 | Printf(meta *Meta, format string, a ...any) (n int, err error) 130 | } 131 | 132 | // StackWanter can be implemented by a logsink.Structured to indicate that it 133 | // wants a stack trace to accompany at least some of the log messages it receives. 134 | type StackWanter interface { 135 | // WantStack returns true if the sink requires a stack trace for a log message 136 | // with this metadata. 137 | // 138 | // NOTE: Returning true implies that meta.Stack will be non-nil. Returning 139 | // false does NOT imply that meta.Stack will be nil. 140 | WantStack(meta *Meta) bool 141 | } 142 | 143 | // Text is a logging destination that accepts pre-formatted log lines (instead of 144 | // structured data). 145 | type Text interface { 146 | // Enabled returns whether this sink should output messages for the given 147 | // Meta. If the sink returns false for a given Meta, the Printf function will 148 | // not call Emit on it for the corresponding log message. 149 | Enabled(*Meta) bool 150 | 151 | // Emit writes a pre-formatted text log entry (including any applicable 152 | // header) to the log. It returns the number of bytes occupied by the entry 153 | // (which may differ from the length of the passed-in slice). 154 | // 155 | // Emit returns any error encountered *if* it is severe enough that the log 156 | // package should terminate the process. 157 | // 158 | // The sink must not modify the *Meta parameter, nor reference it after 159 | // Printf has returned: it may be reused in subsequent calls. 160 | // 161 | // NOTE: When developing a text sink, keep in mind the surface in which the 162 | // logs will be displayed, and whether it's important that the sink be 163 | // resistent to tampering in the style of b/211428300. Standard text sinks 164 | // (like `stderrSink`) do not protect against this (e.g. by escaping 165 | // characters) because the cases where they would show user-influenced bytes 166 | // are vanishingly small. 167 | Emit(*Meta, []byte) (n int, err error) 168 | } 169 | 170 | // bufs is a pool of *bytes.Buffer used in formatting log entries. 171 | var bufs sync.Pool // Pool of *bytes.Buffer. 172 | 173 | // textPrintf formats a text log entry and emits it to all specified Text sinks. 174 | // 175 | // The returned n is the maximum across all Emit calls. 176 | // The returned err is the first non-nil error encountered. 177 | // Sinks that are disabled by configuration should return (0, nil). 178 | func textPrintf(m *Meta, textSinks []Text, format string, args ...any) (n int, err error) { 179 | // We expect at most file, stderr, and perhaps syslog. If there are more, 180 | // we'll end up allocating - no big deal. 181 | const maxExpectedTextSinks = 3 182 | var noAllocSinks [maxExpectedTextSinks]Text 183 | 184 | sinks := noAllocSinks[:0] 185 | for _, s := range textSinks { 186 | if s.Enabled(m) { 187 | sinks = append(sinks, s) 188 | } 189 | } 190 | if len(sinks) == 0 && m.Severity != Fatal { 191 | return 0, nil // No TextSinks specified; don't bother formatting. 192 | } 193 | 194 | bufi := bufs.Get() 195 | var buf *bytes.Buffer 196 | if bufi == nil { 197 | buf = bytes.NewBuffer(nil) 198 | bufi = buf 199 | } else { 200 | buf = bufi.(*bytes.Buffer) 201 | buf.Reset() 202 | } 203 | 204 | // Lmmdd hh:mm:ss.uuuuuu PID/GID file:line] 205 | // 206 | // The "PID" entry arguably ought to be TID for consistency with other 207 | // environments, but TID is not meaningful in a Go program due to the 208 | // multiplexing of goroutines across threads. 209 | // 210 | // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. 211 | // It's worth about 3X. Fprintf is hard. 212 | const severityChar = "IWEF" 213 | buf.WriteByte(severityChar[m.Severity]) 214 | 215 | _, month, day := m.Time.Date() 216 | hour, minute, second := m.Time.Clock() 217 | twoDigits(buf, int(month)) 218 | twoDigits(buf, day) 219 | buf.WriteByte(' ') 220 | twoDigits(buf, hour) 221 | buf.WriteByte(':') 222 | twoDigits(buf, minute) 223 | buf.WriteByte(':') 224 | twoDigits(buf, second) 225 | buf.WriteByte('.') 226 | nDigits(buf, 6, uint64(m.Time.Nanosecond()/1000), '0') 227 | buf.WriteByte(' ') 228 | 229 | nDigits(buf, 7, uint64(m.Thread), ' ') 230 | buf.WriteByte(' ') 231 | 232 | { 233 | file := m.File 234 | if i := strings.LastIndex(file, "/"); i >= 0 { 235 | file = file[i+1:] 236 | } 237 | buf.WriteString(file) 238 | } 239 | 240 | buf.WriteByte(':') 241 | { 242 | var tmp [19]byte 243 | buf.Write(strconv.AppendInt(tmp[:0], int64(m.Line), 10)) 244 | } 245 | buf.WriteString("] ") 246 | 247 | msgStart := buf.Len() 248 | fmt.Fprintf(buf, format, args...) 249 | if buf.Len() > MaxLogMessageLen-1 { 250 | buf.Truncate(MaxLogMessageLen - 1) 251 | } 252 | msgEnd := buf.Len() 253 | if b := buf.Bytes(); b[len(b)-1] != '\n' { 254 | buf.WriteByte('\n') 255 | } 256 | 257 | for _, s := range sinks { 258 | sn, sErr := s.Emit(m, buf.Bytes()) 259 | if sn > n { 260 | n = sn 261 | } 262 | if sErr != nil && err == nil { 263 | err = sErr 264 | } 265 | } 266 | 267 | if m.Severity == Fatal { 268 | savedM := *m 269 | fatalMessageStore(savedEntry{ 270 | meta: &savedM, 271 | msg: buf.Bytes()[msgStart:msgEnd], 272 | }) 273 | } else { 274 | bufs.Put(bufi) 275 | } 276 | return n, err 277 | } 278 | 279 | const digits = "0123456789" 280 | 281 | // twoDigits formats a zero-prefixed two-digit integer to buf. 282 | func twoDigits(buf *bytes.Buffer, d int) { 283 | buf.WriteByte(digits[(d/10)%10]) 284 | buf.WriteByte(digits[d%10]) 285 | } 286 | 287 | // nDigits formats an n-digit integer to buf, padding with pad on the left. It 288 | // assumes d != 0. 289 | func nDigits(buf *bytes.Buffer, n int, d uint64, pad byte) { 290 | var tmp [20]byte 291 | 292 | cutoff := len(tmp) - n 293 | j := len(tmp) - 1 294 | for ; d > 0; j-- { 295 | tmp[j] = digits[d%10] 296 | d /= 10 297 | } 298 | for ; j >= cutoff; j-- { 299 | tmp[j] = pad 300 | } 301 | j++ 302 | buf.Write(tmp[j:]) 303 | } 304 | 305 | // Printf writes a log entry to all registered TextSinks in this package, then 306 | // to all registered StructuredSinks. 307 | // 308 | // The returned n is the maximum across all Emit and Printf calls. 309 | // The returned err is the first non-nil error encountered. 310 | // Sinks that are disabled by configuration should return (0, nil). 311 | func Printf(m *Meta, format string, args ...any) (n int, err error) { 312 | m.Depth++ 313 | n, err = textPrintf(m, TextSinks, format, args...) 314 | 315 | for _, sink := range StructuredSinks { 316 | // TODO: Support TextSinks that implement StackWanter? 317 | if sw, ok := sink.(StackWanter); ok && sw.WantStack(m) { 318 | if m.Stack == nil { 319 | // First, try to find a stacktrace in args, otherwise generate one. 320 | for _, arg := range args { 321 | if stack, ok := arg.(stackdump.Stack); ok { 322 | m.Stack = &stack 323 | break 324 | } 325 | } 326 | if m.Stack == nil { 327 | stack := stackdump.Caller( /* skipDepth = */ m.Depth) 328 | m.Stack = &stack 329 | } 330 | } 331 | } 332 | sn, sErr := sink.Printf(m, format, args...) 333 | if sn > n { 334 | n = sn 335 | } 336 | if sErr != nil && err == nil { 337 | err = sErr 338 | } 339 | } 340 | return n, err 341 | } 342 | 343 | // The sets of sinks to which logs should be written. 344 | // 345 | // These must only be modified during package init, and are read-only thereafter. 346 | var ( 347 | // StructuredSinks is the set of Structured sink instances to which logs 348 | // should be written. 349 | StructuredSinks []Structured 350 | 351 | // TextSinks is the set of Text sink instances to which logs should be 352 | // written. 353 | // 354 | // These are registered separately from Structured sink implementations to 355 | // avoid the need to repeat the work of formatting a message for each Text 356 | // sink that writes it. The package-level Printf function writes to both sets 357 | // independenty, so a given log destination should only register a Structured 358 | // *or* a Text sink (not both). 359 | TextSinks []Text 360 | ) 361 | 362 | type savedEntry struct { 363 | meta *Meta 364 | msg []byte 365 | } 366 | 367 | // StructuredTextWrapper is a Structured sink which forwards logs to a set of Text sinks. 368 | // 369 | // The purpose of this sink is to allow applications to intercept logging calls before they are 370 | // serialized and sent to Text sinks. For example, if one needs to redact PII from logging 371 | // arguments before they reach STDERR, one solution would be to do the redacting in a Structured 372 | // sink that forwards logs to a StructuredTextWrapper instance, and make STDERR a child of that 373 | // StructuredTextWrapper instance. This is how one could set this up in their application: 374 | // 375 | // func init() { 376 | // 377 | // wrapper := logsink.StructuredTextWrapper{TextSinks: logsink.TextSinks} 378 | // // sanitizersink will intercept logs and remove PII 379 | // sanitizer := sanitizersink{Sink: &wrapper} 380 | // logsink.StructuredSinks = append(logsink.StructuredSinks, &sanitizer) 381 | // logsink.TextSinks = nil 382 | // 383 | // } 384 | type StructuredTextWrapper struct { 385 | // TextSinks is the set of Text sinks that should receive logs from this 386 | // StructuredTextWrapper instance. 387 | TextSinks []Text 388 | } 389 | 390 | // Printf forwards logs to all Text sinks registered in the StructuredTextWrapper. 391 | func (w *StructuredTextWrapper) Printf(meta *Meta, format string, args ...any) (n int, err error) { 392 | return textPrintf(meta, w.TextSinks, format, args...) 393 | } 394 | -------------------------------------------------------------------------------- /internal/logsink/logsink_fatal.go: -------------------------------------------------------------------------------- 1 | package logsink 2 | 3 | import ( 4 | "sync/atomic" 5 | "unsafe" 6 | ) 7 | 8 | func fatalMessageStore(e savedEntry) { 9 | // Only put a new one in if we haven't assigned before. 10 | atomic.CompareAndSwapPointer(&fatalMessage, nil, unsafe.Pointer(&e)) 11 | } 12 | 13 | var fatalMessage unsafe.Pointer // savedEntry stored with CompareAndSwapPointer 14 | 15 | // FatalMessage returns the Meta and message contents of the first message 16 | // logged with Fatal severity, or false if none has occurred. 17 | func FatalMessage() (*Meta, []byte, bool) { 18 | e := (*savedEntry)(atomic.LoadPointer(&fatalMessage)) 19 | if e == nil { 20 | return nil, nil, false 21 | } 22 | return e.meta, e.msg, true 23 | } 24 | 25 | // DoNotUseRacyFatalMessage is FatalMessage, but worse. 26 | // 27 | //go:norace 28 | //go:nosplit 29 | func DoNotUseRacyFatalMessage() (*Meta, []byte, bool) { 30 | e := (*savedEntry)(fatalMessage) 31 | if e == nil { 32 | return nil, nil, false 33 | } 34 | return e.meta, e.msg, true 35 | } 36 | -------------------------------------------------------------------------------- /internal/logsink/logsink_test.go: -------------------------------------------------------------------------------- 1 | package logsink_test 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "math" 7 | "reflect" 8 | "runtime" 9 | "slices" 10 | "testing" 11 | "time" 12 | 13 | "github.com/golang/glog/internal/logsink" 14 | "github.com/golang/glog/internal/stackdump" 15 | "github.com/google/go-cmp/cmp" 16 | ) 17 | 18 | // A savingTextSink saves the data argument of the last Emit call made to it. 19 | type savingTextSink struct{ data []byte } 20 | 21 | func (savingTextSink) Enabled(*logsink.Meta) bool { return true } 22 | func (s *savingTextSink) Emit(meta *logsink.Meta, data []byte) (n int, err error) { 23 | s.data = slices.Clone(data) 24 | return len(data), nil 25 | } 26 | 27 | func TestThreadPadding(t *testing.T) { 28 | originalSinks := logsink.StructuredSinks 29 | defer func() { logsink.StructuredSinks = originalSinks }() 30 | var sink savingTextSink 31 | logsink.TextSinks = []logsink.Text{&sink} 32 | 33 | _, file, line, _ := runtime.Caller(0) 34 | meta := &logsink.Meta{ 35 | Time: time.Now(), 36 | File: file, 37 | Line: line, 38 | Severity: logsink.Info, 39 | } 40 | 41 | const msg = "DOOMBAH!" 42 | 43 | for _, tc := range [...]struct { 44 | n uint64 45 | want []byte 46 | }{ 47 | // Integers that encode as fewer than 7 ASCII characters are padded, the 48 | // rest is not; see nDigits(). 49 | {want: []byte(" "), n: 0}, // nDigits does not support 0 (I presume for speed reasons). 50 | {want: []byte(" 1 "), n: 1}, 51 | {want: []byte(" 912389 "), n: 912389}, 52 | {want: []byte(" 2147483648 "), n: math.MaxInt32 + 1}, 53 | {want: []byte(" 9223372036854775806 "), n: math.MaxInt64 - 1}, 54 | {want: []byte(" 9223372036854775808 "), n: math.MaxInt64 + 1}, // Test int64 overflow. 55 | {want: []byte(" 9223372036854775817 "), n: math.MaxInt64 + 10}, // Test int64 overflow. 56 | {want: []byte(" 18446744073709551614 "), n: math.MaxUint64 - 1}, // Test int64 overflow. 57 | } { 58 | meta.Thread = int64(tc.n) 59 | logsink.Printf(meta, "%v", msg) 60 | t.Logf(`logsink.Printf(%+v, "%%v", %q)`, meta, msg) 61 | 62 | // Check if the needle is present exactly. 63 | if !bytes.Contains(sink.data, tc.want) { 64 | t.Errorf("needle = '%s' not found in %s", tc.want, sink.data) 65 | } 66 | } 67 | } 68 | 69 | func TestFatalMessage(t *testing.T) { 70 | const msg = "DOOOOOOM!" 71 | 72 | _, file, line, _ := runtime.Caller(0) 73 | meta := &logsink.Meta{ 74 | Time: time.Now(), 75 | File: file, 76 | Line: line, 77 | Severity: logsink.Fatal, 78 | } 79 | 80 | logsink.Printf(meta, "%v", msg) 81 | t.Logf(`logsink.Printf(%+v, "%%v", %q)`, meta, msg) 82 | 83 | gotMeta, gotMsg, ok := logsink.FatalMessage() 84 | if !ok || !reflect.DeepEqual(gotMeta, meta) || !bytes.Contains(gotMsg, []byte(msg)) { 85 | t.Errorf("logsink.FatalMessage() = %+v, %q, %v", gotMeta, gotMsg, ok) 86 | } 87 | } 88 | 89 | func TestStructuredSink(t *testing.T) { 90 | // Reset logsink.StructuredSinks at the end of the test. 91 | // Each test case will clear it and insert its own test sink. 92 | originalSinks := logsink.StructuredSinks 93 | defer func() { 94 | logsink.StructuredSinks = originalSinks 95 | }() 96 | 97 | testStacktrace := stackdump.Caller(0) 98 | 99 | for _, test := range []struct { 100 | name string 101 | format string 102 | args []any 103 | meta logsink.Meta 104 | wantErr bool 105 | sinks []testStructuredSinkAndWants 106 | }{ 107 | { 108 | name: "sink is called with expected format and args", 109 | format: "test %d", 110 | args: []any{1}, 111 | sinks: []testStructuredSinkAndWants{ 112 | { 113 | sink: &fakeStructuredSink{}, 114 | }, 115 | }, 116 | }, 117 | { 118 | name: "sink is called with expected meta", 119 | meta: logsink.Meta{ 120 | Severity: logsink.Info, 121 | File: "base/go/logsink_test.go", 122 | Line: 1, 123 | Time: time.Unix(1545321163, 0), 124 | Thread: 1, 125 | }, 126 | sinks: []testStructuredSinkAndWants{ 127 | { 128 | sink: &fakeStructuredSink{}, 129 | }, 130 | }, 131 | }, 132 | { 133 | name: "sink is called with expected meta (2)", 134 | meta: logsink.Meta{ 135 | Severity: logsink.Error, 136 | File: "foo.go", 137 | Line: 1337, 138 | Time: time.Unix(0, 0), 139 | Thread: 123, 140 | }, 141 | sinks: []testStructuredSinkAndWants{ 142 | { 143 | sink: &fakeStructuredSink{}, 144 | }, 145 | }, 146 | }, 147 | { 148 | name: "sink returns error", 149 | format: "test", 150 | meta: logsink.Meta{ 151 | Severity: logsink.Info, 152 | File: "base/go/logsink_test.go", 153 | Line: 1, 154 | Time: time.Unix(1545321163, 0), 155 | Thread: 1, 156 | }, 157 | wantErr: true, 158 | sinks: []testStructuredSinkAndWants{ 159 | { 160 | sink: &fakeStructuredSink{ 161 | err: errors.New("err"), 162 | }, 163 | }, 164 | }, 165 | }, 166 | { 167 | name: "sink is StackWanter and WantStack() returns true", 168 | sinks: []testStructuredSinkAndWants{ 169 | { 170 | sink: &fakeStructuredSinkThatWantsStack{ 171 | wantStack: true, 172 | }, 173 | wantStack: true, 174 | }, 175 | }, 176 | }, 177 | { 178 | name: "sink is StackWanter and WantStack() returns false", 179 | sinks: []testStructuredSinkAndWants{ 180 | { 181 | sink: &fakeStructuredSinkThatWantsStack{ 182 | wantStack: false, 183 | }, 184 | wantStack: false, 185 | }, 186 | }, 187 | }, 188 | { 189 | name: "use stacktrace from args if available", 190 | format: "test\n%s", 191 | args: []any{testStacktrace}, 192 | sinks: []testStructuredSinkAndWants{ 193 | { 194 | sink: &fakeStructuredSinkThatWantsStack{ 195 | wantStack: true, 196 | }, 197 | wantStack: true, 198 | wantStackEqual: &testStacktrace, 199 | }, 200 | }, 201 | }, 202 | { 203 | name: "respect StackWanter contract", 204 | format: "test\n%s", 205 | args: []any{testStacktrace}, 206 | sinks: []testStructuredSinkAndWants{ 207 | { 208 | sink: &fakeStructuredSinkThatWantsStack{ 209 | wantStack: true, 210 | }, 211 | wantStack: true, 212 | wantStackEqual: &testStacktrace, 213 | }, 214 | { 215 | sink: &fakeStructuredSink{}, 216 | }, 217 | }, 218 | }, 219 | { 220 | name: "respect StackWanter contract for multiple sinks", 221 | format: "test\n%s", 222 | args: []any{testStacktrace}, 223 | sinks: []testStructuredSinkAndWants{ 224 | { 225 | sink: &fakeStructuredSinkThatWantsStack{wantStack: true}, 226 | wantStack: true, 227 | wantStackEqual: &testStacktrace, 228 | }, 229 | { 230 | sink: &fakeStructuredSinkThatWantsStack{wantStack: false}, 231 | wantStack: false, 232 | }, 233 | { 234 | sink: &fakeStructuredSinkThatWantsStack{wantStack: true}, 235 | wantStack: true, 236 | wantStackEqual: &testStacktrace, 237 | }, 238 | { 239 | sink: &fakeStructuredSink{}, 240 | wantStack: false, 241 | }, 242 | { 243 | sink: &fakeStructuredSinkThatWantsStack{wantStack: true}, 244 | wantStack: true, 245 | wantStackEqual: &testStacktrace, 246 | }, 247 | }, 248 | }, 249 | } { 250 | t.Run(test.name, func(t *testing.T) { 251 | testStructuredSinks := make([]logsink.Structured, len(test.sinks)) 252 | for i, sink := range test.sinks { 253 | testStructuredSinks[i] = sink.sink 254 | } 255 | // Register test logsinks 256 | logsink.StructuredSinks = testStructuredSinks 257 | 258 | // logsink.Printf() should call Printf() on all registered logsinks. 259 | // Copy test.meta to prevent changes by the code under test. 260 | meta := test.meta 261 | _, err := logsink.Printf(&meta, test.format, test.args...) 262 | if gotErr := err != nil; gotErr != test.wantErr { 263 | t.Fatalf("logsink.Printf() = (_, %v), want err? %t", err, test.wantErr) 264 | } 265 | 266 | // Test the behavior for each registered StructuredSink. 267 | for _, testStructuredSinkAndWants := range test.sinks { 268 | // Check that the test logsink was called with expected arguments. 269 | if got, want := testStructuredSinkAndWants.sink.Calls(), 1; got != want { 270 | t.Fatalf("sink.calls = %d, want %d", got, want) 271 | } 272 | 273 | // Check that Meta was passed through to the logsink. 274 | gotMeta := testStructuredSinkAndWants.sink.GotMeta() 275 | // Ignore the Stack and Depth fields; these will be checked further down. 276 | cmpIgnoreSomeFields := cmp.FilterPath(func(p cmp.Path) bool { return p.String() == "Stack" || p.String() == "Depth" }, cmp.Ignore()) 277 | if diff := cmp.Diff(&test.meta, gotMeta, cmpIgnoreSomeFields); diff != "" { 278 | t.Errorf("sink.meta diff -want +got:\n%s", diff) 279 | } 280 | 281 | // The contract is: 282 | // - If WantStack is true, a Stack is present. 283 | // - If WantStack is false, a Stack may be present. 284 | if testStructuredSinkAndWants.wantStack && gotMeta.Stack == nil { 285 | t.Errorf("sink.meta.Stack = %v, but WantStack = %t", gotMeta.Stack, testStructuredSinkAndWants.wantStack) 286 | } else if testStructuredSinkAndWants.wantStackEqual != nil { 287 | // We have a stack, but is it the right one? 288 | if diff := cmp.Diff(testStructuredSinkAndWants.wantStackEqual, gotMeta.Stack); diff != "" { 289 | t.Errorf("sink.meta.Stack diff -want +got:\n%s", diff) 290 | } 291 | } 292 | 293 | // Depth should be 1, since test.meta.Depth is always 0 and there's a single 294 | // function call, logsink.Printf(), between here and the logsink. 295 | if got, want := gotMeta.Depth, 1; got != want { 296 | t.Errorf("sink.meta.Depth = %d, want %d", got, want) 297 | } 298 | 299 | if got, want := testStructuredSinkAndWants.sink.GotFormat(), test.format; got != want { 300 | t.Errorf("sink.format = %q, want %q", got, want) 301 | } 302 | 303 | if diff := cmp.Diff(test.args, testStructuredSinkAndWants.sink.GotArgs()); diff != "" { 304 | t.Errorf("sink.args diff -want +got:\n%s", diff) 305 | } 306 | } 307 | }) 308 | } 309 | } 310 | 311 | func BenchmarkStructuredSink(b *testing.B) { 312 | // Reset logsink.StructuredSinks at the end of the benchmark. 313 | // Each benchmark case will clear it and insert its own test sink. 314 | originalSinks := logsink.StructuredSinks 315 | defer func() { 316 | logsink.StructuredSinks = originalSinks 317 | }() 318 | 319 | noop := noopStructuredSink{} 320 | noopWS := noopStructuredSinkWantStack{} 321 | stringWS := stringStructuredSinkWantStack{} 322 | 323 | _, file, line, _ := runtime.Caller(0) 324 | stack := stackdump.Caller(0) 325 | genMeta := func(dump *stackdump.Stack) *logsink.Meta { 326 | return &logsink.Meta{ 327 | Time: time.Now(), 328 | File: file, 329 | Line: line, 330 | Severity: logsink.Warning, 331 | Thread: 1240, 332 | Stack: dump, 333 | } 334 | } 335 | 336 | for _, test := range []struct { 337 | name string 338 | sinks []logsink.Structured 339 | meta *logsink.Meta 340 | }{ 341 | {name: "meta_nostack_01_sinks_00_want_stack_pconly", meta: genMeta(nil), sinks: []logsink.Structured{noop}}, 342 | {name: "meta___stack_01_sinks_01_want_stack_pconly", meta: genMeta(&stack), sinks: []logsink.Structured{noopWS}}, 343 | {name: "meta_nostack_01_sinks_01_want_stack_pconly", meta: genMeta(nil), sinks: []logsink.Structured{noopWS}}, 344 | {name: "meta_nostack_01_sinks_01_want_stack_string", meta: genMeta(nil), sinks: []logsink.Structured{stringWS}}, 345 | {name: "meta_nostack_02_sinks_01_want_stack_pconly", meta: genMeta(nil), sinks: []logsink.Structured{noopWS, noop}}, 346 | {name: "meta_nostack_02_sinks_02_want_stack_string", meta: genMeta(nil), sinks: []logsink.Structured{stringWS, stringWS}}, 347 | {name: "meta_nostack_10_sinks_00_want_stack_pconly", meta: genMeta(nil), sinks: []logsink.Structured{noop, noop, noop, noop, noop, noop, noop, noop, noop, noop}}, 348 | {name: "meta_nostack_10_sinks_05_want_stack_pconly", meta: genMeta(nil), sinks: []logsink.Structured{noop, noopWS, noop, noop, noopWS, noop, noopWS, noopWS, noopWS, noop}}, 349 | {name: "meta_nostack_10_sinks_05_want_stack_string", meta: genMeta(nil), sinks: []logsink.Structured{noop, stringWS, noop, noop, stringWS, noop, stringWS, stringWS, stringWS, noop}}, 350 | {name: "meta___stack_10_sinks_05_want_stack_pconly", meta: genMeta(&stack), sinks: []logsink.Structured{noop, noopWS, noop, noop, noopWS, noop, noopWS, noopWS, noopWS, noop}}, 351 | {name: "meta___stack_10_sinks_05_want_stack_string", meta: genMeta(&stack), sinks: []logsink.Structured{noop, stringWS, noop, noop, stringWS, noop, stringWS, stringWS, stringWS, noop}}, 352 | } { 353 | b.Run(test.name, func(b *testing.B) { 354 | logsink.StructuredSinks = test.sinks 355 | savedStack := test.meta.Stack 356 | 357 | args := []any{1} // Pre-allocate args slice to avoid allocation in benchmark loop. 358 | 359 | b.ResetTimer() 360 | for i := 0; i < b.N; i++ { 361 | _, err := logsink.Printf(test.meta, "test %d", args...) 362 | if err != nil { 363 | b.Fatalf("logsink.Printf(): didn't expect any error while benchmarking, got %v", err) 364 | } 365 | // logsink.Printf modifies Meta.Depth, which is used during stack 366 | // collection. If we don't reset it, stacks quickly become empty, making 367 | // the benchmark useless. 368 | test.meta.Depth = 0 369 | // There is a possible optimization where logsink.Printf will avoid 370 | // allocating a new meta and modify it in-place if it needs a stack. 371 | // This would throw off benchmarks as subsequent invocations would 372 | // re-use this stack. Since we know this memoization/modification only 373 | // happens with stacks, reset it manually to avoid skewing allocation 374 | // numbers. 375 | test.meta.Stack = savedStack 376 | } 377 | }) 378 | } 379 | } 380 | 381 | // testStructuredSinkAndWants contains a StructuredSink under test 382 | // and its wanted values. The struct is created to help with testing 383 | // multiple StructuredSinks for Printf(). 384 | type testStructuredSinkAndWants struct { 385 | // The sink under test. 386 | sink testStructuredSink 387 | // Whether this sink should want stack in its meta. 388 | // Only set when the sink is fakeStructuredSinkThatWantsStack. 389 | wantStack bool 390 | // If this sink wants stack, the expected stack. 391 | // Only set when the sink is fakeStructuredSinkThatWantsStack and returns true for WantStack(). 392 | wantStackEqual *stackdump.Stack 393 | } 394 | 395 | type testStructuredSink interface { 396 | logsink.Structured 397 | 398 | GotMeta() *logsink.Meta 399 | GotFormat() string 400 | GotArgs() []any 401 | Calls() int 402 | } 403 | 404 | type fakeStructuredSink struct { 405 | // err is returned by Printf(). 406 | err error 407 | // gotMeta is the Meta passed to the last Printf() call. 408 | gotMeta *logsink.Meta 409 | // gotFormat is the format string passed to the last Printf() call. 410 | gotFormat string 411 | // gotArgs are the arguments passed to the last Printf() call. 412 | gotArgs []any 413 | // calls is a counter of the number of times Printf() has been called. 414 | calls int 415 | } 416 | 417 | func (s *fakeStructuredSink) GotMeta() *logsink.Meta { 418 | return s.gotMeta 419 | } 420 | 421 | func (s *fakeStructuredSink) GotFormat() string { 422 | return s.gotFormat 423 | } 424 | 425 | func (s *fakeStructuredSink) GotArgs() []any { 426 | return s.gotArgs 427 | } 428 | 429 | func (s *fakeStructuredSink) Calls() int { 430 | return s.calls 431 | } 432 | 433 | func (s *fakeStructuredSink) Printf(meta *logsink.Meta, format string, a ...any) (n int, err error) { 434 | s.gotMeta = meta 435 | s.gotFormat = format 436 | s.gotArgs = a 437 | s.calls++ 438 | return 0, s.err 439 | } 440 | 441 | type fakeStructuredSinkThatWantsStack struct { 442 | fakeStructuredSink 443 | // wantStack controls what the WantStack() method returns. 444 | wantStack bool 445 | } 446 | 447 | func (s *fakeStructuredSinkThatWantsStack) WantStack(meta *logsink.Meta) bool { 448 | return s.wantStack 449 | } 450 | 451 | type noopStructuredSink struct{} 452 | 453 | func (s noopStructuredSink) Printf(meta *logsink.Meta, format string, a ...any) (n int, err error) { 454 | return 0, nil 455 | } 456 | 457 | type noopStructuredSinkWantStack struct{} 458 | 459 | func (s noopStructuredSinkWantStack) WantStack(_ *logsink.Meta) bool { return true } 460 | func (s noopStructuredSinkWantStack) Printf(meta *logsink.Meta, format string, a ...any) (n int, err error) { 461 | return 0, nil 462 | } 463 | 464 | type stringStructuredSinkWantStack struct{} 465 | 466 | func (s stringStructuredSinkWantStack) WantStack(_ *logsink.Meta) bool { return true } 467 | func (s stringStructuredSinkWantStack) Printf(meta *logsink.Meta, format string, a ...any) (n int, err error) { 468 | return len(meta.Stack.String()), nil 469 | } 470 | 471 | // TestStructuredTextWrapper tests StructuredTextWrapper.Printf(). 472 | // It validates the input received by each Text sink in StructuredTextWrapper.TextSinks 473 | // by comparing it to the input received by a Text sink in logsink.TextSinks. We assume 474 | // that logsink.TextSinks receives a correct input (that fact is already tested in log.test.go) 475 | func TestStructuredTextWrapper(t *testing.T) { 476 | // Reset logsink.TextSinks at the end of the test. 477 | originalTextSinks := logsink.TextSinks 478 | defer func() { 479 | logsink.TextSinks = originalTextSinks 480 | }() 481 | 482 | // The input received by the `reference` sink will be used to validate the input received by 483 | // each sink in StructuredTextWrapper.TextSinks. 484 | reference := fakeTextSink{enabled: true} 485 | logsink.TextSinks = []logsink.Text{&reference} 486 | 487 | meta := logsink.Meta{ 488 | Severity: logsink.Info, 489 | File: "base/go/logsink_test.go", 490 | Line: 1, 491 | Time: time.Unix(1545321163, 0), 492 | Thread: 1, 493 | } 494 | format := "test %d" 495 | args := []any{1} 496 | 497 | for _, test := range []struct { 498 | name string 499 | sinks []fakeTextSink 500 | wantByteCount int 501 | wantErr bool 502 | }{ 503 | { 504 | name: "no sinks", 505 | sinks: []fakeTextSink{}, 506 | }, 507 | { 508 | name: "single sink", 509 | sinks: []fakeTextSink{ 510 | fakeTextSink{enabled: true, byteCount: 300}, 511 | }, 512 | wantByteCount: 300, 513 | }, 514 | { 515 | name: "multiple sinks", 516 | sinks: []fakeTextSink{ 517 | fakeTextSink{enabled: true, byteCount: 100}, 518 | fakeTextSink{enabled: true, byteCount: 300}, 519 | fakeTextSink{enabled: true, byteCount: 200}, 520 | }, 521 | wantByteCount: 300, 522 | }, 523 | { 524 | name: "some sinks disabled", 525 | sinks: []fakeTextSink{ 526 | fakeTextSink{enabled: true, byteCount: 100}, 527 | fakeTextSink{enabled: true, byteCount: 200}, 528 | fakeTextSink{}, 529 | fakeTextSink{}, 530 | }, 531 | wantByteCount: 200, 532 | }, 533 | { 534 | name: "all sinks disabled", 535 | sinks: []fakeTextSink{ 536 | fakeTextSink{}, 537 | fakeTextSink{}, 538 | fakeTextSink{}, 539 | }, 540 | }, 541 | { 542 | name: "error", 543 | sinks: []fakeTextSink{ 544 | fakeTextSink{enabled: true, byteCount: 100}, 545 | fakeTextSink{enabled: true, err: errors.New("err")}, 546 | fakeTextSink{enabled: true, byteCount: 200}, 547 | }, 548 | wantErr: true, 549 | }, 550 | } { 551 | t.Run(test.name, func(t *testing.T) { 552 | wrapper := logsink.StructuredTextWrapper{} 553 | for i := range test.sinks { 554 | wrapper.TextSinks = append(wrapper.TextSinks, &test.sinks[i]) 555 | } 556 | 557 | // Writing to reference sink. 558 | // Copy meta to prevent changes by the code under test. 559 | m := meta 560 | if _, err := logsink.Printf(&m, format, args); err != nil { 561 | t.Fatalf("failed to write to reference sink: %v", err) 562 | } 563 | 564 | // Writing to StructuredTextWrapper. 565 | // Copy meta to prevent changes by the code under test. 566 | m = meta 567 | n, err := wrapper.Printf(&m, format, args) 568 | 569 | if gotErr := err != nil; gotErr != test.wantErr { 570 | t.Fatalf("StructuredTextWrapper.Printf() returned err=%v, want err? %t", err, test.wantErr) 571 | } 572 | 573 | // If an error is expected, we are done. 574 | if err != nil { 575 | return 576 | } 577 | 578 | if n != test.wantByteCount { 579 | t.Fatalf("StructuredTextWrapper.Printf() returned n=%v, want %v", n, test.wantByteCount) 580 | } 581 | 582 | for i, sink := range test.sinks { 583 | if sink.enabled { 584 | if got, want := sink.calls, 1; got != want { 585 | t.Fatalf("sinks[%v].calls = %d, want %d", i, got, want) 586 | } 587 | 588 | if diff := cmp.Diff(&meta, sink.gotMeta); diff != "" { 589 | t.Errorf("sinks[%v].meta diff -want +got:\n%s", i, diff) 590 | } 591 | 592 | if got, want := sink.gotBytes, reference.gotBytes; bytes.Compare(got, want) != 0 { 593 | t.Errorf("sinks[%v].bytes = %s, want %s", i, got, want) 594 | } 595 | } else { 596 | if got, want := sink.calls, 0; got != want { 597 | t.Fatalf("sinks[%v].calls = %d, want %d", i, got, want) 598 | } 599 | } 600 | } 601 | }) 602 | } 603 | } 604 | 605 | type fakeTextSink struct { 606 | // enabled is returned by Enabled(). 607 | enabled bool 608 | // byteCount is returned by Emit(). 609 | byteCount int 610 | // err is returned by Emit(). 611 | err error 612 | // gotMeta is the Meta passed to the last Emit() call. 613 | gotMeta *logsink.Meta 614 | // gotBytes is the byte slice passed to the last Emit() call. 615 | gotBytes []byte 616 | // calls is a counter of the number of times Emit() has been called. 617 | calls int 618 | } 619 | 620 | func (s *fakeTextSink) Enabled(meta *logsink.Meta) bool { 621 | return s.enabled 622 | } 623 | 624 | func (s *fakeTextSink) Emit(meta *logsink.Meta, bytes []byte) (n int, err error) { 625 | s.gotMeta = meta 626 | s.gotBytes = bytes 627 | s.calls++ 628 | return s.byteCount, s.err 629 | } 630 | -------------------------------------------------------------------------------- /internal/stackdump/stackdump.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package stackdump provides wrappers for runtime.Stack and runtime.Callers 16 | // with uniform support for skipping caller frames. 17 | // 18 | // ⚠ Unlike the functions in the runtime package, these may allocate a 19 | // non-trivial quantity of memory: use them with care. ⚠ 20 | package stackdump 21 | 22 | import ( 23 | "bytes" 24 | "runtime" 25 | ) 26 | 27 | // runtimeStackSelfFrames is 1 if runtime.Stack includes the call to 28 | // runtime.Stack itself or 0 if it does not. 29 | // 30 | // As of 2016-04-27, the gccgo compiler includes runtime.Stack but the gc 31 | // compiler does not. 32 | var runtimeStackSelfFrames = func() int { 33 | for n := 1 << 10; n < 1<<20; n *= 2 { 34 | buf := make([]byte, n) 35 | n := runtime.Stack(buf, false) 36 | if bytes.Contains(buf[:n], []byte("runtime.Stack")) { 37 | return 1 38 | } else if n < len(buf) || bytes.Count(buf, []byte("\n")) >= 3 { 39 | return 0 40 | } 41 | } 42 | return 0 43 | }() 44 | 45 | // Stack is a stack dump for a single goroutine. 46 | type Stack struct { 47 | // Text is a representation of the stack dump in a human-readable format. 48 | Text []byte 49 | 50 | // PC is a representation of the stack dump using raw program counter values. 51 | PC []uintptr 52 | } 53 | 54 | func (s Stack) String() string { return string(s.Text) } 55 | 56 | // Caller returns the Stack dump for the calling goroutine, starting skipDepth 57 | // frames before the caller of Caller. (Caller(0) provides a dump starting at 58 | // the caller of this function.) 59 | func Caller(skipDepth int) Stack { 60 | return Stack{ 61 | Text: CallerText(skipDepth + 1), 62 | PC: CallerPC(skipDepth + 1), 63 | } 64 | } 65 | 66 | // CallerText returns a textual dump of the stack starting skipDepth frames before 67 | // the caller. (CallerText(0) provides a dump starting at the caller of this 68 | // function.) 69 | func CallerText(skipDepth int) []byte { 70 | for n := 1 << 10; ; n *= 2 { 71 | buf := make([]byte, n) 72 | n := runtime.Stack(buf, false) 73 | if n < len(buf) { 74 | return pruneFrames(skipDepth+1+runtimeStackSelfFrames, buf[:n]) 75 | } 76 | } 77 | } 78 | 79 | // CallerPC returns a dump of the program counters of the stack starting 80 | // skipDepth frames before the caller. (CallerPC(0) provides a dump starting at 81 | // the caller of this function.) 82 | func CallerPC(skipDepth int) []uintptr { 83 | for n := 1 << 8; ; n *= 2 { 84 | buf := make([]uintptr, n) 85 | n := runtime.Callers(skipDepth+2, buf) 86 | if n < len(buf) { 87 | return buf[:n] 88 | } 89 | } 90 | } 91 | 92 | // pruneFrames removes the topmost skipDepth frames of the first goroutine in a 93 | // textual stack dump. It overwrites the passed-in slice. 94 | // 95 | // If there are fewer than skipDepth frames in the first goroutine's stack, 96 | // pruneFrames prunes it to an empty stack and leaves the remaining contents 97 | // intact. 98 | func pruneFrames(skipDepth int, stack []byte) []byte { 99 | headerLen := 0 100 | for i, c := range stack { 101 | if c == '\n' { 102 | headerLen = i + 1 103 | break 104 | } 105 | } 106 | if headerLen == 0 { 107 | return stack // No header line - not a well-formed stack trace. 108 | } 109 | 110 | skipLen := headerLen 111 | skipNewlines := skipDepth * 2 112 | for ; skipLen < len(stack) && skipNewlines > 0; skipLen++ { 113 | c := stack[skipLen] 114 | if c != '\n' { 115 | continue 116 | } 117 | skipNewlines-- 118 | skipLen++ 119 | if skipNewlines == 0 || skipLen == len(stack) || stack[skipLen] == '\n' { 120 | break 121 | } 122 | } 123 | 124 | pruned := stack[skipLen-headerLen:] 125 | copy(pruned, stack[:headerLen]) 126 | return pruned 127 | } 128 | -------------------------------------------------------------------------------- /internal/stackdump/stackdump_test.go: -------------------------------------------------------------------------------- 1 | // stackdump_test checks that the heuristics the stackdump package applies to 2 | // prune frames work as expected in production Go compilers. 3 | 4 | package stackdump_test 5 | 6 | import ( 7 | "bytes" 8 | "fmt" 9 | "regexp" 10 | "runtime" 11 | "testing" 12 | 13 | "github.com/golang/glog/internal/stackdump" 14 | ) 15 | 16 | var file string 17 | 18 | func init() { 19 | _, file, _, _ = runtime.Caller(0) 20 | } 21 | 22 | func TestCallerText(t *testing.T) { 23 | stack := stackdump.CallerText(0) 24 | _, _, line, _ := runtime.Caller(0) 25 | line-- 26 | 27 | wantRE := regexp.MustCompile(fmt.Sprintf( 28 | `^goroutine \d+ \[running\]: 29 | github.com/golang/glog/internal/stackdump_test\.TestCallerText(\([^)]*\))? 30 | %v:%v.* 31 | `, file, line)) 32 | if !wantRE.Match(stack) { 33 | t.Errorf("Stack dump:\n%s\nwant matching regexp:\n%s", stack, wantRE.String()) 34 | 35 | buf := make([]byte, len(stack)*2) 36 | origStack := buf[:runtime.Stack(buf, false)] 37 | t.Logf("Unpruned stack:\n%s", origStack) 38 | } 39 | } 40 | 41 | func callerAt(calls int, depth int) (stack []byte) { 42 | if calls == 1 { 43 | return stackdump.CallerText(depth) 44 | } 45 | return callerAt(calls-1, depth) 46 | } 47 | 48 | func TestCallerTextSkip(t *testing.T) { 49 | const calls = 3 50 | cases := []struct { 51 | depth int 52 | callerAtFrames int 53 | wantEndOfStack bool 54 | }{ 55 | {depth: 0, callerAtFrames: calls}, 56 | {depth: calls - 1, callerAtFrames: 1}, 57 | {depth: calls, callerAtFrames: 0}, 58 | {depth: calls + 1, callerAtFrames: 0}, 59 | {depth: calls + 100, wantEndOfStack: true}, 60 | } 61 | 62 | for _, tc := range cases { 63 | stack := callerAt(calls, tc.depth) 64 | 65 | wantREBuf := bytes.NewBuffer(nil) 66 | fmt.Fprintf(wantREBuf, `^goroutine \d+ \[running\]: 67 | `) 68 | if tc.wantEndOfStack { 69 | fmt.Fprintf(wantREBuf, "\n|$") 70 | } else { 71 | for n := tc.callerAtFrames; n > 0; n-- { 72 | fmt.Fprintf(wantREBuf, `github.com/golang/glog/internal/stackdump_test\.callerAt(\([^)]*\))? 73 | %v:\d+.* 74 | `, file) 75 | } 76 | 77 | if tc.depth <= calls { 78 | fmt.Fprintf(wantREBuf, `github.com/golang/glog/internal/stackdump_test\.TestCallerTextSkip(\([^)]*\))? 79 | %v:\d+.* 80 | `, file) 81 | } 82 | } 83 | 84 | wantRE := regexp.MustCompile(wantREBuf.String()) 85 | 86 | if !wantRE.Match(stack) { 87 | t.Errorf("for %v calls, stackdump.CallerText(%v) =\n%s\n\nwant matching regexp:\n%s", calls, tc.depth, stack, wantRE.String()) 88 | } 89 | } 90 | } 91 | 92 | func pcAt(calls int, depth int) (stack []uintptr) { 93 | if calls == 1 { 94 | return stackdump.CallerPC(depth) 95 | } 96 | stack = pcAt(calls-1, depth) 97 | runtime.Gosched() // Thwart tail-call optimization. 98 | return stack 99 | } 100 | 101 | func TestCallerPC(t *testing.T) { 102 | const calls = 3 103 | cases := []struct { 104 | depth int 105 | pcAtFrames int 106 | wantEndOfStack bool 107 | }{ 108 | {depth: 0, pcAtFrames: calls}, 109 | {depth: calls - 1, pcAtFrames: 1}, 110 | {depth: calls, pcAtFrames: 0}, 111 | {depth: calls + 1, pcAtFrames: 0}, 112 | {depth: calls + 100, wantEndOfStack: true}, 113 | } 114 | 115 | for _, tc := range cases { 116 | stack := pcAt(calls, tc.depth) 117 | if tc.wantEndOfStack { 118 | if len(stack) != 0 { 119 | t.Errorf("for %v calls, stackdump.CallerPC(%v) =\n%q\nwant []", calls, tc.depth, stack) 120 | } 121 | continue 122 | } 123 | 124 | wantFuncs := []string{} 125 | for n := tc.pcAtFrames; n > 0; n-- { 126 | wantFuncs = append(wantFuncs, `github.com/golang/glog/internal/stackdump_test\.pcAt$`) 127 | } 128 | if tc.depth <= calls { 129 | wantFuncs = append(wantFuncs, `^github.com/golang/glog/internal/stackdump_test\.TestCallerPC$`) 130 | } 131 | 132 | gotFuncs := []string{} 133 | for _, pc := range stack { 134 | gotFuncs = append(gotFuncs, runtime.FuncForPC(pc).Name()) 135 | } 136 | if len(gotFuncs) > len(wantFuncs) { 137 | gotFuncs = gotFuncs[:len(wantFuncs)] 138 | } 139 | 140 | ok := true 141 | for i, want := range wantFuncs { 142 | re := regexp.MustCompile(want) 143 | if i >= len(gotFuncs) || !re.MatchString(gotFuncs[i]) { 144 | ok = false 145 | break 146 | } 147 | } 148 | if !ok { 149 | t.Errorf("for %v calls, stackdump.CallerPC(%v) =\n%q\nwant %q", calls, tc.depth, gotFuncs, wantFuncs) 150 | } 151 | } 152 | } 153 | --------------------------------------------------------------------------------