Skip to content

Commit

Permalink
chore: improve logger (colibri-project-io#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
arkanjoms authored Sep 19, 2023
1 parent ef5c497 commit 0b85e05
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 43 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/quality.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
-Dsonar.organization=colibri-project-io
-Dsonar.projectKey=colibri-project-io_colibri-sdk-go
-Dsonar.sources=.
-Dsonar.exclusions=**/*_test.go,**/*.sql,**/*_mock.go
-Dsonar.exclusions=**/*_test.go,**/*.sql,**/*_mock.go,colibri.go
-Dsonar.tests=.
-Dsonar.test.inclusions=**/*_test.go
-Dsonar.go.coverage.reportPaths=/github/workspace/coverage.txt
11 changes: 5 additions & 6 deletions colibri.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

"github.com/colibri-project-io/colibri-sdk-go/pkg/base/cloud"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/config"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/logging"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/monitoring"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/observer"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/validator"
Expand All @@ -18,14 +17,12 @@ const banner = `
'-..-| / / __ / _ \| | | '_ \| '__| |
/\/\ | (__| (_) | | | |_) | | | |
'--' \___ \___/|_|_|_.__/|_| |_|
project - v%s
project
`

var Version string = "0.0.0"

func InitializeApp() {
if err := config.Load(); err != nil {
logging.Fatal("Occurred a error on try load configs: %v", err)
panic(fmt.Sprintf("Occurred a error on try load configs: %v", err))
}

printBanner()
Expand All @@ -38,7 +35,9 @@ func InitializeApp() {
}

func printBanner() {
fmt.Printf(banner, Version)
if config.IsDevelopmentEnvironment() {
fmt.Printf(banner)
}
}

func printApplicationName() {
Expand Down
12 changes: 0 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,6 @@ github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofiber/fiber/v2 v2.48.0 h1:cRVMCb9aUJDsyHxGFLwz/sGzDggdailZZyptU9F9cU0=
github.com/gofiber/fiber/v2 v2.48.0/go.mod h1:xqJgfqrc23FJuqGOW6DVgi3HyZEm2Mn9pRqUb2kHSX8=
github.com/gofiber/fiber/v2 v2.49.2 h1:ONEN3/Vc+dUCxxDgZZwpqvhISgHqb+bu+isBiEyKEQs=
github.com/gofiber/fiber/v2 v2.49.2/go.mod h1:gNsKnyrmfEWFpJxQAV0qvW6l70K1dZGno12oLtukcts=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
Expand Down Expand Up @@ -171,8 +169,6 @@ github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3
github.com/google/s2a-go v0.1.5 h1:8IYp3w9nysqv3JH+NJgXJzGbDHzLOTj43BmSkp+O7qg=
github.com/google/s2a-go v0.1.5/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM=
Expand All @@ -198,8 +194,6 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY=
github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
Expand All @@ -221,8 +215,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
Expand Down Expand Up @@ -319,8 +311,6 @@ github.com/testcontainers/testcontainers-go v0.22.0/go.mod h1:k0YiPa26xJCRUbUkYq
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.48.0 h1:oJWvHb9BIZToTQS3MuQ2R3bJZiNSa2KiNdeI8A+79Tc=
github.com/valyala/fasthttp v1.48.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/fasthttp v1.49.0 h1:9FdvCpmxB74LH4dPb7IJ1cOSsluR07XG3I1txXWwJpE=
github.com/valyala/fasthttp v1.49.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
Expand Down Expand Up @@ -446,8 +436,6 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
Expand Down
27 changes: 17 additions & 10 deletions pkg/base/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,25 @@ import (
"strings"
)

var log *slog.Logger
var logger *slog.Logger

func init() {
CreateLogger()
InitializeLogger()
}

func CreateLogger() {
opts := &slog.HandlerOptions{Level: parseLevel(config.LOG_LEVEL)}
log = slog.New(slog.NewJSONHandler(config.LOG_OUTPUT, opts)).
func InitializeLogger() {
logger = slog.New(createLogHandler()).
With("colibri-sdk-go", map[string]string{"application": config.APP_NAME, "application_type": config.APP_TYPE, "version": config.VERSION})
}

func createLogHandler() slog.Handler {
opts := &slog.HandlerOptions{Level: parseLevel(config.LOG_LEVEL)}
if config.IsDevelopmentEnvironment() {
return slog.NewTextHandler(config.LOG_OUTPUT, opts)
}
return slog.NewJSONHandler(config.LOG_OUTPUT, opts)
}

func parseLevel(lvl string) slog.Level {
switch strings.ToLower(lvl) {
case "error":
Expand All @@ -35,30 +42,30 @@ func parseLevel(lvl string) slog.Level {
// Info prints in console an info message
func Info(message string, args ...interface{}) {
msg := fmt.Sprintf(message, args...)
log.Info(msg)
logger.Info(msg)
}

// Fatal prints in console a fatal message and exits program
func Fatal(message string, args ...interface{}) {
msg := fmt.Sprintf(message, args...)
log.Error(msg)
logger.Error(msg)
panic(msg)
}

// Error prints in console a error message
func Error(message string, args ...interface{}) {
msg := fmt.Sprintf(message, args...)
log.Error(msg)
logger.Error(msg)
}

// Warn prints in console a warn message
func Warn(message string, args ...interface{}) {
msg := fmt.Sprintf(message, args...)
log.Warn(msg)
logger.Warn(msg)
}

// Debug prints in console a debug message if config is enabled
func Debug(message string, args ...interface{}) {
msg := fmt.Sprintf(message, args...)
log.Debug(msg)
logger.Debug(msg)
}
27 changes: 14 additions & 13 deletions pkg/base/logging/logging_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package logging
package logging_test

import (
"bytes"
"encoding/json"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/config"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/logging"
"github.com/stretchr/testify/assert"
"testing"
)

func captureOutput(f func()) (out map[string]any) {
var buf bytes.Buffer
config.LOG_OUTPUT = &buf
CreateLogger()
logging.InitializeLogger()
f()
_ = json.Unmarshal(buf.Bytes(), &out)
return
Expand All @@ -22,39 +23,39 @@ func TestLogging(t *testing.T) {
config.APP_NAME = "sdk-test"
config.APP_TYPE = "service"

t.Run("Should log info", func(t *testing.T) {
t.Run("Should logger info", func(t *testing.T) {
text := "Log info test"

output := captureOutput(func() {
Info(text)
logging.Info(text)
})

assert.Equal(t, text, output["msg"])
assert.Equal(t, "INFO", output["level"])
})

t.Run("Should log fatal", func(t *testing.T) {
t.Run("Should logger fatal", func(t *testing.T) {
text := "Log fatal test"

assert.PanicsWithValue(t, text, func() { Fatal(text) })
assert.PanicsWithValue(t, text, func() { logging.Fatal(text) })
})

t.Run("Should log error", func(t *testing.T) {
t.Run("Should logger error", func(t *testing.T) {
text := "Log error test"

output := captureOutput(func() {
Error(text)
logging.Error(text)
})

assert.Equal(t, text, output["msg"])
assert.Equal(t, "ERROR", output["level"])
})

t.Run("Should log warn", func(t *testing.T) {
t.Run("Should logger warn", func(t *testing.T) {
text := "Log warn test"

output := captureOutput(func() {
Warn(text)
logging.Warn(text)
})

assert.Equal(t, text, output["msg"])
Expand All @@ -67,13 +68,13 @@ func TestDebug(t *testing.T) {
config.APP_TYPE = "service"
config.LOG_LEVEL = "debug"

_ = config.Load()
logging.InitializeLogger()

t.Run("Should log debug", func(t *testing.T) {
t.Run("Should logger debug", func(t *testing.T) {
text := "Log debug test"

output := captureOutput(func() {
Debug(text)
logging.Debug(text)
})

assert.Equal(t, text, output["msg"])
Expand Down
2 changes: 1 addition & 1 deletion pkg/base/monitoring/monitoring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func TestNonProductionMonitoring(t *testing.T) {
captureOutput := func(fn func()) (out map[string]any) {
var buf bytes.Buffer
config.LOG_OUTPUT = &buf
logging.CreateLogger()
logging.InitializeLogger()
fn()
_ = json.Unmarshal(buf.Bytes(), &out)
return
Expand Down

0 comments on commit 0b85e05

Please sign in to comment.