Skip to content

Commit

Permalink
feat(logger): Use sentryhttp instead of logging manually
Browse files Browse the repository at this point in the history
  • Loading branch information
exler committed Jan 13, 2024
1 parent 69effb0 commit 8231b31
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 36 deletions.
7 changes: 3 additions & 4 deletions cmd/runserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"log"

"github.com/exler/fileigloo/logger"
"github.com/exler/fileigloo/server"
"github.com/urfave/cli/v2"
)
Expand All @@ -30,7 +29,7 @@ var serverCmd = &cli.Command{
},
&cli.IntFlag{
Name: "rate-limit",
Value: 20,
Value: 100,
EnvVars: []string{"RATE_LIMIT"},
},
&cli.StringFlag{
Expand All @@ -40,7 +39,6 @@ var serverCmd = &cli.Command{
},
&cli.StringFlag{
Name: "site-password",
Value: "",
Usage: "Password to protect the site with",
EnvVars: []string{"SITE_PASSWORD"},
},
Expand Down Expand Up @@ -79,6 +77,7 @@ var serverCmd = &cli.Command{
},
&cli.StringFlag{
Name: "sentry-environment",
Value: "undefined",
EnvVars: []string{"SENTRY_ENVIRONMENT"},
},
},
Expand All @@ -87,7 +86,7 @@ var serverCmd = &cli.Command{
server.Port(cCtx.Int("port")),
server.MaxUploadSize(cCtx.Int64("max-upload-size")),
server.MaxRequests(cCtx.Int("rate-limit")),
server.UseLogger(logger.NewLogger(cCtx.String("sentry-dsn"), cCtx.String("sentry-environment"))),
server.Sentry(cCtx.String("sentry-dsn"), cCtx.String("sentry-environment")),
server.ExtraFooterText(cCtx.String("extra-footer")),
server.SitePassword(cCtx.String("site-password")),
}
Expand Down
27 changes: 2 additions & 25 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,25 @@ import (
"log"
"os"

"github.com/getsentry/sentry-go"
colors "github.com/logrusorgru/aurora/v4"
)

type Logger struct {
*log.Logger

sentryHub *sentry.Hub
}

func NewLogger(sentry_dsn, sentry_environment string) *Logger {
var sentryHub *sentry.Hub
if sentry_dsn != "" {
var sentryClient *sentry.Client
var err error
if sentryClient, err = sentry.NewClient(sentry.ClientOptions{
Dsn: sentry_dsn,
Environment: sentry_environment,
}); err != nil {
log.Fatal(err)
}
sentryHub = sentry.NewHub(sentryClient, sentry.NewScope())
}

func NewLogger() *Logger {
return &Logger{
Logger: log.New(os.Stderr, "[fileigloo] ", log.LstdFlags),
sentryHub: sentryHub,
Logger: log.New(os.Stderr, "[fileigloo] ", log.LstdFlags),
}
}

func (l *Logger) Error(err error) {
l.Logger.Print(colors.Red(err.Error()).String())
if l.sentryHub != nil {
l.sentryHub.CaptureException(err)
}
}

func (l *Logger) Info(msg string) {
l.Logger.Print(msg)
if l.sentryHub != nil {
l.sentryHub.CaptureMessage(msg)
}
}

func (l *Logger) Debug(msg string) {
Expand Down
42 changes: 35 additions & 7 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import (

"github.com/exler/fileigloo/logger"
"github.com/exler/fileigloo/storage"
"github.com/getsentry/sentry-go"
sentryhttp "github.com/getsentry/sentry-go/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
"golang.org/x/crypto/bcrypt"
)
Expand Down Expand Up @@ -39,9 +42,22 @@ func UseStorage(storage storage.Storage) OptionFn {
}
}

func UseLogger(logger *logger.Logger) OptionFn {
func Sentry(sentryDSN, sentryEnvironment string) OptionFn {
return func(s *Server) {
s.logger = logger
if sentryDSN == "" {
return
}

err := sentry.Init(sentry.ClientOptions{
Dsn: sentryDSN,
Environment: sentryEnvironment,
EnableTracing: true,
TracesSampleRate: 0.5,
})
if err != nil {
s.logger.Error(err)
}
defer sentry.Flush(time.Second)
}
}

Expand All @@ -65,7 +81,7 @@ func SitePassword(password string) OptionFn {

sitePasswordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
s.logger.Fatal(err)
s.logger.Error(err)
}

s.sitePasswordHash = string(sitePasswordHash)
Expand Down Expand Up @@ -93,7 +109,9 @@ type Server struct {
}

func New(options ...OptionFn) *Server {
s := &Server{}
s := &Server{
logger: logger.NewLogger(),
}
for _, optionFn := range options {
optionFn(s)
}
Expand All @@ -104,23 +122,33 @@ func (s *Server) Run() {
fs := http.FileServer(http.FS(StaticFS))

limiter := httprate.LimitByIP(s.maxRequests, 1*time.Minute)
sentryMiddleware := sentryhttp.New(sentryhttp.Options{
Repanic: true,
})

s.router = chi.NewRouter()
s.router.Use(middleware.Logger)
s.router.Use(middleware.Recoverer)
s.router.Use(limiter)

s.protectedRouter = chi.NewRouter()
s.protectedRouter.Use(limiter)
s.router.Use(sentryMiddleware.Handle)

s.router.Handle("/static/*", fs)
s.router.Get("/{view:(?:view)}/{fileId}", s.downloadHandler)
s.router.Get("/{fileId}", s.downloadHandler)

s.protectedRouter = chi.NewRouter()
s.protectedRouter.Use(middleware.Logger)
s.protectedRouter.Use(middleware.Recoverer)
s.protectedRouter.Use(limiter)

if s.sitePasswordHash != "" {
s.router.Get("/login", s.loginGETHandler)
s.router.Post("/login", s.loginPOSTHandler)
s.protectedRouter.Use(SitePasswordMiddleware(s.sitePasswordHash))
}

s.protectedRouter.Use(sentryMiddleware.Handle)

s.protectedRouter.Get("/", s.indexHandler)
s.protectedRouter.Post("/", s.formHandler)

Expand Down

0 comments on commit 8231b31

Please sign in to comment.