log.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. // CommonLogger wraps a TraceLogger instance with an interface that conforms
  151. // to common.Logger. This is used to make the TraceLogger available to other
  152. // packages that don't import the "server" package.
  153. func CommonLogger(traceLogger *TraceLogger) *commonLogger {
  154. return &commonLogger{
  155. traceLogger: traceLogger,
  156. }
  157. }
  158. // NewLogWriter returns an io.PipeWriter that can be used to write
  159. // to the global logger. Caller must Close() the writer.
  160. func NewLogWriter() *io.PipeWriter {
  161. return log.Writer()
  162. }
  163. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  164. type CustomJSONFormatter struct {
  165. }
  166. var (
  167. useLogCallback int32
  168. logCallback atomic.Value
  169. )
  170. // setLogCallback sets a callback that is invoked with each JSON log message.
  171. // This facility is intended for use in testing only.
  172. func setLogCallback(callback func([]byte)) {
  173. if callback == nil {
  174. atomic.StoreInt32(&useLogCallback, 0)
  175. return
  176. }
  177. atomic.StoreInt32(&useLogCallback, 1)
  178. logCallback.Store(callback)
  179. }
  180. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  181. // Format implements logrus.Formatter. This is a customized version
  182. // of the standard logrus.JSONFormatter adapted from:
  183. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  184. //
  185. // The changes are:
  186. // - "time" is renamed to "timestamp"
  187. // - there's an option to omit the standard "msg" and "level" fields
  188. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  189. data := make(logrus.Fields, len(entry.Data)+3)
  190. for k, v := range entry.Data {
  191. switch v := v.(type) {
  192. case error:
  193. // Otherwise errors are ignored by `encoding/json`
  194. // https://github.com/Sirupsen/logrus/issues/137
  195. data[k] = v.Error()
  196. default:
  197. data[k] = v
  198. }
  199. }
  200. if t, ok := data["timestamp"]; ok {
  201. data["fields.timestamp"] = t
  202. }
  203. data["timestamp"] = entry.Time.Format(time.RFC3339)
  204. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  205. if m, ok := data["msg"]; ok {
  206. data["fields.msg"] = m
  207. }
  208. if l, ok := data["level"]; ok {
  209. data["fields.level"] = l
  210. }
  211. data["msg"] = entry.Message
  212. data["level"] = entry.Level.String()
  213. }
  214. serialized, err := json.Marshal(data)
  215. if err != nil {
  216. return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err)
  217. }
  218. if atomic.LoadInt32(&useLogCallback) == 1 {
  219. logCallback.Load().(func([]byte))(serialized)
  220. }
  221. return append(serialized, '\n'), nil
  222. }
  223. var log *TraceLogger
  224. var logHostID, logHostProvider, logBuildRev string
  225. var initLogging sync.Once
  226. // InitLogging configures a logger according to the specified
  227. // config params. If not called, the default logger set by the
  228. // package init() is used.
  229. // Concurrency notes: this should only be called from the main
  230. // goroutine; InitLogging only has effect on the first call, as
  231. // the logging facilities it initializes may be in use by other
  232. // goroutines after that point.
  233. func InitLogging(config *Config) (retErr error) {
  234. initLogging.Do(func() {
  235. logHostID = config.HostID
  236. logHostProvider = config.HostProvider
  237. logBuildRev = buildinfo.GetBuildInfo().BuildRev
  238. level, err := logrus.ParseLevel(config.LogLevel)
  239. if err != nil {
  240. retErr = errors.Trace(err)
  241. return
  242. }
  243. var logWriter io.Writer
  244. if config.LogFilename != "" {
  245. retries, create, mode := config.GetLogFileReopenConfig()
  246. logWriter, err = rotate.NewRotatableFileWriter(
  247. config.LogFilename, retries, create, mode)
  248. if err != nil {
  249. retErr = errors.Trace(err)
  250. return
  251. }
  252. if !config.SkipPanickingLogWriter {
  253. // Use PanickingLogWriter, which will intentionally
  254. // panic when a Write fails. Set SkipPanickingLogWriter
  255. // if this behavior is not desired.
  256. //
  257. // Note that NewRotatableFileWriter will first attempt
  258. // a retry when a Write fails.
  259. //
  260. // It is assumed that continuing operation while unable
  261. // to log is unacceptable; and that the psiphond service
  262. // is managed and will restart when it terminates.
  263. //
  264. // It is further assumed that panicking will result in
  265. // an error that is externally logged and reported to a
  266. // monitoring system.
  267. //
  268. // TODO: An orderly shutdown may be preferred, as some
  269. // data will be lost in a panic (e.g., server_tunnel logs).
  270. // It may be possible to perform an orderly shutdown first
  271. // and then panic, or perform an orderly shutdown and
  272. // simulate a panic message that will be reported.
  273. logWriter = NewPanickingLogWriter(config.LogFilename, logWriter)
  274. }
  275. } else {
  276. logWriter = os.Stderr
  277. }
  278. log = &TraceLogger{
  279. &logrus.Logger{
  280. Out: logWriter,
  281. Formatter: &CustomJSONFormatter{},
  282. Level: level,
  283. },
  284. }
  285. })
  286. return retErr
  287. }
  288. func IsLogLevelDebug() bool {
  289. return log.Logger.Level == logrus.DebugLevel
  290. }
  291. func init() {
  292. // Suppress standard "log" package logging performed by other packages.
  293. // For example, "net/http" logs messages such as:
  294. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  295. go_log.SetOutput(ioutil.Discard)
  296. log = &TraceLogger{
  297. &logrus.Logger{
  298. Out: os.Stderr,
  299. Formatter: &CustomJSONFormatter{},
  300. Hooks: make(logrus.LevelHooks),
  301. Level: logrus.DebugLevel,
  302. },
  303. }
  304. }