[SEBA-835] Dynamically configuring log levels

Change-Id: Id7bb2e870a9e83cdabd6116b05bcf284d83c37a3
diff --git a/Makefile b/Makefile
index 50f281f..b1e2e4e 100644
--- a/Makefile
+++ b/Makefile
@@ -34,7 +34,7 @@
 build: dep protos build-bbsim build-bbsimctl# @HELP Build the binary
 
 test: dep protos # @HELP Execute unit tests
-	GO111MODULE=on go test -v -mod vendor ./internal/bbsim/... -covermode count -coverprofile ./tests/results/go-test-coverage.out 2>&1 | tee ./tests/results/go-test-results.out
+	GO111MODULE=on go test -v -mod vendor ./... -covermode count -coverprofile ./tests/results/go-test-coverage.out 2>&1 | tee ./tests/results/go-test-results.out
 	go-junit-report < ./tests/results/go-test-results.out > ./tests/results/go-test-results.xml
 	gocover-cobertura < ./tests/results/go-test-coverage.out > ./tests/results/go-test-coverage.xml
 
diff --git a/api/bbsim/bbsim.proto b/api/bbsim/bbsim.proto
index 81a25f1..8df10d5 100644
--- a/api/bbsim/bbsim.proto
+++ b/api/bbsim/bbsim.proto
@@ -56,10 +56,16 @@
     string gitStatus = 4;
 }
 
+message LogLevel {
+    string level = 1;
+    bool caller = 2;
+}
+
 message Empty {}
 
 service BBSim {
     rpc Version(Empty) returns (VersionNumber) {}
     rpc GetOlt(Empty) returns (Olt) {}
     rpc GetONUs(Empty) returns (ONUs) {}
+    rpc SetLogLevel(LogLevel) returns (LogLevel) {}
 }
\ No newline at end of file
diff --git a/cmd/bbsim/bbsim.go b/cmd/bbsim/bbsim.go
index 7d8ea06..f243801 100644
--- a/cmd/bbsim/bbsim.go
+++ b/cmd/bbsim/bbsim.go
@@ -21,6 +21,7 @@
 	"github.com/opencord/bbsim/api/bbsim"
 	"github.com/opencord/bbsim/internal/bbsim/api"
 	"github.com/opencord/bbsim/internal/bbsim/devices"
+	bbsimLogger "github.com/opencord/bbsim/internal/bbsim/logger"
 	log "github.com/sirupsen/logrus"
 	"google.golang.org/grpc"
 	"google.golang.org/grpc/reflection"
@@ -38,6 +39,8 @@
 	STag         int
 	CTagInit     int
 	profileCpu   *string
+	logLevel     string
+	logCaller    bool
 }
 
 func getOpts() *CliOptions {
@@ -46,10 +49,15 @@
 	nni := flag.Int("nni", 1, "Number of NNI ports per OLT device to be emulated (default is 1)")
 	pon := flag.Int("pon", 1, "Number of PON ports per OLT device to be emulated (default is 1)")
 	onu := flag.Int("onu", 1, "Number of ONU devices per PON port to be emulated (default is 1)")
+
 	s_tag := flag.Int("s_tag", 900, "S-Tag value (default is 900)")
 	c_tag_init := flag.Int("c_tag", 900, "C-Tag starting value (default is 900), each ONU will get a sequentail one (targeting 1024 ONUs per BBSim instance the range is bug enough)")
+
 	profileCpu := flag.String("cpuprofile", "", "write cpu profile to file")
 
+	logLevel := flag.String("logLevel", "debug", "Set the log level (trace, debug, info, warn, error)")
+	logCaller := flag.Bool("logCaller", false, "Whether to print the caller filename or not")
+
 	flag.Parse()
 
 	o := new(CliOptions)
@@ -61,6 +69,8 @@
 	o.STag = int(*s_tag)
 	o.CTagInit = int(*c_tag_init)
 	o.profileCpu = profileCpu
+	o.logLevel = *logLevel
+	o.logCaller = *logCaller
 
 	return o
 }
@@ -99,16 +109,11 @@
 	return
 }
 
