log.go 9.4 KB

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