From f08673d24a53e195143223b38355d9a328526c50 Mon Sep 17 00:00:00 2001 From: Anton Tiurin Date: Tue, 17 Feb 2015 04:06:45 +0300 Subject: [PATCH] [Race] Fix datarace in GetLevel `std.Level` is protected by mutex in setter (SetLevel), so it must be protected in geetter (GetLevel) too. Signed-off-by: Anton Tiurin --- exported.go | 2 ++ logrus_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/exported.go b/exported.go index fd092fc..a67e1b8 100644 --- a/exported.go +++ b/exported.go @@ -36,6 +36,8 @@ func SetLevel(level Level) { // GetLevel returns the standard logger level. func GetLevel() Level { + std.mu.Lock() + defer std.mu.Unlock() return std.Level } diff --git a/logrus_test.go b/logrus_test.go index 7f52c6f..d85dba4 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "strconv" "strings" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -281,3 +282,20 @@ func TestParseLevel(t *testing.T) { l, err = ParseLevel("invalid") assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) } + +func TestGetSetLevelRace(t *testing.T) { + wg := sync.WaitGroup{} + for i := 0; i < 100; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + if i%2 == 0 { + SetLevel(InfoLevel) + } else { + GetLevel() + } + }(i) + + } + wg.Wait() +}