| 1 | // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ |
| 2 | // |
| 3 | // Copyright 2013 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 dbg provides some helper code for call traces. |
| 18 | package dbg |
| 19 | |
| 20 | import ( |
| 21 | "runtime" |
| 22 | ) |
| 23 | |
| 24 | // Stacks is a wrapper for runtime.Stack that attempts to recover the data for |
| 25 | // all goroutines or the calling one. |
| 26 | func Stacks(all bool) []byte { |
| 27 | // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. |
| 28 | n := 10000 |
| 29 | if all { |
| 30 | n = 100000 |
| 31 | } |
| 32 | var trace []byte |
| 33 | for i := 0; i < 5; i++ { |
| 34 | trace = make([]byte, n) |
| 35 | nbytes := runtime.Stack(trace, all) |
| 36 | if nbytes < len(trace) { |
| 37 | return trace[:nbytes] |
| 38 | } |
| 39 | n *= 2 |
| 40 | } |
| 41 | return trace |
| 42 | } |