-func init() {
-	// TODO make configurable both via CLI and via ENV (for the tests)
-	log.SetLevel(log.DebugLevel)
-	//log.SetLevel(log.TraceLevel)
-	//log.SetReportCaller(true)
-}
-
 func main() {
 	options := getOpts()
 
+	bbsimLogger.SetLogLevel(log.StandardLogger(), options.logLevel, options.logCaller)
+
 	if *options.profileCpu != "" {
 		// start profiling
 		log.Infof("Creating profile file at: %s", *options.profileCpu)
diff --git a/cmd/bbsimctl/bbsimctl.go b/cmd/bbsimctl/bbsimctl.go
index e7fead0..6371d83 100644
--- a/cmd/bbsimctl/bbsimctl.go
+++ b/cmd/bbsimctl/bbsimctl.go
@@ -38,6 +38,7 @@
 	commands.RegisterOltCommands(parser)
 	commands.RegisterONUCommands(parser)
 	commands.RegisterCompletionCommands(parser)
+	commands.RegisterLoggingCommands(parser)
 
 	_, err = parser.ParseArgs(os.Args[1:])
 	if err != nil {
diff --git a/internal/bbsim/api/grpc_api_server.go b/internal/bbsim/api/grpc_api_server.go
index 27b0ce5..63f5f4a 100644
--- a/internal/bbsim/api/grpc_api_server.go
+++ b/internal/bbsim/api/grpc_api_server.go
@@ -20,6 +20,7 @@
 	"context"
 	"github.com/opencord/bbsim/api/bbsim"
 	"github.com/opencord/bbsim/internal/bbsim/devices"
+	bbsimLogger "github.com/opencord/bbsim/internal/bbsim/logger"
 	log "github.com/sirupsen/logrus"
 )
 
@@ -102,3 +103,13 @@
 	}
 	return &onus, nil
 }
