Repository: NethermindEth/juno
Pull request #335 (2022-08-09 06:31:02)

add colour coded logs
Fixes https://github.com/NethermindEth/juno/issues/119

## Changes:
- Added colour coded logs

## Types of changes

What types of changes does your code introduce?

- [ ] Bugfix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation Update
- [ ] Code style update (formatting, renaming)
- [ ] Refactoring (no functional changes, no api changes)
- [ ] Build related changes
- [ ] Other (please describe): 


codecov[bot]: # [Codecov](https://codecov.io/gh/NethermindEth/juno/pull/335?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth) Report
> Merging [#335](https://codecov.io/gh/NethermindEth/juno/pull/335?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth) (a4c544f) into [main](https://codecov.io/gh/NethermindEth/juno/commit/ca7648abc5e41a60ff7b955495aa74673d052b50?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth) (ca7648a) will **not change** coverage.
> The diff coverage is `100.00%`.

```diff
@@            Coverage Diff            @@
##              main      #335   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           59        59           
  Lines         6726      6727    +1     
=========================================
+ Hits          6726      6727    +1     
```

| Flag | Coverage Δ | |
|---|---|---|
| unittests | `100.00% <100.00%> (ø)` | |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/NethermindEth/juno/pull/335?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth) | Coverage Δ | |
|---|---|---|
| [internal/log/log.go](https://codecov.io/gh/NethermindEth/juno/pull/335/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth#diff-aW50ZXJuYWwvbG9nL2xvZy5nbw==) | `100.00% <100.00%> (ø)` | |
| [pkg/crypto/weierstrass/weierstrass.go](https://codecov.io/gh/NethermindEth/juno/pull/335/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth#diff-cGtnL2NyeXB0by93ZWllcnN0cmFzcy93ZWllcnN0cmFzcy5nbw==) | `100.00% <0.00%> (ø)` | |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=NethermindEth)

joshklop: I just remembered: we do have [a page](https://gojuno.xyz/docs/running/config) in the docs that displays all available configuration parameters. Since another param is added here (`log-nocolor`), it should probably be added to the documentation. This should be a one-line change to [this](https://github.com/NethermindEth/juno/blob/main/docs/docs/running/config.mdx) file.

Patch:
diff --git a/cmd/juno/main.go b/cmd/juno/main.go
index 355b3109..bc6a2dcf 100644
--- a/cmd/juno/main.go
+++ b/cmd/juno/main.go
@@ -99,6 +99,7 @@ func newRootCmd() *cobra.Command {
 	// Log
 	rootCmd.PersistentFlags().StringVar(&cfg.Log.Level, "log-level", "info", "verbosity of the logs. Options: debug, info, warn, error, dpanic, panic, fatal.")
 	rootCmd.PersistentFlags().BoolVar(&cfg.Log.Json, "log-json", false, "print logs in json format. Useful for automated processing. Typically omitted if logs are only viewed from console.")
+	rootCmd.PersistentFlags().BoolVar(&cfg.Log.NoColor, "log-nocolor", false, "disable colour coded logs. Colour coded logs are enabled by default.")
 
 	// RPC
 	rootCmd.PersistentFlags().BoolVar(&cfg.Rpc.Enable, "rpc-enable", false, "enable the RPC server. Warning: this exposes the node to external requests and potentially DoS attacks.")
@@ -229,7 +230,7 @@ func setupVirtualMachine() {
 }
 
 func setupLogger(cfg *config.Log) {
-	if err := ReplaceGlobalLogger(cfg.Json, cfg.Level); err != nil {
+	if err := ReplaceGlobalLogger(cfg.Json, cfg.Level, !cfg.NoColor); err != nil {
 		fmt.Printf("failed to initialize logger: %s\n", err)
 		os.Exit(1)
 	}
diff --git a/docs/docs/running/config.mdx b/docs/docs/running/config.mdx
index 73ff20f5..d5b0fdcd 100644
--- a/docs/docs/running/config.mdx
+++ b/docs/docs/running/config.mdx
@@ -24,6 +24,7 @@ Structure:
 log:
   level: INFO
   json: false
+  nocolor: false
 rpc:
   enable: false
   port: 8080
diff --git a/internal/config/config.go b/internal/config/config.go
index 390a0aa8..c137bad5 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -12,8 +12,9 @@ import (
 
 // Log represents the logger configuration
 type Log struct {
-	Level string `yaml:"level" mapstructure:"level"`
-	Json  bool   `yaml:"json" mapstructure:"json"`
+	Level   string `yaml:"level" mapstructure:"level"`
+	Json    bool   `yaml:"json" mapstructure:"json"`
+	NoColor bool   `yaml:"nocolor" mapstructure:"nocolor"`
 }
 
 // Rpc represents the juno RPC configuration.
diff --git a/internal/log/log.go b/internal/log/log.go
index 166114e9..98be67cf 100644
--- a/internal/log/log.go
+++ b/internal/log/log.go
@@ -15,6 +15,7 @@ var Logger *zap.SugaredLogger
 func init() {
 	config := zap.NewDevelopmentConfig()
 	config.DisableStacktrace = true
+	config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
 	logger, err := config.Build()
 	if err != nil {
 		// notest
@@ -24,9 +25,16 @@ func init() {
 }
 
 // ReplaceGlobalLogger replace the logger and inject it globally
-func ReplaceGlobalLogger(enableJsonOutput bool, verbosityLevel string) error {
+func ReplaceGlobalLogger(enableJsonOutput bool, verbosityLevel string, enableColorEncoder bool) error {
 	config := zap.NewProductionConfig()
 
+	// Colour coding
+	if enableColorEncoder {
+		config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
+	} else {
+		config.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
+	}
+
 	// Timestamp format (ISO8601) and time zone (UTC)
 	config.EncoderConfig.EncodeTime = zapcore.TimeEncoder(func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
 		// notest


Test patch:
diff --git a/internal/log/log_test.go b/internal/log/log_test.go
index ee4ee5e7..b6ef29de 100644
--- a/internal/log/log_test.go
+++ b/internal/log/log_test.go
@@ -4,8 +4,9 @@ import "testing"
 
 func TestReplaceGlobalLogger(t *testing.T) {
 	type args struct {
-		enableJsonOutput bool
-		verbosityLevel   string
+		enableJsonOutput   bool
+		verbosityLevel     string
+		enableColorEncoder bool
 	}
 	tests := []struct {
 		name string
@@ -15,23 +16,25 @@ func TestReplaceGlobalLogger(t *testing.T) {
 		{
 			name: "replace logger with good configuration (console encoding) should not return error",
 			args: args{
-				enableJsonOutput: false,
-				verbosityLevel:   "debug",
+				enableJsonOutput:   false,
+				verbosityLevel:     "debug",
+				enableColorEncoder: false,
 			},
 			err: nil,
 		},
 		{
 			name: "replace logger with good configuration (json encoding) should not return error",
 			args: args{
-				enableJsonOutput: true,
-				verbosityLevel:   "debug",
+				enableJsonOutput:   true,
+				verbosityLevel:     "debug",
+				enableColorEncoder: true,
 			},
 			err: nil,
 		},
 	}
 	for _, test := range tests {
 		t.Run(test.name, func(t *testing.T) {
-			if err := ReplaceGlobalLogger(test.args.enableJsonOutput, test.args.verbosityLevel); err != nil {
+			if err := ReplaceGlobalLogger(test.args.enableJsonOutput, test.args.verbosityLevel, test.args.enableColorEncoder); err != nil {
 				t.Errorf("ReplaceGlobalLogger() error = %v", err)
 			}
 		})