Sentry Logger (Examples)
https://github.com/getsentry/sentry-go
#Examples
// - hello-world.go -
package main
import (
"errors"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/getsentry/sentry-go"
)
var (
errIsOne = errors.New("This is One Error")
errIsTwo = errors.New("This is Two Error")
errIsThree = fmt.Errorf("This is Three Error: %w", errIsTwo)
errIsFour = errors.New("This is Four Error")
)
func main() {
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
Debug: true,
AttachStacktrace: true,
Environment: "development",
IgnoreErrors: []string{
errIsTwo.Error(),
},
ServerName: "service_name",
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetExtra("character.name", "Mighty Fighter")
})
defer sentry.Flush(2 * time.Second)
wg := &sync.WaitGroup{}
wg.Add(1)
time.AfterFunc(5*time.Second, func() {
wg.Done()
})
sentry.CaptureException(errIsFour)
wg.Wait()
}
// - echo.go -
package main
import (
"fmt"
"net/http"
"time"
"github.com/getsentry/sentry-go"
sentryecho "github.com/getsentry/sentry-go/echo"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
func main() {
err := sentry.Init(sentry.ClientOptions{
Dsn: "https://hello@world.io/1337",
Debug: true,
AttachStacktrace: true,
// Transport: &devNullTransport{},
})
fmt.Println(err)
app := echo.New()
app.Use(middleware.Logger())
app.Use(middleware.Recover())
app.Use(sentryecho.New(sentryecho.Options{
Repanic: true,
WaitForDelivery: false,
}))
app.GET("/", func(ctx echo.Context) error {
return ctx.String(200, "ok")
})
app.GET("/bar", func(ctx echo.Context) error {
return ctx.String(http.StatusOK, "Hello, World!")
})
app.GET("/fo1", func(ctx echo.Context) error {
panic("its me again!")
})
app.Logger.Fatal(app.Start(":3000"))
}
// - features.go -
package main
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"github.com/getsentry/sentry-go"
)
func prettyPrint(v interface{}) string {
pp, _ := json.MarshalIndent(v, "", " ")
return string(pp)
}
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
func recoverHandler() {
defer sentry.Recover()
panic("ups")
}
func captureMessage() {
sentry.CaptureMessage("say what again. SAY WHAT again")
}
func configureScope() {
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetExtra("oristhis", "justfantasy")
scope.SetTag("isthis", "reallife")
scope.SetLevel(sentry.LevelFatal)
scope.SetUser(sentry.User{
ID: "1337",
})
})
}
func withScope() {
sentry.WithScope(func(scope *sentry.Scope) {
scope.SetLevel(sentry.LevelFatal)
sentry.CaptureException(errors.New("say what again. SAY WHAT again"))
})
}
func addBreadcrumbs() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Random breadcrumb 1",
})
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Random breadcrumb 2",
})
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Random breadcrumb 3",
})
}
func withScopeAndConfigureScope() {
sentry.WithScope(func(scope *sentry.Scope) {
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetExtras(map[string]interface{}{
"istillcant": 42,
"believe": "that",
})
scope.SetTags(map[string]string{
"italready": "works",
"just": "likethat",
})
})
event := sentry.NewEvent()
event.Message = "say what again. SAY WHAT again"
sentry.CaptureEvent(event)
})
}
type CustomComplexError struct {
Message string
AnswerToLife int
}
func (e CustomComplexError) Error() string {
return "CustomComplexError: " + e.Message
}
func (e CustomComplexError) GimmeMoreData() string {
return strconv.Itoa(e.AnswerToLife)
}
func eventHint() {
sentry.CaptureException(CustomComplexError{Message: "Captured", AnswerToLife: 42})
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Debug: true,
// Dsn: "https://hello@world.io/1337",
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if ex, ok := hint.OriginalException.(CustomComplexError); ok {
event.Message = event.Message + " - " + ex.GimmeMoreData()
}
fmt.Printf("%s\n\n", prettyPrint(event))
return event
},
BeforeBreadcrumb: func(breadcrumb *sentry.Breadcrumb, _ *sentry.BreadcrumbHint) *sentry.Breadcrumb {
if breadcrumb.Message == "Random breadcrumb 3" {
breadcrumb.Message = "Not so random breadcrumb 3"
}
fmt.Printf("%s\n\n", prettyPrint(breadcrumb))
return breadcrumb
},
SampleRate: 1,
Transport: &devNullTransport{},
Integrations: func(integrations []sentry.Integration) []sentry.Integration {
return append(integrations, integrations[1])
},
}); err != nil {
panic(err)
}
defer sentry.Flush(2 * time.Second)
configureScope()
withScope()
captureMessage()
addBreadcrumbs()
withScopeAndConfigureScope()
recoverHandler()
eventHint()
}
// - flush.go -
package main
import (
"fmt"
"time"
"github.com/getsentry/sentry-go"
)
func main() {
_ = sentry.Init(sentry.ClientOptions{
Dsn: "https://hello@world.io/1337",
Debug: true,
})
sentry.CaptureMessage("Event #1")
sentry.CaptureMessage("Event #2")
sentry.CaptureMessage("Event #3")
go func() {
sentry.CaptureMessage("Event #4")
sentry.CaptureMessage("Event #5")
}()
fmt.Println("=> Flushing transport buffer")
if sentry.Flush(time.Second * 2) {
fmt.Println("=> All queued events delivered!")
} else {
fmt.Println("=> Flush timeout reached")
}
}
#Stack Panic
// - main.go -
package main
import (
"log"
"os"
"time"
"github.com/getsentry/sentry-go"
)
func main() {
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
Debug: true,
AttachStacktrace: true,
Environment: "production",
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)
defer sentry.Recover()
func1()
}
// - panic.go -
package main
import "errors"
//go:noinline
func func1() {
func2()
}
//go:noinline
func func2() {
func3()
}
//go:noinline
func func3() {
func4()
}
//go:noinline
func func4() {
func5()
}
//go:noinline
func func5() {
panic(errors.New("ooops"))
}
#With Extras
// - with-extra-1.go -
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/getsentry/sentry-go"
)
func prettyPrint(v interface{}) string {
pp, _ := json.MarshalIndent(v, "", " ")
return string(pp)
}
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
type CustomComplexError struct {
Message string
MoreData map[string]string
}
func (e CustomComplexError) Error() string {
return "CustomComplexError: " + e.Message
}
func (e CustomComplexError) GimmeMoreData() map[string]string {
return e.MoreData
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Debug: true,
Dsn: "https://hello@world.io/1337",
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
// Solution 1 (use beforeSend, which will be applied to
// all events and is usually application specific):
if ex, ok := hint.OriginalException.(CustomComplexError); ok {
for key, val := range ex.GimmeMoreData() {
event.Extra[key] = val
}
}
fmt.Printf("%s\n\n", prettyPrint(event.Extra))
return event
},
Transport: &devNullTransport{},
}); err != nil {
panic(err)
}
sentry.CaptureException(CustomComplexError{
Message: "say what again. SAY WHAT again",
MoreData: map[string]string{
"say": "wat1",
},
})
}
// - with-extra-2.go -
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/getsentry/sentry-go"
)
func prettyPrint(v interface{}) string {
pp, _ := json.MarshalIndent(v, "", " ")
return string(pp)
}
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
type CustomComplexError struct {
Message string
MoreData map[string]string
}
func (e CustomComplexError) Error() string {
return "CustomComplexError: " + e.Message
}
func (e CustomComplexError) GimmeMoreData() map[string]string {
return e.MoreData
}
type ExtractExtra struct{}
func (ee ExtractExtra) Name() string {
return "ExtractExtra"
}
func (ee ExtractExtra) SetupOnce(client *sentry.Client) {
client.AddEventProcessor(func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if ex, ok := hint.OriginalException.(CustomComplexError); ok {
for key, val := range ex.GimmeMoreData() {
event.Extra[key] = val
}
}
fmt.Printf("%s\n\n", prettyPrint(event.Extra))
return event
})
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Debug: true,
Dsn: "https://hello@world.io/1337",
Transport: &devNullTransport{},
Integrations: func(integrations []sentry.Integration) []sentry.Integration {
return append(integrations, new(ExtractExtra))
},
}); err != nil {
panic(err)
}
sentry.CaptureException(CustomComplexError{
Message: "say what again. SAY WHAT again",
MoreData: map[string]string{
"say": "wat1",
},
})
}
// - with-extra-3.go -
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/getsentry/sentry-go"
)
func prettyPrint(v interface{}) string {
pp, _ := json.MarshalIndent(v, "", " ")
return string(pp)
}
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
type CustomComplexError struct {
Message string
MoreData map[string]string
}
func (e CustomComplexError) Error() string {
return "CustomComplexError: " + e.Message
}
func (e CustomComplexError) GimmeMoreData() map[string]string {
return e.MoreData
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Debug: true,
Dsn: "https://hello@world.io/1337",
Transport: &devNullTransport{},
}); err != nil {
panic(err)
}
// Solution 3 and 4 (use scope event processors, which can be either
// applied to all events - if used with ConfigureScope or per
// event/block if used with WithScope):
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.AddEventProcessor(func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if ex, ok := hint.OriginalException.(CustomComplexError); ok {
for key, val := range ex.GimmeMoreData() {
event.Extra[key] = val
}
}
fmt.Printf("%s\n\n", prettyPrint(event.Extra))
return event
})
})
sentry.CaptureException(CustomComplexError{
Message: "say what again. SAY WHAT again",
MoreData: map[string]string{
"say": "wat1",
},
})
}
// - with-extra-4.go -
package main
import (
"fmt"
"time"
"github.com/getsentry/sentry-go"
)
type devNullTransport struct{}
func (t *devNullTransport) Configure(options sentry.ClientOptions) {
dsn, _ := sentry.NewDsn(options.Dsn)
fmt.Println()
fmt.Println("Store Endpoint:", dsn.StoreAPIURL())
fmt.Println("Headers:", dsn.RequestHeaders())
fmt.Println()
}
func (t *devNullTransport) SendEvent(event *sentry.Event) {
fmt.Println("Faked Transport")
}
func (t *devNullTransport) Flush(timeout time.Duration) bool {
return true
}
type CustomComplexError struct {
Message string
MoreData map[string]string
}
func (e CustomComplexError) Error() string {
return "CustomComplexError: " + e.Message
}
func (e CustomComplexError) GimmeMoreData() map[string]string {
return e.MoreData
}
func main() {
if err := sentry.Init(sentry.ClientOptions{
Debug: true,
Dsn: "https://hello@world.io/1337",
Transport: &devNullTransport{},
}); err != nil {
panic(err)
}
sentry.WithScope(func(scope *sentry.Scope) {
err := CustomComplexError{
Message: "say what again. SAY WHAT again",
MoreData: map[string]string{
"say": "wat1",
},
}
for key, val := range err.GimmeMoreData() {
scope.SetExtra(key, val)
}
sentry.CaptureException(err)
})
}