github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/logconfig/logger_capture.go (about)

     1  /*
     2   * Copyright (C) 2018 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package logconfig
    19  
    20  import (
    21  	"github.com/rs/zerolog"
    22  	"github.com/rs/zerolog/log"
    23  )
    24  
    25  // LogCapturer captures logging messages to an in-memory slice for accessing later.
    26  // Typical use case is asserting certain log messages in tests.
    27  type LogCapturer struct {
    28  	logs     []string
    29  	original zerolog.Logger
    30  }
    31  
    32  // NewLogCapturer creates a LogCapturer.
    33  func NewLogCapturer() *LogCapturer {
    34  	return &LogCapturer{logs: []string{}}
    35  }
    36  
    37  // Attach attaches LogCapturer hook to the global zerolog instance.
    38  func (l *LogCapturer) Attach() {
    39  	l.original = log.Logger
    40  	log.Logger = log.Logger.Hook(l)
    41  }
    42  
    43  // Detach restores original global zerolog instance.
    44  func (l *LogCapturer) Detach() {
    45  	log.Logger = l.original
    46  }
    47  
    48  // Run appends log message to an in-memory slice (zerolog hook).
    49  func (l *LogCapturer) Run(e *zerolog.Event, level zerolog.Level, message string) {
    50  	l.logs = append(l.logs, message)
    51  }
    52  
    53  // Messages returns all captures log messages.
    54  func (l *LogCapturer) Messages() []string {
    55  	return l.logs
    56  }