log.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. go_log "log"
  26. "os"
  27. "github.com/Psiphon-Inc/logrus"
  28. "github.com/Psiphon-Inc/rotate-safe-writer"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. )
  31. // ContextLogger adds context logging functionality to the
  32. // underlying logging packages.
  33. type ContextLogger struct {
  34. *logrus.Logger
  35. }
  36. // LogFields is an alias for the field struct in the
  37. // underlying logging package.
  38. type LogFields logrus.Fields
  39. // WithContext adds a "context" field containing the caller's
  40. // function name and source file line number. Use this function
  41. // when the log has no fields.
  42. func (logger *ContextLogger) WithContext() *logrus.Entry {
  43. return log.WithFields(
  44. logrus.Fields{
  45. "context": common.GetParentContext(),
  46. })
  47. }
  48. // WithContextFields adds a "context" field containing the caller's
  49. // function name and source file line number. Use this function
  50. // when the log has fields. Note that any existing "context" field
  51. // will be renamed to "field.context".
  52. func (logger *ContextLogger) WithContextFields(fields LogFields) *logrus.Entry {
  53. _, ok := fields["context"]
  54. if ok {
  55. fields["fields.context"] = fields["context"]
  56. }
  57. fields["context"] = common.GetParentContext()
  58. return log.WithFields(logrus.Fields(fields))
  59. }
  60. // LogRawFieldsWithTimestamp directly logs the supplied fields adding only
  61. // an additional "timestamp" field. The stock "msg" and "level" fields are
  62. // omitted. This log is emitted at the Error level. This function exists to
  63. // support API logs which have neither a natural message nor severity; and
  64. // omitting these values here makes it easier to ship these logs to existing
  65. // API log consumers.
  66. func (logger *ContextLogger) LogRawFieldsWithTimestamp(fields LogFields) {
  67. logger.WithFields(logrus.Fields(fields)).Error(
  68. customJSONFormatterLogRawFieldsWithTimestamp)
  69. }
  70. // NewLogWriter returns an io.PipeWriter that can be used to write
  71. // to the global logger. Caller must Close() the writer.
  72. func NewLogWriter() *io.PipeWriter {
  73. return log.Writer()
  74. }
  75. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  76. type CustomJSONFormatter struct {
  77. }
  78. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  79. // Format implements logrus.Formatter. This is a customized version
  80. // of the standard logrus.JSONFormatter adapted from:
  81. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  82. //
  83. // The changes are:
  84. // - "time" is renamed to "timestamp"
  85. // - there's an option to omit the standard "msg" and "level" fields
  86. //
  87. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  88. data := make(logrus.Fields, len(entry.Data)+3)
  89. for k, v := range entry.Data {
  90. switch v := v.(type) {
  91. case error:
  92. // Otherwise errors are ignored by `encoding/json`
  93. // https://github.com/Sirupsen/logrus/issues/137
  94. data[k] = v.Error()
  95. default:
  96. data[k] = v
  97. }
  98. }
  99. if t, ok := data["timestamp"]; ok {
  100. data["fields.timestamp"] = t
  101. }
  102. data["timestamp"] = entry.Time.Format(logrus.DefaultTimestampFormat)
  103. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  104. if m, ok := data["msg"]; ok {
  105. data["fields.msg"] = m
  106. }
  107. if l, ok := data["level"]; ok {
  108. data["fields.level"] = l
  109. }
  110. data["msg"] = entry.Message
  111. data["level"] = entry.Level.String()
  112. }
  113. serialized, err := json.Marshal(data)
  114. if err != nil {
  115. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  116. }
  117. return append(serialized, '\n'), nil
  118. }
  119. var log *ContextLogger
  120. // InitLogging configures a logger according to the specified
  121. // config params. If not called, the default logger set by the
  122. // package init() is used.
  123. // Concurrenty note: should only be called from the main
  124. // goroutine.
  125. func InitLogging(config *Config) error {
  126. level, err := logrus.ParseLevel(config.LogLevel)
  127. if err != nil {
  128. return common.ContextError(err)
  129. }
  130. var logWriter io.Writer
  131. if config.LogFilename != "" {
  132. logWriter, err = rotate.NewRotatableFileWriter(config.LogFilename, 0666)
  133. if err != nil {
  134. return common.ContextError(err)
  135. }
  136. } else {
  137. logWriter = os.Stderr
  138. }
  139. log = &ContextLogger{
  140. &logrus.Logger{
  141. Out: logWriter,
  142. Formatter: &CustomJSONFormatter{},
  143. Level: level,
  144. },
  145. }
  146. return nil
  147. }
  148. func init() {
  149. // Suppress standard "log" package logging performed by other packages.
  150. // For example, "net/http" logs messages such as:
  151. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  152. go_log.SetOutput(ioutil.Discard)
  153. log = &ContextLogger{
  154. &logrus.Logger{
  155. Out: os.Stderr,
  156. Formatter: &CustomJSONFormatter{},
  157. Hooks: make(logrus.LevelHooks),
  158. Level: logrus.DebugLevel,
  159. },
  160. }
  161. }