log.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. type commonLogger struct {
  109. contextLogger *ContextLogger
  110. }
  111. func (logger *commonLogger) WithContext() common.LogContext {
  112. // Patch context to be correct parent
  113. return logger.contextLogger.WithContext().WithField("context", common.GetParentContext())
  114. }
  115. func (logger *commonLogger) WithContextFields(fields common.LogFields) common.LogContext {
  116. // Patch context to be correct parent
  117. return logger.contextLogger.WithContextFields(LogFields(fields)).WithField("context", common.GetParentContext())
  118. }
  119. func (logger *commonLogger) LogMetric(metric string, fields common.LogFields) {
  120. fields["event_name"] = metric
  121. logger.contextLogger.LogRawFieldsWithTimestamp(LogFields(fields))
  122. }
  123. // CommonLogger wraps a ContextLogger instance with an interface
  124. // that conforms to common.Logger. This is used to make the ContextLogger
  125. // available to other packages that don't import the "server" package.
  126. func CommonLogger(contextLogger *ContextLogger) *commonLogger {
  127. return &commonLogger{
  128. contextLogger: contextLogger,
  129. }
  130. }
  131. // NewLogWriter returns an io.PipeWriter that can be used to write
  132. // to the global logger. Caller must Close() the writer.
  133. func NewLogWriter() *io.PipeWriter {
  134. return log.Writer()
  135. }
  136. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  137. type CustomJSONFormatter struct {
  138. }
  139. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  140. // Format implements logrus.Formatter. This is a customized version
  141. // of the standard logrus.JSONFormatter adapted from:
  142. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  143. //
  144. // The changes are:
  145. // - "time" is renamed to "timestamp"
  146. // - there's an option to omit the standard "msg" and "level" fields
  147. //
  148. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  149. data := make(logrus.Fields, len(entry.Data)+3)
  150. for k, v := range entry.Data {
  151. switch v := v.(type) {
  152. case error:
  153. // Otherwise errors are ignored by `encoding/json`
  154. // https://github.com/Sirupsen/logrus/issues/137
  155. data[k] = v.Error()
  156. default:
  157. data[k] = v
  158. }
  159. }
  160. if t, ok := data["timestamp"]; ok {
  161. data["fields.timestamp"] = t
  162. }
  163. data["timestamp"] = entry.Time.Format(logrus.DefaultTimestampFormat)
  164. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  165. if m, ok := data["msg"]; ok {
  166. data["fields.msg"] = m
  167. }
  168. if l, ok := data["level"]; ok {
  169. data["fields.level"] = l
  170. }
  171. data["msg"] = entry.Message
  172. data["level"] = entry.Level.String()
  173. }
  174. serialized, err := json.Marshal(data)
  175. if err != nil {
  176. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  177. }
  178. return append(serialized, '\n'), nil
  179. }
  180. var log *ContextLogger
  181. var logHostID, logBuildRev string
  182. var initLogging sync.Once
  183. // InitLogging configures a logger according to the specified
  184. // config params. If not called, the default logger set by the
  185. // package init() is used.
  186. // Concurrency notes: this should only be called from the main
  187. // goroutine; InitLogging only has effect on the first call, as
  188. // the logging facilities it initializes may be in use by other
  189. // goroutines after that point.
  190. func InitLogging(config *Config) (retErr error) {
  191. initLogging.Do(func() {
  192. logHostID = config.HostID
  193. logBuildRev = common.GetBuildInfo().BuildRev
  194. level, err := logrus.ParseLevel(config.LogLevel)
  195. if err != nil {
  196. retErr = common.ContextError(err)
  197. return
  198. }
  199. var logWriter io.Writer
  200. if config.LogFilename != "" {
  201. logWriter, err = rotate.NewRotatableFileWriter(config.LogFilename, 0666)
  202. if err != nil {
  203. retErr = common.ContextError(err)
  204. return
  205. }
  206. if !config.SkipPanickingLogWriter {
  207. // Use PanickingLogWriter, which will intentionally
  208. // panic when a Write fails. Set SkipPanickingLogWriter
  209. // if this behavior is not desired.
  210. //
  211. // Note that NewRotatableFileWriter will first attempt
  212. // a retry when a Write fails.
  213. //
  214. // It is assumed that continuing operation while unable
  215. // to log is unacceptable; and that the psiphond service
  216. // is managed and will restart when it terminates.
  217. //
  218. // It is further assumed that panicking will result in
  219. // an error that is externally logged and reported to a
  220. // monitoring system.
  221. //
  222. // TODO: An orderly shutdown may be preferred, as some
  223. // data will be lost in a panic (e.g., server_tunnel logs).
  224. // It may be possible to perform an orderly shutdown first
  225. // and then panic, or perform an orderly shutdown and
  226. // simulate a panic message that will be reported.
  227. logWriter = NewPanickingLogWriter(config.LogFilename, logWriter)
  228. }
  229. } else {
  230. logWriter = os.Stderr
  231. }
  232. log = &ContextLogger{
  233. &logrus.Logger{
  234. Out: logWriter,
  235. Formatter: &CustomJSONFormatter{},
  236. Level: level,
  237. },
  238. }
  239. })
  240. return retErr
  241. }
  242. func init() {
  243. // Suppress standard "log" package logging performed by other packages.
  244. // For example, "net/http" logs messages such as:
  245. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  246. go_log.SetOutput(ioutil.Discard)
  247. log = &ContextLogger{
  248. &logrus.Logger{
  249. Out: os.Stderr,
  250. Formatter: &CustomJSONFormatter{},
  251. Hooks: make(logrus.LevelHooks),
  252. Level: logrus.DebugLevel,
  253. },
  254. }
  255. }