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