log.go 9.5 KB

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