debug.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package debug
  14. import (
  15. "io"
  16. "os"
  17. "path"
  18. )
  19. // Provider specified the interface types must implement to be used as a
  20. // debugging sink. Having multiple such sink implementations allows it to be
  21. // changed externally (for example when running tests).
  22. type Provider interface {
  23. NewFile(s string) io.WriteCloser
  24. Flush()
  25. }
  26. var currentProvider Provider = nil
  27. func SetProvider(p Provider) {
  28. if currentProvider != nil {
  29. currentProvider.Flush()
  30. }
  31. currentProvider = p
  32. }
  33. // Enabled returns whether debugging is enabled or not.
  34. func Enabled() bool {
  35. return currentProvider != nil
  36. }
  37. // NewFile dispatches to the current provider's NewFile function.
  38. func NewFile(s string) io.WriteCloser {
  39. return currentProvider.NewFile(s)
  40. }
  41. // Flush dispatches to the current provider's Flush function.
  42. func Flush() {
  43. currentProvider.Flush()
  44. }
  45. // FileProvider implements a debugging provider that creates a real file for
  46. // every call to NewFile. It maintains a list of all files that it creates,
  47. // such that it can close them when its Flush function is called.
  48. type FileProvider struct {
  49. Path string
  50. files []*os.File
  51. }
  52. func (fp *FileProvider) NewFile(p string) io.WriteCloser {
  53. f, err := os.Create(path.Join(fp.Path, p))
  54. if err != nil {
  55. panic(err)
  56. }
  57. fp.files = append(fp.files, f)
  58. return f
  59. }
  60. func (fp *FileProvider) Flush() {
  61. for _, f := range fp.files {
  62. f.Close()
  63. }
  64. }