log.go 8.8 KB

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