dbg.go 1.2 KB

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