log_writer.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package xlog
  15. import "strings"
  16. // LogWriter forwards writes to frp's logger at configurable level.
  17. // It is safe for concurrent use as long as the underlying Logger is thread-safe.
  18. type LogWriter struct {
  19. xl *Logger
  20. logFunc func(string)
  21. }
  22. func (w LogWriter) Write(p []byte) (n int, err error) {
  23. msg := strings.TrimSpace(string(p))
  24. w.logFunc(msg)
  25. return len(p), nil
  26. }
  27. func NewTraceWriter(xl *Logger) LogWriter {
  28. return LogWriter{
  29. xl: xl,
  30. logFunc: func(msg string) { xl.Tracef("%s", msg) },
  31. }
  32. }
  33. func NewDebugWriter(xl *Logger) LogWriter {
  34. return LogWriter{
  35. xl: xl,
  36. logFunc: func(msg string) { xl.Debugf("%s", msg) },
  37. }
  38. }
  39. func NewInfoWriter(xl *Logger) LogWriter {
  40. return LogWriter{
  41. xl: xl,
  42. logFunc: func(msg string) { xl.Infof("%s", msg) },
  43. }
  44. }
  45. func NewWarnWriter(xl *Logger) LogWriter {
  46. return LogWriter{
  47. xl: xl,
  48. logFunc: func(msg string) { xl.Warnf("%s", msg) },
  49. }
  50. }
  51. func NewErrorWriter(xl *Logger) LogWriter {
  52. return LogWriter{
  53. xl: xl,
  54. logFunc: func(msg string) { xl.Errorf("%s", msg) },
  55. }
  56. }