logger.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package logs
  15. import (
  16. "io"
  17. "sync"
  18. "time"
  19. )
  20. type logWriter struct {
  21. sync.Mutex
  22. writer io.Writer
  23. }
  24. func newLogWriter(wr io.Writer) *logWriter {
  25. return &logWriter{writer: wr}
  26. }
  27. func (lg *logWriter) println(when time.Time, msg string) {
  28. lg.Lock()
  29. h, _ := formatTimeHeader(when)
  30. lg.writer.Write(append(append(h, msg...), '\n'))
  31. lg.Unlock()
  32. }
  33. func formatTimeHeader(when time.Time) ([]byte, int) {
  34. y, mo, d := when.Date()
  35. h, mi, s := when.Clock()
  36. //len(2006/01/02 15:03:04)==19
  37. var buf [20]byte
  38. t := 3
  39. for y >= 10 {
  40. p := y / 10
  41. buf[t] = byte('0' + y - p*10)
  42. y = p
  43. t--
  44. }
  45. buf[0] = byte('0' + y)
  46. buf[4] = '/'
  47. if mo > 9 {
  48. buf[5] = '1'
  49. buf[6] = byte('0' + mo - 9)
  50. } else {
  51. buf[5] = '0'
  52. buf[6] = byte('0' + mo)
  53. }
  54. buf[7] = '/'
  55. t = d / 10
  56. buf[8] = byte('0' + t)
  57. buf[9] = byte('0' + d - t*10)
  58. buf[10] = ' '
  59. t = h / 10
  60. buf[11] = byte('0' + t)
  61. buf[12] = byte('0' + h - t*10)
  62. buf[13] = ':'
  63. t = mi / 10
  64. buf[14] = byte('0' + t)
  65. buf[15] = byte('0' + mi - t*10)
  66. buf[16] = ':'
  67. t = s / 10
  68. buf[17] = byte('0' + t)
  69. buf[18] = byte('0' + s - t*10)
  70. buf[19] = ' '
  71. return buf[0:], d
  72. }