logging.go 2.1 KB

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