log.go 9.9 KB

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