log.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. "io"
  22. "os"
  23. "github.com/Psiphon-Inc/logrus"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  25. )
  26. // ContextLogger adds context logging functionality to the
  27. // underlying logging packages.
  28. type ContextLogger struct {
  29. *logrus.Logger
  30. }
  31. // LogFields is an alias for the field struct in the
  32. // underlying logging package.
  33. type LogFields logrus.Fields
  34. // WithContext adds a "context" field containing the caller's
  35. // function name and source file line number. Use this function
  36. // when the log has no fields.
  37. func (logger *ContextLogger) WithContext() *logrus.Entry {
  38. return logrus.WithFields(
  39. logrus.Fields{
  40. "context": psiphon.GetParentContext(),
  41. })
  42. }
  43. // WithContextFields adds a "context" field containing the caller's
  44. // function name and source file line number. Use this function
  45. // when the log has fields. Note that any existing "context" field
  46. // will be renamed to "field.context".
  47. func (logger *ContextLogger) WithContextFields(fields LogFields) *logrus.Entry {
  48. _, ok := fields["context"]
  49. if ok {
  50. fields["fields.context"] = fields["context"]
  51. }
  52. fields["context"] = psiphon.GetParentContext()
  53. return log.WithFields(logrus.Fields(fields))
  54. }
  55. // NewLogWriter returns an io.PipeWriter that can be used to write
  56. // to the global logger. Caller must Close() the writer.
  57. func NewLogWriter() *io.PipeWriter {
  58. return log.Writer()
  59. }
  60. var log *ContextLogger
  61. func init() {
  62. log = &ContextLogger{
  63. &logrus.Logger{
  64. Out: os.Stderr,
  65. Formatter: new(logrus.TextFormatter),
  66. Hooks: make(logrus.LevelHooks),
  67. Level: logrus.DebugLevel,
  68. },
  69. }
  70. }