Transition to new logger

This commit is contained in:
Melon 2024-05-13 20:06:17 +01:00
parent 77979c3527
commit 06c036817d
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
11 changed files with 44 additions and 32 deletions

View File

@ -10,6 +10,7 @@ import (
"github.com/1f349/tulip"
"github.com/1f349/tulip/database"
"github.com/1f349/tulip/database/types"
"github.com/1f349/tulip/logger"
"github.com/1f349/tulip/mail/templates"
"github.com/1f349/tulip/pages"
"github.com/1f349/tulip/server"
@ -17,7 +18,6 @@ import (
"github.com/google/subcommands"
_ "github.com/mattn/go-sqlite3"
"github.com/mrmelon54/exit-reload"
"log"
"os"
"path/filepath"
"time"
@ -40,19 +40,19 @@ func (s *serveCmd) Usage() string {
}
func (s *serveCmd) Execute(_ context.Context, _ *flag.FlagSet, _ ...any) subcommands.ExitStatus {
log.Println("[Tulip] Starting...")
logger.Logger.Info("Starting...")
if s.configPath == "" {
log.Println("[Tulip] Error: config flag is missing")
logger.Logger.Error("Config flag is missing")
return subcommands.ExitUsageError
}
openConf, err := os.Open(s.configPath)
if err != nil {
if os.IsNotExist(err) {
log.Println("[Tulip] Error: missing config file")
logger.Logger.Error("Missing config file")
} else {
log.Println("[Tulip] Error: open config file: ", err)
logger.Logger.Error("Open config file: ", err)
}
return subcommands.ExitFailure
}
@ -60,13 +60,13 @@ func (s *serveCmd) Execute(_ context.Context, _ *flag.FlagSet, _ ...any) subcomm
var config server.Conf
err = json.NewDecoder(openConf).Decode(&config)
if err != nil {
log.Println("[Tulip] Error: invalid config file: ", err)
logger.Logger.Error("Invalid config file: ", err)
return subcommands.ExitFailure
}
configPathAbs, err := filepath.Abs(s.configPath)
if err != nil {
log.Fatal("[Tulip] Failed to get absolute config path")
logger.Logger.Fatal("Failed to get absolute config path")
}
wd := filepath.Dir(configPathAbs)
normalLoad(config, wd)
@ -76,29 +76,29 @@ func (s *serveCmd) Execute(_ context.Context, _ *flag.FlagSet, _ ...any) subcomm
func normalLoad(startUp server.Conf, wd string) {
signingKey, err := mjwt.NewMJwtSignerFromFileOrCreate(startUp.OtpIssuer, filepath.Join(wd, "tulip.key.pem"), rand.Reader, 4096)
if err != nil {
log.Fatal("[Tulip] Failed to open signing key file:", err)
logger.Logger.Fatal("Failed to open signing key file:", err)
}
db, err := tulip.InitDB(filepath.Join(wd, "tulip.db.sqlite"))
if err != nil {
log.Fatal("[Tulip] Failed to open database:", err)
logger.Logger.Fatal("Failed to open database:", err)
}
log.Println("[Tulip] Checking database contains at least one user")
logger.Logger.Info("Checking database contains at least one user")
if err := checkDbHasUser(db); err != nil {
log.Fatal("[Tulip] Failed check:", err)
logger.Logger.Fatal("Failed check:", err)
}
if err = pages.LoadPages(wd); err != nil {
log.Fatal("[Tulip] Failed to load page templates:", err)
logger.Logger.Fatal("Failed to load page templates:", err)
}
if err := templates.LoadMailTemplates(wd); err != nil {
log.Fatal("[Tulip] Failed to load mail templates:", err)
logger.Logger.Fatal("Failed to load mail templates:", err)
}
srv := server.NewHttpServer(startUp, db, signingKey)
log.Printf("[Tulip] Starting HTTP server on '%s'\n", srv.Addr)
go utils.RunBackgroundHttp("HTTP", srv)
logger.Logger.Info("Starting server", "addr", srv.Addr)
go utils.RunBackgroundHttp(logger.Logger, srv)
exit_reload.ExitReload("Tulip", func() {}, func() {
// stop http server

View File

@ -3,6 +3,8 @@ package database
import (
"fmt"
"github.com/1f349/tulip/database/types"
"github.com/go-oauth2/oauth2/v4"
"github.com/hardfinhq/go-date"
"github.com/mrmelon54/pronouns"
"golang.org/x/text/language"
"net/url"

2
go.mod
View File

@ -6,7 +6,7 @@ require (
github.com/1f349/cache v0.0.3
github.com/1f349/mjwt v0.2.5
github.com/1f349/overlapfs v0.0.1
github.com/1f349/violet v0.0.13
github.com/1f349/violet v0.0.14
github.com/charmbracelet/log v0.4.0
github.com/emersion/go-message v0.18.1
github.com/emersion/go-sasl v0.0.0-20231106173351-e73c9f7bad43

1
go.sum
View File

@ -7,6 +7,7 @@ github.com/1f349/overlapfs v0.0.1 h1:LAxBolrXFAgU0yqZtXg/C/aaPq3eoQSPpBc49BHuTp0
github.com/1f349/overlapfs v0.0.1/go.mod h1:I6aItQycr7nrzplmfNXp/QF9tTmKRSgY3fXmu/7Ky2o=
github.com/1f349/violet v0.0.13 h1:lJpTz15Ea83Uc1VAISXTjtKuzr8Pe8NM4cMGp3Aiyhk=
github.com/1f349/violet v0.0.13/go.mod h1:Ga5/hWqI+EkR6J1mAMNzs7aJhuGcA89XFqgQaDXC7Jo=
github.com/1f349/violet v0.0.14/go.mod h1:iAREhm+wxnGXkmuvmBhOuhUx2T7/5w7stLYNgQGbqC8=
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=

12
logger/logger.go Normal file
View File

@ -0,0 +1,12 @@
package logger
import (
"github.com/charmbracelet/log"
"os"
)
var Logger = log.NewWithOptions(os.Stderr, log.Options{
ReportCaller: true,
ReportTimestamp: true,
Prefix: "Tulip",
})

View File

@ -4,10 +4,10 @@ import (
"embed"
"errors"
"github.com/1f349/overlapfs"
"github.com/1f349/tulip/logger"
htmlTemplate "html/template"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"sync"
@ -46,10 +46,10 @@ func LoadMailTemplates(wd string) (err error) {
func RenderMailTemplate(wrHtml, wrTxt io.Writer, name string, data any) {
err := mailHtmlTemplates.ExecuteTemplate(wrHtml, name+".go.html", data)
if err != nil {
log.Printf("Failed to render mail html: %s: %s\n", name, err)
logger.Logger.Warn("Failed to render mail html", "name", name, "err", err)
}
err = mailTextTemplates.ExecuteTemplate(wrTxt, name+".go.txt", data)
if err != nil {
log.Printf("Failed to render mail text: %s: %s\n", name, err)
logger.Logger.Warn("Failed to render mail text", "name", name, "err", err)
}
}

View File

@ -5,10 +5,10 @@ import (
_ "embed"
"errors"
"github.com/1f349/overlapfs"
"github.com/1f349/tulip/logger"
"html/template"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"sync"
@ -43,7 +43,7 @@ func LoadPages(wd string) (err error) {
func RenderPageTemplate(wr io.Writer, name string, data any) {
err := wwwTemplates.ExecuteTemplate(wr, name+".go.html", data)
if err != nil {
log.Printf("Failed to render page: %s: %s\n", name, err)
logger.Logger.Warn("Failed to render page", "name", name, "err", err)
}
}

View File

@ -2,7 +2,7 @@ package server
import (
"github.com/1f349/tulip/database"
"log"
"github.com/1f349/tulip/logger"
"net/http"
)
@ -13,7 +13,7 @@ func (h *HttpServer) DbTx(rw http.ResponseWriter, action func(db *database.Queri
err := action(h.db)
if err != nil {
http.Error(rw, "Database error", http.StatusInternalServerError)
log.Println("Database action error:", err)
logger.Logger.Warn("Database action error", "err", err)
return true
}

View File

@ -7,13 +7,13 @@ import (
"github.com/1f349/mjwt/auth"
"github.com/1f349/mjwt/claims"
"github.com/1f349/tulip/database"
"github.com/1f349/tulip/logger"
"github.com/1f349/tulip/pages"
"github.com/emersion/go-message/mail"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/julienschmidt/httprouter"
"golang.org/x/crypto/bcrypt"
"log"
"net/http"
"net/url"
"time"
@ -107,7 +107,7 @@ func (h *HttpServer) LoginPost(rw http.ResponseWriter, req *http.Request, _ http
"VerifyUrl": h.conf.BaseUrl + "/mail/verify/" + u,
})
if err != nil {
log.Println("[Tulip] Login: Failed to send verification email:", err)
logger.Logger.Warn("Login: Failed to send verification email", "err", err)
http.Error(rw, "500 Internal Server Error: Failed to send verification email", http.StatusInternalServerError)
return
}

View File

@ -4,11 +4,11 @@ import (
"errors"
"github.com/1f349/tulip/database"
"github.com/1f349/tulip/database/types"
"github.com/1f349/tulip/logger"
"github.com/1f349/tulip/pages"
"github.com/emersion/go-message/mail"
"github.com/google/uuid"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"net/url"
"strconv"
@ -142,7 +142,7 @@ func (h *HttpServer) ManageUsersPost(rw http.ResponseWriter, req *http.Request,
"RegisterUrl": h.conf.BaseUrl + "/mail/password/" + u,
})
if err != nil {
log.Println("[Tulip] Login: Failed to send register email:", err)
logger.Logger.Warn("Login: Failed to send register email:", "err", err)
http.Error(rw, "500 Internal Server Error: Failed to send register email", http.StatusInternalServerError)
return
}

View File

@ -10,6 +10,7 @@ import (
"github.com/1f349/mjwt"
clientStore "github.com/1f349/tulip/client-store"
"github.com/1f349/tulip/database"
"github.com/1f349/tulip/logger"
"github.com/1f349/tulip/openid"
scope2 "github.com/1f349/tulip/scope"
"github.com/1f349/tulip/theme"
@ -18,7 +19,6 @@ import (
"github.com/go-oauth2/oauth2/v4/server"
"github.com/go-oauth2/oauth2/v4/store"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"net/url"
"strings"
@ -64,7 +64,7 @@ func NewHttpServer(conf Conf, db *database.Queries, signingKey mjwt.Signer) *htt
openIdConf := openid.GenConfig(conf.BaseUrl, []string{"openid", "name", "username", "profile", "email", "birthdate", "age", "zoneinfo", "locale"}, []string{"sub", "name", "preferred_username", "profile", "picture", "website", "email", "email_verified", "gender", "birthdate", "zoneinfo", "locale", "updated_at"})
openIdBytes, err := json.Marshal(openIdConf)
if err != nil {
log.Fatalln("Failed to generate OpenID configuration:", err)
logger.Logger.Fatal("Failed to generate OpenID configuration", "err", err)
}
oauthManager := manage.NewDefaultManager()
@ -85,9 +85,6 @@ func NewHttpServer(conf Conf, db *database.Queries, signingKey mjwt.Signer) *htt
oauthManager.MapAccessGenerate(NewJWTAccessGenerate(hs.signingKey))
oauthManager.MapClientStorage(clientStore.New(db))
oauthSrv.SetResponseErrorHandler(func(re *errors.Response) {
log.Printf("Response error: %#v\n", re)
})
oauthSrv.SetClientInfoHandler(func(req *http.Request) (clientID, clientSecret string, err error) {
cId, cSecret, err := server.ClientBasicHandler(req)
if cId == "" && cSecret == "" {