logging.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains code related to discordgo package logging
  7. package discordgo
  8. import (
  9. "bytes"
  10. "encoding/json"
  11. "fmt"
  12. "log"
  13. "runtime"
  14. "strings"
  15. )
  16. const (
  17. LogError int = iota
  18. LogWarning
  19. LogNotice
  20. LogDebug
  21. )
  22. // TODO: Merge util.go code into here
  23. // dumps debug information to stdout
  24. func msglog(cfgL, msgL int, format string, a ...interface{}) {
  25. if msgL > cfgL {
  26. return
  27. }
  28. pc, file, line, _ := runtime.Caller(1)
  29. files := strings.Split(file, "/")
  30. file = files[len(files)-1]
  31. name := runtime.FuncForPC(pc).Name()
  32. fns := strings.Split(name, ".")
  33. name = fns[len(fns)-1]
  34. msg := fmt.Sprintf(format, a...)
  35. log.Printf("%s:%d:%s %s\n", file, line, name, msg)
  36. }
  37. func (s *Session) log(msgL int, format string, a ...interface{}) {
  38. if s.Debug { // Deprecated
  39. s.LogLevel = LogDebug
  40. }
  41. msglog(s.LogLevel, msgL, format, a...)
  42. }
  43. func (v *VoiceConnection) log(msgL int, format string, a ...interface{}) {
  44. if v.Debug { // Deprecated
  45. v.LogLevel = LogDebug
  46. }
  47. msglog(v.LogLevel, msgL, format, a...)
  48. }
  49. // printEvent prints out a WSAPI event.
  50. func printEvent(e *Event) {
  51. log.Println(fmt.Sprintf("Event. Type: %s, State: %d Operation: %d Direction: %d", e.Type, e.State, e.Operation, e.Direction))
  52. printJSON(e.RawData)
  53. }
  54. // printJSON is a helper function to display JSON data in a easy to read format.
  55. func printJSON(body []byte) {
  56. var prettyJSON bytes.Buffer
  57. error := json.Indent(&prettyJSON, body, "", "\t")
  58. if error != nil {
  59. log.Print("JSON parse error: ", error)
  60. }
  61. log.Println(string(prettyJSON.Bytes()))
  62. }