diff --git a/logger.go b/logger.go index 1c5fc8d..ca2d20a 100644 --- a/logger.go +++ b/logger.go @@ -54,6 +54,7 @@ func (c *Client) logStdErr() { func CreateClient() *Client { var client Client + client.initialized = true client.writer = make(LogWriter, 100) sliceTex.Lock() clients = append(clients, &client) @@ -70,11 +71,14 @@ func Flush() { func (c *Client) Destroy() error { var otherClients []*Client + if !c.initialized { + panic(errors.New("Cannot delete uninitialized client, did you use CreateClient?")) + } sliceTex.Lock() c.writer = nil - c = nil + c.initialized = false for _, x := range clients { - if x != nil { + if x.initialized { otherClients = append(otherClients, x) } } @@ -84,6 +88,9 @@ func (c *Client) Destroy() error { } func (c *Client) GetLogLevel() Level { + if !c.initialized { + panic(errors.New("Cannot get level for uninitialized client, use CreateClient instead")) + } return c.LogLevel } @@ -102,9 +109,19 @@ func createLog(e Entry) { // SetLogLevel set log level of logger func (c *Client) SetLogLevel(level Level) { + if !c.initialized { + panic(errors.New("Cannot set level for uninitialized client, use CreateClient instead")) + } c.LogLevel = level } +func (c *Client) Get() Entry { + if !c.initialized { + panic(errors.New("Cannot get logs for uninitialized client, did you use CreateClient?")) + } + return <-c.writer +} + // Trace prints out logs on trace level func Trace(args ...interface{}) { output := fmt.Sprint(args...) diff --git a/logger_test.go b/logger_test.go index 0aea27b..80053a9 100644 --- a/logger_test.go +++ b/logger_test.go @@ -5,8 +5,17 @@ import ( ) func TestCreateDestroy(t *testing.T) { + if len(clients) != 1 { + t.Errorf("Expected 1 client, but found %d", len(clients)) + } c := CreateClient() + if len(clients) != 2 { + t.Errorf("Expected 2 clients, but found %d", len(clients)) + } c.Destroy() + if len(clients) != 1 { + t.Errorf("Expected 1 client, but found %d", len(clients)) + } } // SetLogLevel set log level of logger @@ -19,18 +28,24 @@ func TestSetLogLevel(t *testing.T) { t.Errorf("Got logLevel %d, but expected %d", int(c.GetLogLevel()), int(x)) } } + c.Destroy() } // Trace prints out logs on trace level func TestTrace(t *testing.T) { - var c Client + testString := "Testing trace!" + var c *Client + c = CreateClient() c.SetLogLevel(LTrace) - Trace("Testing trace!") - Trace("Testing trace!") - Trace("Testing trace!") - Trace("Testing trace!") - Trace("Testing trace!") + for i := 0; i < 5; i++ { + Trace(testString) + } + for i := 0; i < 5; i++ { + if testString != c.Get().Output { + t.Error("Trace input doesn't match output") + } + } } // Debug prints out logs on debug level diff --git a/structs.go b/structs.go index a15d028..9b4119d 100644 --- a/structs.go +++ b/structs.go @@ -5,8 +5,9 @@ import "time" type LogWriter chan Entry type Client struct { - LogLevel Level `json:"level"` - writer LogWriter + LogLevel Level `json:"level"` + writer LogWriter + initialized bool } type Entry struct {