mirror of
https://github.com/42wim/matterbridge.git
synced 2024-12-18 17:12:37 +01:00
58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
// Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
|
|
|
|
package log4go
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
)
|
|
|
|
// This log writer sends output to a socket
|
|
type SocketLogWriter chan *LogRecord
|
|
|
|
// This is the SocketLogWriter's output method
|
|
func (w SocketLogWriter) LogWrite(rec *LogRecord) {
|
|
w <- rec
|
|
}
|
|
|
|
func (w SocketLogWriter) Close() {
|
|
close(w)
|
|
}
|
|
|
|
func NewSocketLogWriter(proto, hostport string) SocketLogWriter {
|
|
sock, err := net.Dial(proto, hostport)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err)
|
|
return nil
|
|
}
|
|
|
|
w := SocketLogWriter(make(chan *LogRecord, LogBufferLength))
|
|
|
|
go func() {
|
|
defer func() {
|
|
if sock != nil && proto == "tcp" {
|
|
sock.Close()
|
|
}
|
|
}()
|
|
|
|
for rec := range w {
|
|
// Marshall into JSON
|
|
js, err := json.Marshal(rec)
|
|
if err != nil {
|
|
fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
|
|
return
|
|
}
|
|
|
|
_, err = sock.Write(js)
|
|
if err != nil {
|
|
fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
return w
|
|
}
|