log.go 8.1 KB

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