1
0
mirror of https://github.com/taigrr/log-socket synced 2025-01-18 04:53:14 -08:00

Remove mutexes, allow the GC to take care of things

This commit is contained in:
Tai Groot 2021-04-08 17:58:26 -07:00
parent 15a9017e2e
commit 9ff091038a
Signed by: taigrr
GPG Key ID: D00C269A87614812
2 changed files with 40 additions and 10 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"strings" "strings"
"sync"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -21,7 +22,8 @@ const (
) )
var logger = logrus.New() var logger = logrus.New()
var clients []Client var clients []*Client
var sliceTex sync.Mutex
func init() { func init() {
stderrClient := CreateClient() stderrClient := CreateClient()
@ -30,22 +32,40 @@ func init() {
} }
func (c *Client) logStdErr() { func (c *Client) logStdErr() {
select { for {
case entry := <-c.writer: select {
if c.LogLevel >= entry.level { case entry, more := <-c.writer:
fmt.Println(entry.Output) if c.LogLevel >= entry.level {
fmt.Println(entry.Output)
}
if !more {
return
}
} }
} }
} }
func CreateClient() *Client { func CreateClient() *Client {
var client Client var client Client
client.writer = make(LogWriter, 10) client.writer = make(LogWriter, 100)
clients = append(clients, client) sliceTex.Lock()
clients = append(clients, &client)
sliceTex.Unlock()
return &client return &client
} }
func (c *Client) Destroy() error { func (c *Client) Destroy() error {
var otherClients []*Client
sliceTex.Lock()
c.writer = nil
c = nil
for _, x := range clients {
if x != nil {
otherClients = append(otherClients, x)
}
}
clients = otherClients
sliceTex.Unlock()
return nil return nil
} }
@ -54,11 +74,16 @@ func (c *Client) GetLogLevel() Level {
} }
func createLog(e Entry) { func createLog(e Entry) {
sliceTex.Lock()
for _, c := range clients { for _, c := range clients {
go func(c Client, e Entry) { go func(c *Client, e Entry) {
c.writer <- e select {
case c.writer <- e:
default:
}
}(c, e) }(c, e)
} }
sliceTex.Unlock()
} }
// SetLogLevel set log level of logger // SetLogLevel set log level of logger

View File

@ -4,10 +4,15 @@ import (
"testing" "testing"
) )
func TestCreateDestroy(t *testing.T) {
c := CreateClient()
c.Destroy()
}
// SetLogLevel set log level of logger // SetLogLevel set log level of logger
func TestSetLogLevel(t *testing.T) { func TestSetLogLevel(t *testing.T) {
logLevels := [...]Level{LTrace, LDebug, LInfo, LWarn, LError, LPanic, LFatal} logLevels := [...]Level{LTrace, LDebug, LInfo, LWarn, LError, LPanic, LFatal}
var c Client c := CreateClient()
for _, x := range logLevels { for _, x := range logLevels {
c.SetLogLevel(x) c.SetLogLevel(x)
if c.GetLogLevel() != x { if c.GetLogLevel() != x {