Skip to content
This repository has been archived by the owner on Oct 28, 2022. It is now read-only.

Commit

Permalink
use global logger
Browse files Browse the repository at this point in the history
  • Loading branch information
karimra committed May 17, 2020
1 parent b2e1ac3 commit 28a265f
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 63 deletions.
7 changes: 3 additions & 4 deletions cmd/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package cmd
import (
"context"
"fmt"
"log"
"net"
"strings"
"sync"
Expand Down Expand Up @@ -67,13 +66,13 @@ var capabilitiesCmd = &cobra.Command{
if strings.Contains(err.Error(), "missing port in address") {
address = net.JoinHostPort(address, defaultGrpcPort)
} else {
log.Printf("error parsing address '%s': %v", address, err)
logger.Printf("error parsing address '%s': %v", address, err)
return
}
}
conn, err := createGrpcConn(address)
if err != nil {
log.Printf("connection to %s failed: %v", address, err)
logger.Printf("connection to %s failed: %v", address, err)
return
}
client := gnmi.NewGNMIClient(conn)
Expand All @@ -87,7 +86,7 @@ var capabilitiesCmd = &cobra.Command{

response, err := client.Capabilities(ctx, req)
if err != nil {
log.Printf("error sending capabilities request: %v", err)
logger.Printf("error sending capabilities request: %v", err)
return
}
printPrefix := ""
Expand Down
26 changes: 11 additions & 15 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"strings"
"sync"
Expand Down Expand Up @@ -100,13 +99,13 @@ var getCmd = &cobra.Command{
if strings.Contains(err.Error(), "missing port in address") {
address = net.JoinHostPort(address, defaultGrpcPort)
} else {
log.Printf("error parsing address '%s': %v", address, err)
logger.Printf("error parsing address '%s': %v", address, err)
return
}
}
conn, err := createGrpcConn(address)
if err != nil {
log.Printf("connection to %s failed: %v", address, err)
logger.Printf("connection to %s failed: %v", address, err)
return
}
client := gnmi.NewGNMIClient(conn)
Expand All @@ -117,14 +116,14 @@ var getCmd = &cobra.Command{
if model != "" {
capResp, err := client.Capabilities(ctx, &gnmi.CapabilityRequest{})
if err != nil {
log.Printf("%v", err)
logger.Printf("%v", err)
return
}
var found bool
for _, m := range capResp.SupportedModels {
if m.Name == model {
if debug {
log.Printf("target %s: found model: %v\n", address, m)
logger.Printf("target %s: found model: %v\n", address, m)
}
xreq.UseModels = append(xreq.UseModels,
&gnmi.ModelData{
Expand All @@ -137,21 +136,20 @@ var getCmd = &cobra.Command{
}
}
if !found {
log.Printf("model '%s' not supported by target %s", model, address)
logger.Printf("model '%s' not supported by target %s", model, address)
return
}
}
log.Printf("sending gnmi GetRequest '%+v' to %s", xreq, address)
logger.Printf("sending gnmi GetRequest '%+v' to %s", xreq, address)
response, err := client.Get(ctx, xreq)
if err != nil {
log.Printf("failed sending GetRequest to %s: %v", address, err)
logger.Printf("failed sending GetRequest to %s: %v", address, err)
return
}
printPrefix := ""
if len(addresses) > 1 && !viper.GetBool("no-prefix") {
printPrefix = fmt.Sprintf("[%s] ", address)
}
// valsOnly := viper.GetBool("get-values-only")
lock.Lock()
printGetResponse(printPrefix, response)
lock.Unlock()
Expand All @@ -170,19 +168,17 @@ func init() {
getCmd.Flags().StringP("prefix", "", "", "get request prefix")
getCmd.Flags().StringP("model", "", "", "get request model")
getCmd.Flags().StringP("type", "t", "ALL", "the type of data that is requested from the target. one of: ALL, CONFIG, STATE, OPERATIONAL")
getCmd.Flags().BoolP("values-only", "", false, "output returned values only, useful for file redirection")
viper.BindPFlag("get-path", getCmd.Flags().Lookup("path"))
viper.BindPFlag("get-prefix", getCmd.Flags().Lookup("prefix"))
viper.BindPFlag("get-model", getCmd.Flags().Lookup("model"))
viper.BindPFlag("get-type", getCmd.Flags().Lookup("type"))
viper.BindPFlag("get-values-only", getCmd.Flags().Lookup("values-only"))
}

func printGetResponse(printPrefix string, response *gnmi.GetResponse) {
if viper.GetBool("raw") {
data, err := json.MarshalIndent(response, printPrefix, " ")
if err != nil {
log.Println(err)
logger.Println(err)
}
fmt.Printf("%s%s\n", printPrefix, string(data))
return
Expand All @@ -194,7 +190,7 @@ func printGetResponse(printPrefix string, response *gnmi.GetResponse) {
for i, upd := range notif.Update {
if upd.Val == nil {
if viper.GetBool("debug") {
log.Printf("DEBUG: got a nil val update: %+v", upd)
logger.Printf("DEBUG: got a nil val update: %+v", upd)
}
continue
}
Expand All @@ -204,7 +200,7 @@ func printGetResponse(printPrefix string, response *gnmi.GetResponse) {
}
value, err := getValue(upd.Val)
if err != nil {
log.Println(err)
logger.Println(err)
}
msg.Updates = append(msg.Updates,
&update{
Expand All @@ -215,7 +211,7 @@ func printGetResponse(printPrefix string, response *gnmi.GetResponse) {
}
dMsg, err := json.MarshalIndent(msg, printPrefix, " ")
if err != nil {
log.Printf("error marshling json msg:%v", err)
logger.Printf("error marshling json msg:%v", err)
return
}
fmt.Printf("%s%s\n", printPrefix, string(dMsg))
Expand Down
24 changes: 12 additions & 12 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const (

var cfgFile string
var f io.WriteCloser
var logger *log.Logger

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Expand All @@ -55,23 +56,25 @@ var rootCmd = &cobra.Command{
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if viper.GetBool("nolog") {
f = myWriteCloser{}
return
}
if viper.GetString("log-file") == "" {
f = os.Stderr
} else {
var err error
f, err = os.OpenFile(viper.GetString("log-file"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
logger.Fatalf("error opening file: %v", err)
}
log.SetOutput(f)
}
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
logger := log.New(f, "", log.LstdFlags|log.Lmicroseconds)
grpclog.SetLogger(logger)
logger = log.New(f, "", log.LstdFlags|log.Lmicroseconds)
logger.SetFlags(log.LstdFlags | log.Lmicroseconds)
if viper.GetBool("debug") {
grpclog.SetLogger(logger)
}
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if !viper.GetBool("nolog") && !viper.GetBool("logstdout") {
if !viper.GetBool("nolog") || viper.GetString("log-file") != "" {
f.Close()
}
},
Expand Down Expand Up @@ -192,16 +195,14 @@ func createGrpcConn(address string) (*grpc.ClientConn, error) {
}
err := loadCerts(tlsConfig)
if err != nil {
log.Printf("failed loading certificates: %v", err)
logger.Printf("failed loading certificates: %v", err)
}

err = loadCACerts(tlsConfig)
if err != nil {
log.Printf("failed loading CA certificates: %v", err)
logger.Printf("failed loading CA certificates: %v", err)
}

opts = append(opts, grpc.WithMaxHeaderListSize(8192))
opts = append(opts, grpc.WithInitialWindowSize(4194304))
opts = append(opts, grpc.WithDisableRetry())
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
conn, err := grpc.Dial(address, opts...)
Expand Down Expand Up @@ -279,7 +280,6 @@ func gather(ctx context.Context, c chan string, ls *[]string) {
}
}
}

func getValue(updValue *gnmi.TypedValue) (interface{}, error) {
var value interface{}
var jsondata []byte
Expand Down
41 changes: 20 additions & 21 deletions cmd/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"path/filepath"
"strconv"
Expand Down Expand Up @@ -79,16 +78,16 @@ var setCmd = &cobra.Command{
replaceTypes := make([]string, 0)

if viper.GetBool("debug") {
log.Printf("deletes(%d)=%v\n", len(deletes), deletes)
log.Printf("updates(%d)=%v\n", len(updates), updates)
log.Printf("replaces(%d)=%v\n", len(replaces), replaces)
log.Printf("delimiter=%v\n", delimiter)
log.Printf("updates-paths(%d)=%v\n", len(updatePaths), updatePaths)
log.Printf("replaces-paths(%d)=%v\n", len(replacePaths), replacePaths)
log.Printf("updates-files(%d)=%v\n", len(updateFiles), updateFiles)
log.Printf("replaces-files(%d)=%v\n", len(replaceFiles), replaceFiles)
log.Printf("updates-values(%d)=%v\n", len(updateValues), updateValues)
log.Printf("replaces-values(%d)=%v\n", len(replaceValues), replaceValues)
logger.Printf("deletes(%d)=%v\n", len(deletes), deletes)
logger.Printf("updates(%d)=%v\n", len(updates), updates)
logger.Printf("replaces(%d)=%v\n", len(replaces), replaces)
logger.Printf("delimiter=%v\n", delimiter)
logger.Printf("updates-paths(%d)=%v\n", len(updatePaths), updatePaths)
logger.Printf("replaces-paths(%d)=%v\n", len(replacePaths), replacePaths)
logger.Printf("updates-files(%d)=%v\n", len(updateFiles), updateFiles)
logger.Printf("replaces-files(%d)=%v\n", len(replaceFiles), replaceFiles)
logger.Printf("updates-values(%d)=%v\n", len(updateValues), updateValues)
logger.Printf("replaces-values(%d)=%v\n", len(replaceValues), replaceValues)
}
if inlineUpdates && !useUpdateFile {
updateSlice := strings.Split(updates, delimiter)
Expand Down Expand Up @@ -137,22 +136,22 @@ var setCmd = &cobra.Command{
for _, p := range deletes {
gnmiPath, err := xpath.ToGNMIPath(p)
if err != nil {
log.Printf("path '%s' parse error: %v", p, err)
logger.Printf("path '%s' parse error: %v", p, err)
continue
}
req.Delete = append(req.Delete, gnmiPath)
}
for i, p := range updatePaths {
gnmiPath, err := xpath.ToGNMIPath(p)
if err != nil {
log.Print(err)
logger.Print(err)
}
value := new(gnmi.TypedValue)
if useUpdateFile {
var updateData []byte
updateData, err = readFile(updateFiles[i])
if err != nil {
log.Printf("error reading data from file '%s': %v", updateFiles[i], err)
logger.Printf("error reading data from file '%s': %v", updateFiles[i], err)
continue
}
value.Value = &gnmi.TypedValue_JsonVal{
Expand Down Expand Up @@ -205,7 +204,7 @@ var setCmd = &cobra.Command{
value.Value = &gnmi.TypedValue_DecimalVal{
DecimalVal: dVal,
}
log.Println("decimal type not implemented")
logger.Println("decimal type not implemented")
return nil
case "float":
f, err := strconv.ParseFloat(updateValues[i], 32)
Expand Down Expand Up @@ -247,14 +246,14 @@ var setCmd = &cobra.Command{
for i, p := range replacePaths {
gnmiPath, err := xpath.ToGNMIPath(p)
if err != nil {
log.Print(err)
logger.Print(err)
}
value := new(gnmi.TypedValue)
if useReplaceFile {
var replaceData []byte
replaceData, err = readFile(replaceFiles[i])
if err != nil {
log.Printf("error reading data from file '%s': %v", replaceFiles[i], err)
logger.Printf("error reading data from file '%s': %v", replaceFiles[i], err)
continue
}
value.Value = &gnmi.TypedValue_JsonVal{
Expand Down Expand Up @@ -307,7 +306,7 @@ var setCmd = &cobra.Command{
value.Value = &gnmi.TypedValue_DecimalVal{
DecimalVal: dVal,
}
log.Println("decimal type not implemented")
logger.Println("decimal type not implemented")
return nil
case "float":
f, err := strconv.ParseFloat(replaceValues[i], 32)
Expand Down Expand Up @@ -368,13 +367,13 @@ var setCmd = &cobra.Command{
if strings.Contains(err.Error(), "missing port in address") {
address = net.JoinHostPort(address, defaultGrpcPort)
} else {
log.Printf("error parsing address '%s': %v", address, err)
logger.Printf("error parsing address '%s': %v", address, err)
return
}
}
conn, err := createGrpcConn(address)
if err != nil {
log.Printf("connection to %s failed: %v", address, err)
logger.Printf("connection to %s failed: %v", address, err)
return
}
client := gnmi.NewGNMIClient(conn)
Expand Down Expand Up @@ -406,7 +405,7 @@ var setCmd = &cobra.Command{
}
response, err := client.Set(ctx, req)
if err != nil {
log.Printf("error sending set request: %v", err)
logger.Printf("error sending set request: %v", err)
return
}
fmt.Printf("%sgnmi set response:\n", printPrefix)
Expand Down
Loading

0 comments on commit 28a265f

Please sign in to comment.