log.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. "sync"
  28. "github.com/Psiphon-Inc/logrus"
  29. "github.com/Psiphon-Inc/rotate-safe-writer"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. // ContextLogger adds context logging functionality to the
  33. // underlying logging packages.
  34. type ContextLogger struct {
  35. *logrus.Logger
  36. }
  37. // LogFields is an alias for the field struct in the
  38. // underlying logging package.
  39. type LogFields logrus.Fields
  40. // WithContext adds a "context" field containing the caller's
  41. // function name and source file line number; and "host_id" and
  42. // "build_rev" fields identifying this server and build.
  43. // Use this function when the log has no fields.
  44. func (logger *ContextLogger) WithContext() *logrus.Entry {
  45. return logger.WithFields(
  46. logrus.Fields{
  47. "context": common.GetParentContext(),
  48. "host_id": logHostID,
  49. "build_rev": logBuildRev,
  50. })
  51. }
  52. func renameLogFields(fields LogFields) {
  53. if _, ok := fields["context"]; ok {
  54. fields["fields.context"] = fields["context"]
  55. }
  56. if _, ok := fields["host_id"]; ok {
  57. fields["fields.host_id"] = fields["host_id"]
  58. }
  59. if _, ok := fields["build_rev"]; ok {
  60. fields["fields.build_rev"] = fields["build_rev"]
  61. }
  62. }
  63. // WithContextFields adds a "context" field containing the caller's
  64. // function name and source file line number; and "host_id" and
  65. // "build_rev" fields identifying this server and build.
  66. // Use this function when the log has fields.
  67. // Note that any existing "context"/"host_id"/"build_rev" field will
  68. // be renamed to "field.<name>".
  69. func (logger *ContextLogger) WithContextFields(fields LogFields) *logrus.Entry {
  70. renameLogFields(fields)
  71. fields["context"] = common.GetParentContext()
  72. fields["host_id"] = logHostID
  73. fields["build_rev"] = logBuildRev
  74. return logger.WithFields(logrus.Fields(fields))
  75. }
  76. // LogRawFieldsWithTimestamp directly logs the supplied fields adding only
  77. // an additional "timestamp" field; and "host_id" and "build_rev" fields
  78. // identifying this server and build. The stock "msg" and "level" fields are
  79. // omitted. This log is emitted at the Error level. This function exists to
  80. // support API logs which have neither a natural message nor severity; and
  81. // omitting these values here makes it easier to ship these logs to existing
  82. // API log consumers.
  83. // Note that any existing "context"/"host_id"/"build_rev" field will
  84. // be renamed to "field.<name>".
  85. func (logger *ContextLogger) LogRawFieldsWithTimestamp(fields LogFields) {
  86. renameLogFields(fields)
  87. fields["host_id"] = logHostID
  88. fields["build_rev"] = logBuildRev
  89. logger.WithFields(logrus.Fields(fields)).Error(
  90. customJSONFormatterLogRawFieldsWithTimestamp)
  91. }
  92. // LogPanicRecover calls LogRawFieldsWithTimestamp with standard fields
  93. // for logging recovered panics.
  94. func (logger *ContextLogger) LogPanicRecover(recoverValue interface{}, stack []byte) {
  95. log.LogRawFieldsWithTimestamp(
  96. LogFields{
  97. "event_name": "panic",
  98. "recover_value": recoverValue,
  99. "stack": string(stack),
  100. })
  101. }
  102. // NewLogWriter returns an io.PipeWriter that can be used to write
  103. // to the global logger. Caller must Close() the writer.
  104. func NewLogWriter() *io.PipeWriter {
  105. return log.Writer()
  106. }
  107. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  108. type CustomJSONFormatter struct {
  109. }
  110. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  111. // Format implements logrus.Formatter. This is a customized version
  112. // of the standard logrus.JSONFormatter adapted from:
  113. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  114. //
  115. // The changes are:
  116. // - "time" is renamed to "timestamp"
  117. // - there's an option to omit the standard "msg" and "level" fields
  118. //
  119. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  120. data := make(logrus.Fields, len(entry.Data)+3)
  121. for k, v := range entry.Data {
  122. switch v := v.(type) {
  123. case error:
  124. // Otherwise errors are ignored by `encoding/json`
  125. // https://github.com/Sirupsen/logrus/issues/137
  126. data[k] = v.Error()
  127. default:
  128. data[k] = v
  129. }
  130. }
  131. if t, ok := data["timestamp"]; ok {
  132. data["fields.timestamp"] = t
  133. }
  134. data["timestamp"] = entry.Time.Format(logrus.DefaultTimestampFormat)
  135. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  136. if m, ok := data["msg"]; ok {
  137. data["fields.msg"] = m
  138. }
  139. if l, ok := data["level"]; ok {
  140. data["fields.level"] = l
  141. }
  142. data["msg"] = entry.Message
  143. data["level"] = entry.Level.String()
  144. }
  145. serialized, err := json.Marshal(data)
  146. if err != nil {
  147. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  148. }
  149. return append(serialized, '\n'), nil
  150. }
  151. var log *ContextLogger
  152. var logHostID, logBuildRev string
  153. var initLogging sync.Once
  154. // InitLogging configures a logger according to the specified
  155. // config params. If not called, the default logger set by the
  156. // package init() is used.
  157. // Concurrency notes: this should only be called from the main
  158. // goroutine; InitLogging only has effect on the first call, as
  159. // the logging facilities it initializes may be in use by other
  160. // goroutines after that point.
  161. func InitLogging(config *Config) (retErr error) {
  162. initLogging.Do(func() {
  163. logHostID = config.HostID
  164. logBuildRev = common.GetBuildInfo().BuildRev
  165. level, err := logrus.ParseLevel(config.LogLevel)
  166. if err != nil {
  167. retErr = common.ContextError(err)
  168. return
  169. }
  170. var logWriter io.Writer
  171. if config.LogFilename != "" {
  172. logWriter, err = rotate.NewRotatableFileWriter(config.LogFilename, 0666)
  173. if err != nil {
  174. retErr = common.ContextError(err)
  175. return
  176. }
  177. } else {
  178. logWriter = os.Stderr
  179. }
  180. log = &ContextLogger{
  181. &logrus.Logger{
  182. Out: logWriter,
  183. Formatter: &CustomJSONFormatter{},
  184. Level: level,
  185. },
  186. }
  187. })
  188. return retErr
  189. }
  190. func init() {
  191. // Suppress standard "log" package logging performed by other packages.
  192. // For example, "net/http" logs messages such as:
  193. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  194. go_log.SetOutput(ioutil.Discard)
  195. log = &ContextLogger{
  196. &logrus.Logger{
  197. Out: os.Stderr,
  198. Formatter: &CustomJSONFormatter{},
  199. Hooks: make(logrus.LevelHooks),
  200. Level: logrus.DebugLevel,
  201. },
  202. }
  203. }