Skip to content

Commit

Permalink
feat: implement logger pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
sundowndev committed Nov 12, 2020
1 parent 493b5da commit 1d1235d
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 14 deletions.
5 changes: 5 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package api

import (
"errors"
_ "github.com/dreamvo/gilfoyle/api/docs"
"github.com/dreamvo/gilfoyle/config"
"github.com/dreamvo/gilfoyle/httputils"
Expand Down Expand Up @@ -53,6 +54,10 @@ func RegisterRoutes(r *gin.Engine) *gin.Engine {
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}

r.Use(func (ctx *gin.Context){
httputils.NewError(ctx, http.StatusNotFound, errors.New("resource not found"))
})

return r
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var rootCmd = &cobra.Command{

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file path")
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "Config file path")
}

func initConfig() {
Expand Down
55 changes: 50 additions & 5 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import (
"github.com/dreamvo/gilfoyle/api/db"
"github.com/dreamvo/gilfoyle/config"
"github.com/dreamvo/gilfoyle/ent/migrate"
"github.com/dreamvo/gilfoyle/logger"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"log"
"go.uber.org/zap"
"os"
)

var httpPort int
Expand All @@ -26,9 +28,21 @@ var serveCmd = &cobra.Command{
Use: "serve",
Short: "Launch the REST API",
Run: func(cmd *cobra.Command, args []string) {
logger := logger.New()

logger.Info("Initializing API server")
logger.Info("Environment", zap.Bool("debug", config.GetConfig().Settings.Debug))

if !config.GetConfig().Settings.Debug {
gin.SetMode(gin.ReleaseMode)
} else {
_ = os.Setenv("PGSSLMODE", "disable")
gin.SetMode(gin.DebugMode)
}

err := db.InitClient(config.GetConfig())
if err != nil {
log.Fatalf("failed opening connection: %v", err)
logger.Fatal("failed opening connection: %v", zap.Error(err))
}
defer db.Client.Close()

Expand All @@ -38,16 +52,47 @@ var serveCmd = &cobra.Command{
migrate.WithDropIndex(true),
migrate.WithDropColumn(true),
); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
logger.Fatal("failed creating schema resources", zap.Error(err))
}

router := gin.Default()
logger.Info("Successfully executed database auto migration")

router := gin.New()

router.Use(gin.Recovery())

router.Use(func(ctx *gin.Context) {
path := ctx.Request.URL.Path
raw := ctx.Request.URL.RawQuery
errorMsg := ctx.Errors.ByType(gin.ErrorTypePrivate).String()

if raw != "" {
path = path + "?" + raw
}

log := logger.With(
zap.String("Method", ctx.Request.Method),
zap.String("Path", path),
zap.Int("StatusCode", ctx.Writer.Status()),
zap.Int("BodySize", ctx.Writer.Size()),
zap.String("UserAgent", ctx.Request.UserAgent()),
)

if errorMsg != "" {
log.Error("Incoming HTTP Request",
zap.String("ErrorMessage", errorMsg),
)
return
}

log.Info("Incoming HTTP Request")
})

api.RegisterRoutes(router)

// Launch web server
if err := router.Run(fmt.Sprintf(":%d", httpPort)); err != nil {
fmt.Printf("error while launching web server: %e\n", err)
logger.Fatal("error while launching web server", zap.Error(err))
}
},
}
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type ServicesConfig struct {
type SettingsConfig struct {
ExposeSwaggerUI bool `yaml:"expose_swagger_ui" json:"expose_swagger_ui" default:"true"`
MaxFileSize string `yaml:"max_file_size" json:"max_file_size" default:"50Mi"`
Debug bool `yaml:"debug" json:"debug" default:"false" env:"DEBUG"`
}

type storageConfig struct {
Expand Down
4 changes: 3 additions & 1 deletion config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func TestConfig(t *testing.T) {
},
Settings: SettingsConfig{
ExposeSwaggerUI: true,
MaxFileSize: "50Mi"},
MaxFileSize: "50Mi",
Debug: false,
},
Storage: storageConfig{
Class: "fs",
Filesystem: FileSystemConfig{
Expand Down
24 changes: 24 additions & 0 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package logger

import (
"go.uber.org/zap"
"sync"
)

var (
once sync.Once
Logger *zap.Logger
)

func New() *zap.Logger {
once.Do(func() {
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}

Logger = logger
})

return Logger
}
28 changes: 22 additions & 6 deletions support/config/config.example.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
services:
db:
dialect: postgres
host: localhost
port: 5432
port: "5432"
user: postgres
password: secret
db_name: gilfoyle
redis:
host: localhost
port: 3482
database: "0"
port: "3482"
password: secret
ipfs:
gateway: gateway.ipfs.io
settings:
expose_swagger_ui: true
max_file_size: 50mb
serve_docs: true
storage:
class: fs
fs:
data_path: /data
s3:
hostname: ""
port: ""
access_key_id: ""
secret_access_key: ""
region: ""
bucket: ""
enable_ssl: true
use_path_style: false
gcs:
credentials_file: ""
bucket: ""
ipfs:
gateway: gateway.ipfs.io
4 changes: 3 additions & 1 deletion support/docker/docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ services:
context: ../../
dockerfile: support/docker/Dockerfile
command:
- "serve -p 3000"
- "serve"
- "-p"
- "3000"
ports:
- 3000:3000

Expand Down

0 comments on commit 1d1235d

Please sign in to comment.