log.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package log
  2. import (
  3. "encoding/json"
  4. "io"
  5. "log"
  6. "github.com/k0kubun/pp/v3"
  7. "github.com/pkg/errors"
  8. )
  9. func Error(f string, err error, params ...interface{}) error {
  10. err = errors.Wrap(err, f)
  11. log.Default().Println(err)
  12. for _, param := range params {
  13. switch param.(type) {
  14. case string:
  15. log.Default().Println(param)
  16. default:
  17. b, e := json.MarshalIndent(param, "", " ")
  18. if e != nil {
  19. continue
  20. }
  21. log.Default().Println(string(b))
  22. }
  23. }
  24. return err
  25. }
  26. func Errorf(e error, f string, a ...interface{}) {
  27. e = errors.Wrapf(e, f, a...)
  28. if e != nil {
  29. log.Default().Println(e.Error())
  30. }
  31. }
  32. func ErrorJ(e error, a ...interface{}) {
  33. if e == nil {
  34. return
  35. } else {
  36. log.Default().Println(e.Error())
  37. for _, v := range a {
  38. switch v.(type) {
  39. case string:
  40. log.Default().Println(v)
  41. default:
  42. pp.Print(v)
  43. }
  44. }
  45. }
  46. }
  47. func Info(p ...interface{}) {
  48. // log.Default().Print(msg)
  49. var b []byte
  50. var e error
  51. for _, v := range p {
  52. b, e = json.MarshalIndent(v, "", " ")
  53. if e != nil {
  54. Error("log Infof:", e, v)
  55. return
  56. }
  57. log.Default().Printf("%s\n", string(b))
  58. }
  59. }
  60. func Printf(format string, v ...interface{}) {
  61. log.Default().Printf(format, v...)
  62. }
  63. func Print(v ...interface{}) {
  64. log.Default().Println(v...)
  65. }
  66. func Fatal(method string, err error, params ...interface{}) error {
  67. err = errors.Wrap(err, method+" error: ")
  68. log.Default().Fatalln(err)
  69. for _, param := range params {
  70. b, e := json.MarshalIndent(param, "", " ")
  71. if e != nil {
  72. continue
  73. }
  74. log.Default().Println(string(b))
  75. }
  76. return err
  77. }
  78. func PrettyStruct(p interface{}, r interface{}) {
  79. b := p.(string)
  80. e := json.Unmarshal([]byte(b), r)
  81. if e != nil {
  82. Error("log PrettyStruct:", e, p)
  83. }
  84. pp.Print(r)
  85. }
  86. func InfoS(p ...interface{}) {
  87. for _, v := range p {
  88. pp.Print(v)
  89. }
  90. }
  91. func New(out io.Writer, prefix string) *log.Logger {
  92. flag := log.LstdFlags
  93. return log.New(out, prefix, flag)
  94. }
  95. func Path(path string) {
  96. log.Default().Println(path)
  97. }
  98. func Wrapf(err error, m string, a ...interface{}) error {
  99. return errors.Wrapf(err, m, a...)
  100. }