Skip to content

Commit

Permalink
chore(logger): implement better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
EverythingSuckz committed Nov 25, 2023
1 parent ce801f4 commit 006fe3b
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 40 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ go.work
sessons/

# build folder
dist/
dist/

# logs folder
logs/
*.log
9 changes: 5 additions & 4 deletions bot/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package bot
import (
"EverythingSuckz/fsb/commands"
"EverythingSuckz/fsb/config"
"log"

"go.uber.org/zap"

"github.com/celestix/gotgproto"
"github.com/celestix/gotgproto/sessionMaker"
)

func StartClient() (*gotgproto.Client, error) {
func StartClient(log *zap.Logger) (*gotgproto.Client, error) {
client, err := gotgproto.NewClient(
int(config.ValueOf.ApiID),
config.ValueOf.ApiHash,
Expand All @@ -24,7 +25,7 @@ func StartClient() (*gotgproto.Client, error) {
if err != nil {
return nil, err
}
commands.Load(client.Dispatcher)
log.Println("Client started")
commands.Load(log, client.Dispatcher)
log.Info("Client started", zap.String("username", client.Self.Username))
return client, nil
}
11 changes: 6 additions & 5 deletions commands/commands.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
package commands

import (
"log"
"reflect"

"github.com/celestix/gotgproto/dispatcher"
"go.uber.org/zap"
)

type command struct {
log *zap.Logger
}

func Load(dispatcher dispatcher.Dispatcher) {
defer log.Println("Initialized")
Type := reflect.TypeOf(&command{})
Value := reflect.ValueOf(&command{})
func Load(log *zap.Logger, dispatcher dispatcher.Dispatcher) {
defer log.Info("Initialized all command handlers")
Type := reflect.TypeOf(&command{log})
Value := reflect.ValueOf(&command{log})
for i := 0; i < Type.NumMethod(); i++ {
Type.Method(i).Func.Call([]reflect.Value{Value, reflect.ValueOf(dispatcher)})
}
Expand Down
4 changes: 1 addition & 3 deletions commands/start.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package commands

import (
"log"

"github.com/celestix/gotgproto/dispatcher"
"github.com/celestix/gotgproto/dispatcher/handlers"
"github.com/celestix/gotgproto/ext"
)

func (m *command) LoadStart(dispatcher dispatcher.Dispatcher) {
defer log.Println("Loaded start command")
defer m.log.Sugar().Info("Loaded start command")
dispatcher.AddHandler(handlers.NewCommand("start", start))
}

Expand Down
13 changes: 7 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package config

import (
"log"
"strconv"
"strings"

_ "github.com/joho/godotenv/autoload"
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap"
)

var ValueOf = &config{}
Expand All @@ -27,17 +27,18 @@ func (c *config) setupEnvVars() {
}
}

func Load() {
func Load(log *zap.Logger) {
ValueOf.setupEnvVars()
ValueOf.LogChannelID = int64(stripInt(int(ValueOf.LogChannelID)))
log.Println("Loaded config")
ValueOf.LogChannelID = int64(stripInt(log, int(ValueOf.LogChannelID)))
log.Info("Loaded config")
}
func stripInt(a int) int {

func stripInt(log *zap.Logger, a int) int {
strA := strconv.Itoa(abs(a))
lastDigits := strings.Replace(strA, "100", "", 1)
result, err := strconv.Atoi(lastDigits)
if err != nil {
log.Println(err)
log.Sugar().Fatalln(err)
return 0
}
return result
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,6 @@ require (
golang.org/x/sys v0.14.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down
58 changes: 42 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,79 @@
package main

import (
"EverythingSuckz/fsb/bot"
"EverythingSuckz/fsb/config"
"EverythingSuckz/fsb/routes"
"EverythingSuckz/fsb/types"
"EverythingSuckz/fsb/utils"
"EverythingSuckz/fsb/bot"
"fmt"
"log"
"net/http"
"os"
"time"

"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)

const versionString = "v0.0.1"

var startTime time.Time = time.Now()

func main() {
log.Println("Starting server...")
config.Load()
router := getRouter()
log := initLogger()
log.Info("Starting server...")
config.Load(log)
router := getRouter(log)

_, err := bot.StartClient()
_, err := bot.StartClient(log)
if err != nil {
log.Println(err)
log.Info(err.Error())
return
}
log.Printf("Server started at: http://localhost:%d\n", config.ValueOf.Port)
log.Info("Server started", zap.Int("port", config.ValueOf.Port))
log.Info("File Stream Bot", zap.String("version", versionString))
err = router.Run(fmt.Sprintf(":%d", config.ValueOf.Port))
if err != nil {
log.Println(err)
log.Sugar().Fatalln(err)
}

}

// TODO: Use zap logger
func initLogger() *zap.Logger {
logger, err := zap.NewProduction()
if err != nil {
log.Fatalf("can't initialize zap logger: %v", err)
customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("02/01/2006 03:04 PM"))
}
defer logger.Sync()
consoleConfig := zap.NewDevelopmentEncoderConfig()
consoleConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
consoleConfig.EncodeTime = customTimeEncoder
consoleEncoder := zapcore.NewConsoleEncoder(consoleConfig)
defaultLogLevel := zapcore.DebugLevel

fileEncoderConfig := zap.NewProductionEncoderConfig()
fileEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
fileEncoder := zapcore.NewJSONEncoder(fileEncoderConfig)

fileWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: "logs/app.log",
MaxSize: 10,
MaxBackups: 3,
MaxAge: 7,
Compress: true,
})

core := zapcore.NewTee(
zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), defaultLogLevel),
zapcore.NewCore(fileEncoder, fileWriter, defaultLogLevel),
)

logger := zap.New(core, zap.AddStacktrace(zapcore.ErrorLevel))
return logger

}

func getRouter() *gin.Engine {
func getRouter(log *zap.Logger) *gin.Engine {
if config.ValueOf.Dev {
gin.SetMode(gin.DebugMode)
} else {
Expand All @@ -63,6 +89,6 @@ func getRouter() *gin.Engine {
Version: versionString,
})
})
routes.Load(router)
routes.Load(log, router)
return router
}
11 changes: 6 additions & 5 deletions routes/routes.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package routes

import (
"log"
"reflect"

"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

type Route struct {
Expand All @@ -17,14 +17,15 @@ func (r *Route) Init(engine *gin.Engine) {
}

type allRoutes struct {
log *zap.Logger
}

func Load(r *gin.Engine) {
defer log.Println("Loaded all API Routes")
func Load(log *zap.Logger, r *gin.Engine) {
defer log.Sugar().Info("Loaded all API Routes")
route := &Route{Name: "/", Engine: r}
route.Init(r)
Type := reflect.TypeOf(&allRoutes{})
Value := reflect.ValueOf(&allRoutes{})
Type := reflect.TypeOf(&allRoutes{log})
Value := reflect.ValueOf(&allRoutes{log})
for i := 0; i < Type.NumMethod(); i++ {
Type.Method(i).Func.Call([]reflect.Value{Value, reflect.ValueOf(route)})
}
Expand Down

0 comments on commit 006fe3b

Please sign in to comment.