logger.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package tyr
  2. import (
  3. "log"
  4. "os"
  5. )
  6. // Logger logger
  7. type Logger struct {
  8. FP *os.File
  9. Log *log.Logger
  10. }
  11. var (
  12. deflog *Logger
  13. )
  14. // NewDefaultLogger defult logger
  15. func NewDefaultLogger(path string) (*Logger, error) {
  16. var err error
  17. fp := &os.File{}
  18. if fp, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666); err != nil {
  19. return nil, err
  20. }
  21. deflog = &Logger{}
  22. deflog.FP = fp
  23. deflog.Log = log.New(fp, "[INFO]", log.LstdFlags)
  24. return deflog, err
  25. }
  26. // ReopenDefaultLogger re open default logger
  27. func ReopenDefaultLogger(path string) (*Logger, error) {
  28. var err error
  29. fp := &os.File{}
  30. if fp, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666); err != nil {
  31. return nil, err
  32. }
  33. if deflog == nil {
  34. deflog = &Logger{}
  35. }
  36. fpo := deflog.FP
  37. deflog.FP = fp
  38. deflog.Log = log.New(fp, "[INFO]", log.LstdFlags)
  39. fpo.Close()
  40. return deflog, err
  41. }
  42. // CloseDefaultLogger close
  43. func CloseDefaultLogger() error {
  44. return deflog.FP.Close()
  45. }
  46. // LogInfo log info
  47. func LogInfo(v ...interface{}) {
  48. deflog.Log.SetPrefix("[INFO]")
  49. deflog.Log.Println(v...)
  50. }
  51. // LogDebug log debug
  52. func LogDebug(v ...interface{}) {
  53. deflog.Log.SetPrefix("[DEBUG]")
  54. deflog.Log.Println(v...)
  55. }
  56. // NewLogger new
  57. func NewLogger(path string) (logger *Logger, err error) {
  58. fp := &os.File{}
  59. if fp, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, os.ModePerm); err != nil {
  60. return
  61. }
  62. logger.FP = fp
  63. logger.Log = log.New(fp, "[INFO]", log.Ldate|log.Ltime)
  64. return
  65. }
  66. // Close close
  67. func (logger Logger) Close() error {
  68. return logger.FP.Close()
  69. }
  70. // Info log info
  71. func (logger Logger) Info(v ...interface{}) {
  72. logger.Log.SetPrefix("[INFO]")
  73. logger.Log.Println(v...)
  74. }
  75. // Debug log debug
  76. func (logger Logger) Debug(v ...interface{}) {
  77. logger.Log.SetPrefix("[DEBUG]")
  78. logger.Log.Println(v...)
  79. }