+
+func (s BBSimServer) SetLogLevel(ctx context.Context, req *bbsim.LogLevel) (*bbsim.LogLevel, error) {
+
+	bbsimLogger.SetLogLevel(log.StandardLogger(), req.Level, req.Caller)
+
+	return &bbsim.LogLevel{
+		Level:  log.StandardLogger().Level.String(),
+		Caller: log.StandardLogger().ReportCaller,
+	}, nil
+}
diff --git a/internal/bbsim/logger/logger.go b/internal/bbsim/logger/logger.go
new file mode 100644
index 0000000..c6036fc
--- /dev/null
+++ b/internal/bbsim/logger/logger.go
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package logger
+
+import log "github.com/sirupsen/logrus"
+
+func SetLogLevel(logger *log.Logger, level string, caller bool) {
+
+	logger.SetReportCaller(caller)
+
+	switch level {
+	case "trace":
+		logger.SetLevel(log.TraceLevel)
+	case "debug":
+		logger.SetLevel(log.DebugLevel)
+	case "info":
+		logger.SetLevel(log.InfoLevel)
+	case "warn":
+		logger.SetLevel(log.WarnLevel)
+	case "error":
+		logger.SetLevel(log.ErrorLevel)
+	default:
+		logger.SetLevel(log.DebugLevel)
+		logger.WithFields(log.Fields{
+			"level": level,
+		}).Warn("The provided level is unknown. Defaulting to 'debug'")
+	}
+
+}
diff --git a/internal/bbsim/logger/logger_test.go b/internal/bbsim/logger/logger_test.go
new file mode 100644
index 0000000..d692135
--- /dev/null
+++ b/internal/bbsim/logger/logger_test.go
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package logger_test
+
+import (
+	bbsimLogger "github.com/opencord/bbsim/internal/bbsim/logger"
+	"github.com/sirupsen/logrus"
+	"gotest.tools/assert"
+	"testing"
+)
+
+func Test_SetLogLevel(t *testing.T) {
+	log := logrus.New()
+
+	bbsimLogger.SetLogLevel(log, "trace", false)
+	assert.Equal(t, log.Level, logrus.TraceLevel)
+
+	bbsimLogger.SetLogLevel(log, "debug", false)
+	assert.Equal(t, log.Level, logrus.DebugLevel)
+
+	bbsimLogger.SetLogLevel(log, "info", false)
+	assert.Equal(t, log.Level, logrus.InfoLevel)
+
+	bbsimLogger.SetLogLevel(log, "warn", false)
+	assert.Equal(t, log.Level, logrus.WarnLevel)
+
+	bbsimLogger.SetLogLevel(log, "error", false)
+	assert.Equal(t, log.Level, logrus.ErrorLevel)
+
+	bbsimLogger.SetLogLevel(log, "foobar", false)
+	assert.Equal(t, log.Level, logrus.DebugLevel)
+}
+
+func Test_SetLogLevelCaller(t *testing.T) {
+	log := logrus.New()
+
+	bbsimLogger.SetLogLevel(log, "debug", true)
+	assert.Equal(t, log.ReportCaller, true)
+
+	bbsimLogger.SetLogLevel(log, "debug", false)
+	assert.Equal(t, log.ReportCaller, false)
+}
diff --git a/internal/bbsimctl/commands/logging.go b/internal/bbsimctl/commands/logging.go
new file mode 100644
index 0000000..42e4771
--- /dev/null
+++ b/internal/bbsimctl/commands/logging.go
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package commands
+
+import (
+	"context"
+	"fmt"
+	"github.com/jessevdk/go-flags"
+	pb "github.com/opencord/bbsim/api/bbsim"
+	"github.com/opencord/bbsim/internal/bbsimctl/config"
+	log "github.com/sirupsen/logrus"
+	"google.golang.org/grpc"
+)
+
+type LoggingOptions struct {
+	Args struct {
+		Level  string
+		Caller bool
+	} `positional-args:"yes" required:"yes"`
+}
+
+func RegisterLoggingCommands(parent *flags.Parser) {
+	parent.AddCommand("log", "set bbsim log level", "Commands to set the log level", &LoggingOptions{})
+}
+
+func (options *LoggingOptions) Execute(args []string) error {
+	conn, err := grpc.Dial(config.GlobalConfig.Server, grpc.WithInsecure())
+
+	if err != nil {
+		log.Fatalf("did not connect: %v", err)
+		return nil
+	}
+	defer conn.Close()
+	c := pb.NewBBSimClient(conn)
+
+	// Contact the server and print out its response.
+
+	ctx, cancel := context.WithTimeout(context.Background(), config.GlobalConfig.Grpc.Timeout)
+	defer cancel()
+
+	req := pb.LogLevel{
+		Level:  options.Args.Level,
+		Caller: options.Args.Caller,
+	}
+
+	logLevel, err := c.SetLogLevel(ctx, &req)
+
+	fmt.Println("New log settings:")
+	fmt.Println(fmt.Sprintf("\tLevel: %s", logLevel.Level))
+	fmt.Println(fmt.Sprintf("\tReportCaller: %t", logLevel.Caller))
+
+	return nil
+}
diff --git a/internal/bbsimctl/commands/olt.go b/internal/bbsimctl/commands/olt.go
index 7f698f1..3a434b2 100644
--- a/internal/bbsimctl/commands/olt.go
+++ b/internal/bbsimctl/commands/olt.go
@@ -54,7 +54,7 @@
 func getOLT() *pb.Olt {
 	conn, err := grpc.Dial(config.GlobalConfig.Server, grpc.WithInsecure())
 	if err != nil {
-		log.Fatal("did not connect: %v", err)
+		log.Fatalf("did not connect: %v", err)
 		return nil
 	}
 	defer conn.Close()
@@ -66,7 +66,7 @@
 	defer cancel()
 	olt, err := c.GetOlt(ctx, &pb.Empty{})
 	if err != nil {
-		log.Fatal("could not get OLT: %v", err)
+		log.Fatalf("could not get OLT: %v", err)
 		return nil
 	}
 	return olt
diff --git a/internal/bbsimctl/commands/onu.go b/internal/bbsimctl/commands/onu.go
index 6422f0a..2e8f887 100644
--- a/internal/bbsimctl/commands/onu.go
+++ b/internal/bbsimctl/commands/onu.go
@@ -42,7 +42,7 @@
 	conn, err := grpc.Dial(config.GlobalConfig.Server, grpc.WithInsecure())
 
 	if err != nil {
-		log.Fatal("did not connect: %v", err)
+		log.Fatalf("did not connect: %v", err)
 		return nil
 	}
 	defer conn.Close()
@@ -54,7 +54,7 @@
 	defer cancel()
 	onus, err := c.GetONUs(ctx, &pb.Empty{})
 	if err != nil {
-		log.Fatal("could not get OLT: %v", err)
+		log.Fatalf("could not get OLT: %v", err)
 		return nil
 	}
 	return onus