log.go 10 KB

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