log.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. "github.com/Psiphon-Inc/logrus"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. )
  30. // ContextLogger adds context logging functionality to the
  31. // underlying logging packages.
  32. type ContextLogger struct {
  33. *logrus.Logger
  34. }
  35. // LogFields is an alias for the field struct in the
  36. // underlying logging package.
  37. type LogFields logrus.Fields
  38. // WithContext adds a "context" field containing the caller's
  39. // function name and source file line number. Use this function
  40. // when the log has no fields.
  41. func (logger *ContextLogger) WithContext() *logrus.Entry {
  42. return log.WithFields(
  43. logrus.Fields{
  44. "context": common.GetParentContext(),
  45. })
  46. }
  47. // WithContextFields adds a "context" field containing the caller's
  48. // function name and source file line number. Use this function
  49. // when the log has fields. Note that any existing "context" field
  50. // will be renamed to "field.context".
  51. func (logger *ContextLogger) WithContextFields(fields LogFields) *logrus.Entry {
  52. _, ok := fields["context"]
  53. if ok {
  54. fields["fields.context"] = fields["context"]
  55. }
  56. fields["context"] = common.GetParentContext()
  57. return log.WithFields(logrus.Fields(fields))
  58. }
  59. // LogRawFieldsWithTimestamp directly logs the supplied fields adding only
  60. // an additional "timestamp" field. The stock "msg" and "level" fields are
  61. // omitted. This log is emitted at the Error level. This function exists to
  62. // support API logs which have neither a natural message nor severity; and
  63. // omitting these values here makes it easier to ship these logs to existing
  64. // API log consumers.
  65. func (logger *ContextLogger) LogRawFieldsWithTimestamp(fields LogFields) {
  66. logger.WithFields(logrus.Fields(fields)).Error(
  67. customJSONFormatterLogRawFieldsWithTimestamp)
  68. }
  69. // NewLogWriter returns an io.PipeWriter that can be used to write
  70. // to the global logger. Caller must Close() the writer.
  71. func NewLogWriter() *io.PipeWriter {
  72. return log.Writer()
  73. }
  74. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  75. type CustomJSONFormatter struct {
  76. }
  77. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  78. // Format implements logrus.Formatter. This is a customized version
  79. // of the standard logrus.JSONFormatter adapted from:
  80. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  81. //
  82. // The changes are:
  83. // - "time" is renamed to "timestamp"
  84. // - there's an option to omit the standard "msg" and "level" fields
  85. //
  86. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  87. data := make(logrus.Fields, len(entry.Data)+3)
  88. for k, v := range entry.Data {
  89. switch v := v.(type) {
  90. case error:
  91. // Otherwise errors are ignored by `encoding/json`
  92. // https://github.com/Sirupsen/logrus/issues/137
  93. data[k] = v.Error()
  94. default:
  95. data[k] = v
  96. }
  97. }
  98. if t, ok := data["timestamp"]; ok {
  99. data["fields.timestamp"] = t
  100. }
  101. data["timestamp"] = entry.Time.Format(logrus.DefaultTimestampFormat)
  102. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  103. if m, ok := data["msg"]; ok {
  104. data["fields.msg"] = m
  105. }
  106. if l, ok := data["level"]; ok {
  107. data["fields.level"] = l
  108. }
  109. data["msg"] = entry.Message
  110. data["level"] = entry.Level.String()
  111. }
  112. serialized, err := json.Marshal(data)
  113. if err != nil {
  114. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  115. }
  116. return append(serialized, '\n'), nil
  117. }
  118. var log *ContextLogger
  119. // InitLogging configures a logger according to the specified
  120. // config params. If not called, the default logger set by the
  121. // package init() is used.
  122. // Concurrenty note: should only be called from the main
  123. // goroutine.
  124. func InitLogging(config *Config) error {
  125. level, err := logrus.ParseLevel(config.LogLevel)
  126. if err != nil {
  127. return common.ContextError(err)
  128. }
  129. logWriter := os.Stderr
  130. if config.LogFilename != "" {
  131. logWriter, err = os.OpenFile(
  132. config.LogFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
  133. if err != nil {
  134. return common.ContextError(err)
  135. }
  136. }
  137. log = &ContextLogger{
  138. &logrus.Logger{
  139. Out: logWriter,
  140. Formatter: &CustomJSONFormatter{},
  141. Level: level,
  142. },
  143. }
  144. return nil
  145. }
  146. func init() {
  147. // Suppress standard "log" package logging performed by other packages.
  148. // For example, "net/http" logs messages such as:
  149. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  150. go_log.SetOutput(ioutil.Discard)
  151. log = &ContextLogger{
  152. &logrus.Logger{
  153. Out: os.Stderr,
  154. Formatter: &CustomJSONFormatter{},
  155. Hooks: make(logrus.LevelHooks),
  156. Level: logrus.DebugLevel,
  157. },
  158. }
  159. }