formater.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2013, Cong Ding. 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. //
  15. // author: Cong Ding <dinggnu@gmail.com>
  16. //
  17. package logging
  18. import (
  19. "errors"
  20. "fmt"
  21. "strings"
  22. )
  23. // pre-defined formats
  24. const (
  25. BasicFormat = "%s [%6s] %30s - %s\n name,levelname,time,message"
  26. RichFormat = "%s [%6s] %d %30s - %d - %s:%s:%d - %s\n name, levelname, seqid, time, thread, filename, funcname, lineno, message"
  27. )
  28. // genLog generates log string from the format setting.
  29. func (logger *Logger) genLog(level Level, message string) string {
  30. fs := make([]interface{}, len(logger.recordArgs))
  31. r := new(record)
  32. r.message = message
  33. r.level = level
  34. for k, v := range logger.recordArgs {
  35. fs[k] = fields[v](logger, r)
  36. }
  37. return fmt.Sprintf(logger.recordFormat, fs...)
  38. }
  39. // parseFormat checks the legality of format and parses it to recordFormat and recordArgs
  40. func (logger *Logger) parseFormat(format string) error {
  41. logger.runtime = false
  42. fts := strings.Split(format, "\n")
  43. if len(fts) != 2 {
  44. return errors.New("logging format error")
  45. }
  46. logger.recordFormat = fts[0]
  47. logger.recordArgs = strings.Split(fts[1], ",")
  48. for k, v := range logger.recordArgs {
  49. tv := strings.TrimSpace(v)
  50. _, ok := fields[tv]
  51. if ok == false {
  52. return errors.New("logging format error")
  53. }
  54. logger.recordArgs[k] = tv
  55. logger.runtime = logger.runtime || runtimeFields[tv]
  56. }
  57. return nil
  58. }