log.go 5.0 KB

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