Skip to content

Commit 83fd88b

Browse files
authored
Logger Changes (#158)
* Changes to logger, adding tracing capabilities v1 * Started changing Logr struct to incorporate log.entry + cleaning * Updated * Integrated tracing with Debug, Info, and Trace * Updated Start Context and End Context * Cleaning up code on logger.go and logger_test.go * Changes made to support ending and restarting a span * Removed log line * removed test.log
1 parent 7563f6b commit 83fd88b

File tree

4 files changed

+188
-20
lines changed

4 files changed

+188
-20
lines changed

glide.lock

Lines changed: 35 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

glide.yaml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,9 @@ import:
6868
version: 4e5b6552494c8005c60de6c60b50ebaefc69e592
6969
- package: github.com/fsnotify/fsnotify
7070
version: ^v1.4.9
71+
- package: github.com/opentracing/opentracing-go
72+
version: ^v1.2.0
73+
- package: github.com/uber/jaeger-client-go
74+
version: ^v2.29
75+
- package: "github.com/opentracing/opentracing-go/ext"
76+
version: ^v1.2.0

logger/logger.go

Lines changed: 118 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import (
1616
"sync"
1717
"time"
1818

19+
"github.com/opentracing/opentracing-go"
20+
otLog "github.com/opentracing/opentracing-go/log"
1921
log "github.com/sirupsen/logrus"
22+
"github.com/uber/jaeger-client-go/config"
2023
"golang.org/x/crypto/ssh/terminal"
2124
"gopkg.in/natefinch/lumberjack.v2"
2225
)
@@ -41,6 +44,12 @@ type LogParams struct {
4144
Format string
4245
}
4346

47+
type Logr struct {
48+
ctx context.Context
49+
logEntry *log.Entry
50+
cl io.Closer
51+
}
52+
4453
var (
4554
logParams LogParams
4655
initMutex sync.Mutex
@@ -163,8 +172,28 @@ func updateLogParamsFromEnv() {
163172
}
164173
}
165174

175+
//Initalizes opentracing tracing
176+
func InitOpentracing(service string) (opentracing.Tracer, io.Closer) {
177+
cfg := &config.Configuration{
178+
ServiceName: service,
179+
Sampler: &config.SamplerConfig{
180+
Type: "const",
181+
Param: 1,
182+
},
183+
Reporter: &config.ReporterConfig{
184+
LogSpans: true,
185+
},
186+
}
187+
//add tracer as a input of NewTracer so that the logspans declared true above will work
188+
tracer, closer, err := cfg.NewTracer()
189+
if err != nil {
190+
panic(fmt.Sprintf("ERROR: cannot init tracing: %v\n", err))
191+
}
192+
return tracer, closer
193+
}
194+
166195
// Initialize logging with given params
167-
func InitLogging(logName string, params *LogParams, alsoLogToStderr bool) (err error) {
196+
func InitLogging(logName string, params *LogParams, alsoLogToStderr bool, initTracing bool) (err error, l *Logr) {
168197
initMutex.Lock()
169198
defer initMutex.Unlock()
170199

@@ -190,23 +219,27 @@ func InitLogging(logName string, params *LogParams, alsoLogToStderr bool) (err e
190219
// No output except for the hooks
191220
log.SetOutput(ioutil.Discard)
192221

222+
//Default Logr
223+
logEntry := sourced()
224+
lg := Logr{nil, logEntry, nil}
225+
193226
if logParams.GetFile() != "" {
194227
err = AddFileHook()
195228
if err != nil {
196-
return err
229+
return err, &lg
197230
}
198231
}
199232
if alsoLogToStderr {
200233
err = AddConsoleHook()
201234
if err != nil {
202-
return err
235+
return err, &lg
203236
}
204237
}
205238

206239
// Set log level
207240
level, err := log.ParseLevel(logParams.GetLevel())
208241
if err != nil {
209-
return err
242+
return err, &lg
210243
}
211244
log.SetLevel(level)
212245

@@ -217,7 +250,64 @@ func InitLogging(logName string, params *LogParams, alsoLogToStderr bool) (err e
217250
"alsoLogToStderr": alsoLogToStderr,
218251
}).Info("Initialized logging.")
219252

220-
return nil
253+
//initializes tracing capabilites if true
254+
if initTracing {
255+
//Initializing the tracer
256+
tracer, closer := InitOpentracing("CSI-Driver")
257+
opentracing.SetGlobalTracer(tracer)
258+
259+
//Span Initialized with default context
260+
span := tracer.StartSpan("CSI-Driver")
261+
log.Printf("Span Context --- Traceid:Spanid:ParentSpanid:Flags : %v", span.Context())
262+
ctx := opentracing.ContextWithSpan(context.Background(), span)
263+
logEntry := sourced()
264+
l := Logr{ctx, logEntry, closer}
265+
266+
l.LogToTrace("Info", "Tracing Initialized")
267+
defer span.Finish()
268+
269+
return nil, &l
270+
}
271+
272+
return nil, &lg
273+
}
274+
275+
func (l *Logr) CloseTracer() {
276+
l.cl.Close()
277+
}
278+
279+
//Logs given string to tracer
280+
func (l *Logr) LogToTrace(level, msg string) {
281+
span := opentracing.SpanFromContext(l.ctx)
282+
//fmt.Print("In LogToTrace")
283+
if span != nil {
284+
span.LogFields(otLog.String("event", msg))
285+
}
286+
if span == nil {
287+
fmt.Print("Span is nil")
288+
}
289+
span.Finish()
290+
}
291+
292+
//Sets context of called Logr to given context
293+
func (l *Logr) SetContext(context context.Context) {
294+
l.ctx = context
295+
}
296+
297+
//Starts and returns a span for the inputted Logr
298+
func (l *Logr) StartContext(spanName string) (s opentracing.Span) {
299+
s = opentracing.SpanFromContext(l.ctx)
300+
if s == nil || s.BaggageItem(spanName) == "" {
301+
s = opentracing.StartSpan(spanName)
302+
s.SetBaggageItem(spanName, "true")
303+
l.ctx = opentracing.ContextWithSpan(context.Background(), s)
304+
}
305+
return s
306+
}
307+
308+
//Ends the inputted span
309+
func EndContext(span opentracing.Span) {
310+
span.Finish()
221311
}
222312

223313
func AddConsoleHook() error {
@@ -455,7 +545,6 @@ func IsSensitive(key string) bool {
455545
"token",
456546
"accesskey",
457547
"passphrase",
458-
459548
}
460549
key = strings.ToLower(key)
461550
for _, bad := range badWords {
@@ -506,24 +595,42 @@ func sourced() *log.Entry {
506595
return log.WithField("file", fmt.Sprintf("%s:%d", file, line))
507596
}
508597

509-
// Trace logs a message at level Trace on the standard logger.
510598
func Trace(args ...interface{}) {
511599
sourced().Trace(args...)
512600
}
513601

514-
// Debug logs a message at level Debug on the standard logger.
602+
// Trace logs a message at level Trace on the standard logger.
603+
func (lg *Logr) Trace(args ...interface{}) {
604+
lg.logEntry.Trace(args...)
605+
str := fmt.Sprintf("%v", args)
606+
lg.LogToTrace("Trace", str)
607+
}
608+
515609
func Debug(args ...interface{}) {
516-
sourced().Debug(args...)
610+
sourced().Trace(args...)
611+
}
612+
613+
// Debug logs a message at level Debug on the standard logger.
614+
func (lg *Logr) Debug(args ...interface{}) {
615+
lg.logEntry.Debug(args...)
616+
str := fmt.Sprintf("%v", args)
617+
lg.LogToTrace("Debug", str)
517618
}
518619

519620
// Print logs a message at level Info on the standard logger.
520621
func Print(args ...interface{}) {
521622
sourced().Print(args...)
522623
}
523624

524-
// Info logs a message at level Info on the standard logger.
525625
func Info(args ...interface{}) {
526-
sourced().Info(args...)
626+
sourced().Trace(args...)
627+
}
628+
629+
// Info logs a message at level Info on the standard logger.
630+
func (lg *Logr) Info(args ...interface{}) {
631+
lg.logEntry.Info(args...)
632+
str := fmt.Sprintf("%v", args)
633+
lg.LogToTrace("Info", str)
527634
}
528635

529636
// Warn logs a message at level Warn on the standard logger.

logger/logger_test.go

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"strings"
99
"testing"
1010

11+
"github.com/hpe-storage/common-host-libs/logger"
1112
log "github.com/sirupsen/logrus"
1213
"github.com/stretchr/testify/assert"
1314
)
@@ -68,7 +69,7 @@ func TestInitLogging(t *testing.T) {
6869
os.RemoveAll(logFile)
6970

7071
// Test1: test overrides with params to log to only stdout
71-
InitLogging("", nil, true)
72+
InitLogging("", nil, true, false)
7273

7374
// verify logging with override to stdout only
7475
testName := "test_param_override_stdout_only"
@@ -78,7 +79,7 @@ func TestInitLogging(t *testing.T) {
7879
assert.Equal(t, true, os.IsNotExist(err))
7980

8081
// Test 2: initialize logger with nil params to verify default levels
81-
InitLogging(logFile, nil, false)
82+
InitLogging(logFile, nil, false, false)
8283

8384
// verify default info level setting with no params
8485
assert.Equal(t, DefaultLogLevel, log.GetLevel().String())
@@ -93,7 +94,7 @@ func TestInitLogging(t *testing.T) {
9394
testContains(t, logFile, testName, "debug", false)
9495

9596
// Test3: initialize logger with override of trace level
96-
InitLogging(logFile, &LogParams{Level: "trace"}, false)
97+
InitLogging(logFile, &LogParams{Level: "trace"}, false, false)
9798

9899
// verify trace level setting with param override
99100
assert.Equal(t, log.TraceLevel.String(), log.GetLevel().String())
@@ -109,7 +110,7 @@ func TestInitLogging(t *testing.T) {
109110

110111
// Test4: initialize logger with env vars for info level
111112
os.Setenv("LOG_LEVEL", "debug")
112-
InitLogging(logFile, nil, false)
113+
InitLogging(logFile, nil, false, false)
113114
// verify logging with debug level and below
114115
testName = "test_env_debug_level"
115116
logAllLevels(testName)
@@ -121,20 +122,20 @@ func TestInitLogging(t *testing.T) {
121122

122123
// Test5: initialize logger with invalid log format through env
123124
os.Setenv("LOG_FORMAT", "yaml")
124-
InitLogging(logFile, nil, false)
125+
InitLogging(logFile, nil, false, false)
125126

126127
// verify log format is set to default value of text
127128
assert.Equal(t, logParams.GetLogFormat(), DefaultLogFormat)
128129

129130
// Test6: initialize logger with invalid log files limit through config
130-
InitLogging(logFile, &LogParams{MaxFiles: 1000}, false)
131+
InitLogging(logFile, &LogParams{MaxFiles: 1000}, false, false)
131132

132133
// verify log files is set to default value of 10
133134
assert.Equal(t, logParams.GetMaxFiles(), DefaultMaxLogFiles)
134135

135136
// Test7: test overrides with env variables even when params is not nil
136137
os.Setenv("LOG_LEVEL", "info")
137-
InitLogging(logFile, &LogParams{Level: "trace"}, false)
138+
InitLogging(logFile, &LogParams{Level: "trace"}, false, false)
138139

139140
// verify logging with only info level and below with override from env
140141
testName = "test_env_override_info_level"
@@ -148,3 +149,24 @@ func TestInitLogging(t *testing.T) {
148149
// cleanup log file after test
149150
os.RemoveAll(logFile)
150151
}
152+
153+
func TestInitJaeger(t *testing.T) {
154+
_, lg := logger.InitLogging("test.log", nil, true, true)
155+
156+
lg.Info("************** Start Workflow 1 **************")
157+
lg.Info("********** Workflow 1 Line 1 **********")
158+
s := lg.StartContext("Workflow 2")
159+
lg.Info("**************** Start Workflow 2 *****************")
160+
lg.Info("********** Workflow 2 Line 1 ******************")
161+
logger.EndContext(s)
162+
sp := lg.StartContext("Workflow 2")
163+
lg.Info("**************** Start Workflow 2 *****************")
164+
lg.Info("********** Workflow 2 Line 1 ******************")
165+
logger.EndContext(sp)
166+
sp2 := lg.StartContext("Workflow 3")
167+
lg.Info("**************** Start Workflow 3 *****************")
168+
lg.Info("********** Workflow 3 Line 1 ******************")
169+
logger.EndContext(sp2)
170+
lg.CloseTracer()
171+
172+
}

0 commit comments

Comments
 (0)