logging.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // Logs critical errors that can lead to data loss or panic
  18. // also, only logs errors that would never be returned to
  19. // a calling function. Such as errors within goroutines.
  20. LogError int = iota
  21. // Logs very abnormal events even if they're also returend as
  22. // an error to the calling code.
  23. LogWarning
  24. // Logs normal non-error activity like connect/disconnects
  25. LogInformational
  26. // Logs detailed activity including all HTTP/Websocket packets.
  27. LogDebug
  28. )
  29. // logs messages to stderr
  30. func msglog(cfgL, msgL int, format string, a ...interface{}) {
  31. if msgL > cfgL {
  32. return
  33. }
  34. pc, file, line, _ := runtime.Caller(1)
  35. files := strings.Split(file, "/")
  36. file = files[len(files)-1]
  37. name := runtime.FuncForPC(pc).Name()
  38. fns := strings.Split(name, ".")
  39. name = fns[len(fns)-1]
  40. msg := fmt.Sprintf(format, a...)
  41. log.Printf("%s:%d:%s %s\n", file, line, name, msg)
  42. }
  43. // helper function that wraps msglog for the Session struct
  44. func (s *Session) log(msgL int, format string, a ...interface{}) {
  45. if s.Debug { // Deprecated
  46. s.LogLevel = LogDebug
  47. }
  48. msglog(s.LogLevel, msgL, format, a...)
  49. }
  50. // helper function that wraps msglog for the VoiceConnection struct
  51. func (v *VoiceConnection) log(msgL int, format string, a ...interface{}) {
  52. if v.Debug { // Deprecated
  53. v.LogLevel = LogDebug
  54. }
  55. msglog(v.LogLevel, msgL, format, a...)
  56. }
  57. // printEvent prints out a WSAPI event.
  58. func printEvent(e *Event) {
  59. log.Println(fmt.Sprintf("Event. Type: %s, State: %d Operation: %d Direction: %d", e.Type, e.State, e.Operation, e.Direction))
  60. printJSON(e.RawData)
  61. }
  62. // printJSON is a helper function to display JSON data in a easy to read format.
  63. func printJSON(body []byte) {
  64. var prettyJSON bytes.Buffer
  65. error := json.Indent(&prettyJSON, body, "", "\t")
  66. if error != nil {
  67. log.Print("JSON parse error: ", error)
  68. }
  69. log.Println(string(prettyJSON.Bytes()))
  70. }