github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/logger/memory_output.go (about)

     1  // Copyright 2021 iLogtail 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  
    15  package logger
    16  
    17  import (
    18  	"sync"
    19  
    20  	"github.com/cihub/seelog"
    21  )
    22  
    23  const maxLines = 1000
    24  
    25  var cursor int
    26  var memLogs = make([]string, maxLines)
    27  var rwLocker sync.RWMutex
    28  
    29  // ReadMemoryLog get log when MemoryWriter working.
    30  func ReadMemoryLog(line int) (msg string, ok bool) {
    31  	rwLocker.RLock()
    32  	defer rwLocker.RUnlock()
    33  	if line > 0 && line <= cursor {
    34  		msg = memLogs[(line-1)%maxLines]
    35  		ok = true
    36  	}
    37  	return
    38  }
    39  
    40  // ClearMemoryLog clear the whole memory logs.
    41  func ClearMemoryLog() {
    42  	rwLocker.Lock()
    43  	defer rwLocker.Unlock()
    44  	memLogs = make([]string, maxLines)
    45  	cursor = 0
    46  }
    47  
    48  // GetMemoryLogCount returns the stored logs count, but only store the recently maxLines items.
    49  func GetMemoryLogCount() int {
    50  	rwLocker.RLock()
    51  	defer rwLocker.RUnlock()
    52  	return cursor
    53  }
    54  
    55  // MemoryWriter provide a easy way to check log in testing.
    56  type MemoryWriter struct {
    57  }
    58  
    59  func (m *MemoryWriter) ReceiveMessage(message string, level seelog.LogLevel, context seelog.LogContextInterface) error {
    60  	rwLocker.Lock()
    61  	defer rwLocker.Unlock()
    62  	memLogs[cursor%maxLines] = message
    63  	cursor++
    64  	return nil
    65  }
    66  
    67  func (m *MemoryWriter) AfterParse(initArgs seelog.CustomReceiverInitArgs) error {
    68  	return nil
    69  }
    70  
    71  func (m *MemoryWriter) Flush() {
    72  }
    73  
    74  func (m *MemoryWriter) Close() error {
    75  	rwLocker.Lock()
    76  	defer rwLocker.Unlock()
    77  	memLogs = make([]string, maxLines)
    78  	cursor = 0
    79  	return nil
    80  }
    81  
    82  func init() {
    83  	seelog.RegisterReceiver("memory", new(MemoryWriter))
    84  }