log.go 6.6 KB

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