github.com/binkynet/BinkyNet@v1.12.1-0.20240421190447-da4e34c20be0/netlog/logger.go (about)

     1  // Copyright 2021 Ewout Prangsma
     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  // Author Ewout Prangsma
    16  //
    17  
    18  package netlog
    19  
    20  import (
    21  	"fmt"
    22  	"log"
    23  	"net"
    24  	"time"
    25  
    26  	"github.com/rs/zerolog"
    27  )
    28  
    29  // NetLogger send log messages over UDP.
    30  type NetLogger struct {
    31  	conn *net.UDPConn
    32  	buf  chan netLogMsg
    33  }
    34  
    35  type netLogMsg struct {
    36  	Level zerolog.Level
    37  	Msg   []byte
    38  }
    39  
    40  // NewLogger constructs a new UDP logger
    41  func NewLogger() (*NetLogger, error) {
    42  	addr, err := net.ResolveUDPAddr("udp", logAddr)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	c, err := net.DialUDP("udp", nil, addr)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	l := &NetLogger{
    51  		conn: c,
    52  		buf:  make(chan netLogMsg, 64),
    53  	}
    54  	go l.run()
    55  	return l, nil
    56  }
    57  
    58  const (
    59  	logAddr = "224.6.3.1:9832"
    60  )
    61  
    62  var _ zerolog.LevelWriter = &NetLogger{}
    63  
    64  // Write a std message
    65  func (l *NetLogger) Write(p []byte) (int, error) {
    66  	return l.WriteLevel(zerolog.InfoLevel, p)
    67  }
    68  
    69  // Write a message with given level
    70  func (l *NetLogger) WriteLevel(level zerolog.Level, p []byte) (n int, err error) {
    71  	select {
    72  	case l.buf <- netLogMsg{Level: level, Msg: p}:
    73  		return len(p), nil
    74  	default:
    75  		return 0, fmt.Errorf("Buffer full")
    76  	}
    77  }
    78  
    79  // Write a message with given level
    80  func (l *NetLogger) run() {
    81  	buf := make([]byte, maxDatagramSize)
    82  	for msg := range l.buf {
    83  		buf[0] = byte(msg.Level)
    84  		actualLen := copy(buf[1:], msg.Msg)
    85  		l.conn.SetWriteDeadline(time.Now().Add(time.Second / 4))
    86  		if _, err := l.conn.Write(buf[:1+actualLen]); err != nil {
    87  			log.Printf("Write failed: %s\n", err)
    88  		}
    89  	}
    90  }