go: fully switch to slogging
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
leo 2023-04-19 05:30:52 +02:00
parent c6378d7dd3
commit aadb409606
Signed by: wanderer
SSH Key Fingerprint: SHA256:Dp8+iwKHSlrMEHzE3bJnPng70I7LEsa3IJXRH/U+idQ
5 changed files with 59 additions and 49 deletions

View File

@ -3,17 +3,16 @@ package app
import (
"embed"
"errors"
"log"
"os"
"git.dotya.ml/mirre-mt/pcmt/config"
"git.dotya.ml/mirre-mt/pcmt/ent"
"git.dotya.ml/mirre-mt/pcmt/slogging"
"github.com/labstack/echo/v4"
)
type App struct {
e *echo.Echo
logger *log.Logger
logger *slogging.Logger
initialised bool
embeds Embeds
config *config.Config
@ -31,24 +30,24 @@ type Embeds struct {
}
// Init allows setting App's important fields - once.
func (a *App) Init(version string, conf *config.Config, dbclient *ent.Client) error {
func (a *App) Init(version string, logger *slogging.Logger, conf *config.Config, dbclient *ent.Client) error {
if !a.initialised {
e := echo.New()
a.e = e
a.logger = log.New(os.Stderr, "*** pcmt:", log.Ldate|log.Ltime|log.Lshortfile)
a.logger = logger
a.Logger().Printf("app version: %s", version)
a.Logger().Infof("app version: %s", version)
a.version = version
a.Logger().Printf("setting app config to %#v", conf)
a.config = conf
a.Logger().Printf("app config set to %#v", a.config)
a.Logger().Infof("app config set to %#v", a.config)
a.Logger().Print("saving client conn to db")
a.Logger().Info("saving db connection string")
a.db = dbclient
a.initialised = true
a.Logger().Info("app initialised")
return nil
}
@ -56,37 +55,33 @@ func (a *App) Init(version string, conf *config.Config, dbclient *ent.Client) er
return errors.New("ErrAppAlreadyInitialised")
}
// E returns app's *echo.Echo.
// E returns app's *echo.Echo instance.
func (a *App) E() *echo.Echo {
return a.e
}
// Logger returns app's *log.Logger.
func (a *App) Logger() *log.Logger {
// Logger returns app's logger instance.
func (a *App) Logger() *slogging.Logger {
return a.logger
}
// SetEmbeds saves the embedded files to application state.
func (a *App) SetEmbeds(templates, assets embed.FS) {
a.logger.Info("setting embeds")
a.embeds.templates = templates
a.embeds.assets = assets
}
// SetDevel puts the app in devel mode, which loads browser-sync script in
// SetDevel puts the app in devel mode, which loads a browser-sync script in
// templates and expects browser-sync running.
func (a *App) SetDevel() {
if !a.Config().DevelMode {
a.Logger().Print("overriding configuration value of DevelMode based on a flag")
a.Logger().Info("overriding configuration value of DevelMode based on a flag")
a.Config().DevelMode = true
return
}
a.Logger().Print("setting DevelMode based on a flag")
a.Logger().Info("setting DevelMode based on a flag")
a.develMode = true
}
// func (a *App) SetVersion(version string) {
// a.Logger().Printf("setting app version to %s", version)
// a.version = version
// }

View File

@ -1,20 +1,19 @@
package app
import (
"fmt"
"io/fs"
"log"
"net/http"
"os"
)
func (a *App) getAssets(live bool) http.FileSystem {
if live {
log.Print("assets - live mode")
a.logger.Info("assets loaded in live mode")
return http.FS(os.DirFS("static"))
}
log.Print("assets - embed mode")
a.logger.Info("assets loaded in embed mode")
fsys, err := fs.Sub(a.embeds.assets, "static")
if err != nil {
@ -24,29 +23,28 @@ func (a *App) getAssets(live bool) http.FileSystem {
return http.FS(fsys)
}
// func (a *App) getTemplates(live bool) http.FileSystem {
func (a *App) getTemplates(live bool) fs.FS {
if live {
log.Print("tmpls - live mode")
// return http.FS(os.DirFS("../templates"))
entries, err := os.ReadDir("templates")
a.logger.Info("templates loaded in live mode")
_, err := os.ReadDir("templates")
if err != nil {
a.Logger().Error("templates dir does not exist or is not accessible, check permissions")
panic(err)
}
for _, e := range entries {
fmt.Println(e.Name())
}
return os.DirFS("templates")
}
log.Print("tmpls - embed mode")
a.logger.Info("templates loaded in embed mode")
fsys, err := fs.Sub(a.embeds.templates, "templates")
if err != nil {
panic(err)
}
// return http.FS(fsys)
// alt:
// func (a *App) getTemplates(live bool) http.FileSystem {
// return http.FS(os.DirFS("../templates"))
return fsys
}

View File

@ -23,15 +23,13 @@ func (a *App) Config() *config.Config {
// PrintConfiguration outputs relevant settings of the application to console.
func (a *App) PrintConfiguration() {
a.Logger().Print("app configuration options")
if a.Config() != nil {
if a.Config().LiveMode {
a.Logger().Print("live mode enabled")
a.Logger().Info("app config: live mode enabled")
}
if a.Config().DevelMode {
a.Logger().Print("devel mode enabled - make sure that browser-sync is running")
a.Logger().Info("app config: devel mode enabled - make sure that browser-sync is running")
}
return

11
main.go
View File

@ -1,10 +1,17 @@
package main
import "log"
import (
"os"
"golang.org/x/exp/slog"
)
func main() {
err := run()
if err != nil {
log.Fatalln(err)
l := slog.New(slog.NewJSONHandler(os.Stderr))
// log.Fatalln(err)
l.Error("error running app:", err)
os.Exit(1)
}
}

32
run.go
View File

@ -2,9 +2,9 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
@ -17,6 +17,7 @@ import (
"git.dotya.ml/mirre-mt/pcmt/app"
"git.dotya.ml/mirre-mt/pcmt/config"
"git.dotya.ml/mirre-mt/pcmt/ent"
"git.dotya.ml/mirre-mt/pcmt/slogging"
)
const (
@ -52,6 +53,9 @@ var (
// "/": "templates/index.tmpl",
// }
version = "dev"
log *slogging.Logger
ErrCouldNotInitialiseLogger = errors.New("Could not initialise logger")
)
func run() error {
@ -59,6 +63,13 @@ func run() error {
flag.Parse()
err := slogging.Init(true)
if err != nil {
return ErrCouldNotInitialiseLogger
}
log = slogging.GetLogger()
// TODO: allow different configuration formats (toml, ni)
// TODO: rename main.go to pcmt.go
// TODO: add .golangci-lint
@ -70,20 +81,20 @@ func run() error {
conf, err := config.LoadConfig(*configFlag)
if err != nil {
log.Println("error loading config file", *configFlag)
log.Errorf("error loading config file at '%s', bailing", *configFlag)
return err
}
// for "github.com/xiaoqidun/entps".
connstr := "file:ent?mode=memory&cache=shared&_fk=1"
log.Printf("connecting to db at '%s'", connstr)
log.Infof("connecting to db at '%s'", connstr)
db, err := ent.Open("sqlite3", connstr)
if err != nil {
return fmt.Errorf("failed to open a connection to sqlite: %v", err)
}
defer db.Close()
log.Println("attempting to automatically migrate db schema")
log.Info("attempting to automatically migrate db schema")
// Run the auto migration tool.
if err = db.Schema.Create(context.Background()); err != nil {
return fmt.Errorf("failed creating schema resources: %v", err)
@ -91,7 +102,7 @@ func run() error {
a := &app.App{}
err = a.Init(version, conf, db)
err = a.Init(version, log, conf, db)
if err != nil {
return err
}
@ -100,8 +111,6 @@ func run() error {
a.SetupRoutes()
logger := a.Logger()
a.SetEchoSettings()
// a.SetConfig(conf)
@ -121,7 +130,7 @@ func run() error {
e := a.E()
go func() {
if err = e.Start(*addr); err != nil && err != http.ErrServerClosed {
logger.Println("shutting down the server")
log.Info("shutting down the server")
}
}()
@ -132,13 +141,16 @@ func run() error {
signal.Notify(quit, syscall.SIGHUP)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
shutdownTimeout := 10 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer func() {
logger.Println("Interrupt received, gracefully shutting down the server")
log.Infof("Interrupt received, gracefully shutting down the server (timeout %s)", shutdownTimeout)
cancel()
log.Info("Bye!")
}()
if err = e.Shutdown(ctx); err != nil {
log.Error("There was an error shutting the server down")
return err
}