diff options
author | msglm <msglm@techchud.xyz> | 2023-10-27 07:08:25 -0500 |
---|---|---|
committer | msglm <msglm@techchud.xyz> | 2023-10-27 07:08:25 -0500 |
commit | 032a7e0c1188d3507b8d9a9571f2446a43cf775b (patch) | |
tree | 2bd38c01bc7761a6195e426082ce7191ebc765a1 /vendor/maunium.net/go/maulogger/v2/writer.go | |
parent | 56e7bd01ca09ad52b0c4f48f146a20a4f1b78696 (diff) | |
download | matterbridge-msglm-032a7e0c1188d3507b8d9a9571f2446a43cf775b.tar.gz matterbridge-msglm-032a7e0c1188d3507b8d9a9571f2446a43cf775b.tar.bz2 matterbridge-msglm-032a7e0c1188d3507b8d9a9571f2446a43cf775b.zip |
apply https://github.com/42wim/matterbridge/pull/1864v1.26.0+0.1.0
Diffstat (limited to 'vendor/maunium.net/go/maulogger/v2/writer.go')
-rw-r--r-- | vendor/maunium.net/go/maulogger/v2/writer.go | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/vendor/maunium.net/go/maulogger/v2/writer.go b/vendor/maunium.net/go/maulogger/v2/writer.go new file mode 100644 index 00000000..8852b857 --- /dev/null +++ b/vendor/maunium.net/go/maulogger/v2/writer.go @@ -0,0 +1,78 @@ +// mauLogger - A logger for Go programs +// Copyright (c) 2021 Tulir Asokan +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package maulogger + +import ( + "bytes" + "io" + "sync" +) + +// LogWriter is a buffered io.Writer that writes lines to a Logger. +type LogWriter struct { + log Logger + lock sync.Mutex + level Level + buf bytes.Buffer +} + +func (log *BasicLogger) Writer(level Level) io.WriteCloser { + return &LogWriter{ + log: log, + level: level, + } +} + +func (log *Sublogger) Writer(level Level) io.WriteCloser { + return &LogWriter{ + log: log, + level: level, + } +} + +func (lw *LogWriter) writeLine(data []byte) { + if lw.buf.Len() == 0 { + if len(data) == 0 { + return + } + lw.log.Logln(lw.level, string(data)) + } else { + lw.buf.Write(data) + lw.log.Logln(lw.level, lw.buf.String()) + lw.buf.Reset() + } +} + +// Write will write lines from the given data to the buffer. If the data doesn't end with a line break, +// everything after the last line break will be buffered until the next Write or Close call. +func (lw *LogWriter) Write(data []byte) (int, error) { + lw.lock.Lock() + newline := bytes.IndexByte(data, '\n') + if newline == len(data)-1 { + lw.writeLine(data[:len(data)-1]) + } else if newline < 0 { + lw.buf.Write(data) + } else { + lines := bytes.Split(data, []byte("\n")) + for _, line := range lines[:len(lines)-1] { + lw.writeLine(line) + } + lw.buf.Write(lines[len(lines)-1]) + } + lw.lock.Unlock() + return len(data), nil +} + +// Close will flush remaining data in the buffer into the logger. +func (lw *LogWriter) Close() error { + lw.lock.Lock() + lw.log.Logln(lw.level, lw.buf.String()) + lw.buf.Reset() + lw.lock.Unlock() + return nil +} |