{{.error}}+ Request ID
{{.requestID}}
diff --git a/.golangci.yml b/.golangci.yml
index e4f777334..fcfbdee76 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -14,7 +14,6 @@ run:
linters:
# enable some extra linters, see here for the list: https://golangci-lint.run/usage/linters/
enable:
- - contextcheck
- forcetypeassert
- goconst
- gocritic
@@ -27,3 +26,8 @@ linters-settings:
govet:
disable:
- composites
+ staticcheck:
+ # Enable all checks
+ # Disable:
+ # - SA1012: nil context passing
+ checks: ["all", "-SA1012"]
diff --git a/cmd/gotosocial/action/admin/media/prune/orphaned.go b/cmd/gotosocial/action/admin/media/prune/orphaned.go
index d8dcec9a4..31196531b 100644
--- a/cmd/gotosocial/action/admin/media/prune/orphaned.go
+++ b/cmd/gotosocial/action/admin/media/prune/orphaned.go
@@ -42,9 +42,9 @@
}
if dry /* dick heyyoooooo */ {
- log.Infof("DRY RUN: %d items are orphaned and eligible to be pruned", pruned)
+ log.Infof(ctx, "DRY RUN: %d items are orphaned and eligible to be pruned", pruned)
} else {
- log.Infof("%d orphaned items were pruned", pruned)
+ log.Infof(ctx, "%d orphaned items were pruned", pruned)
}
return prune.shutdown(ctx)
diff --git a/cmd/gotosocial/action/admin/media/prune/remote.go b/cmd/gotosocial/action/admin/media/prune/remote.go
index 473c1d3e4..329f04a94 100644
--- a/cmd/gotosocial/action/admin/media/prune/remote.go
+++ b/cmd/gotosocial/action/admin/media/prune/remote.go
@@ -49,9 +49,9 @@
total := pruned + uncached
if dry /* dick heyyoooooo */ {
- log.Infof("DRY RUN: %d remote items are unused/stale and eligible to be pruned", total)
+ log.Infof(ctx, "DRY RUN: %d remote items are unused/stale and eligible to be pruned", total)
} else {
- log.Infof("%d unused/stale remote items were pruned", pruned)
+ log.Infof(ctx, "%d unused/stale remote items were pruned", pruned)
}
return prune.shutdown(ctx)
diff --git a/cmd/gotosocial/action/server/server.go b/cmd/gotosocial/action/server/server.go
index 89486a5dc..388a88533 100644
--- a/cmd/gotosocial/action/server/server.go
+++ b/cmd/gotosocial/action/server/server.go
@@ -62,7 +62,7 @@
// Start creates and starts a gotosocial server
var Start action.GTSAction = func(ctx context.Context) error {
- _, err := maxprocs.Set(maxprocs.Logger(log.Debugf))
+ _, err := maxprocs.Set(nil)
if err != nil {
return fmt.Errorf("failed to set CPU limits from cgroup: %s", err)
}
@@ -156,6 +156,9 @@
// attach global middlewares which are used for every request
router.AttachGlobalMiddleware(
+ middleware.AddRequestID(config.GetRequestIDHeader()),
+ // note: hooks adding ctx fields must be ABOVE
+ // the logger, otherwise won't be accessible.
middleware.Logger(),
middleware.UserAgent(),
middleware.CORS(),
@@ -237,13 +240,13 @@
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigs // block until signal received
- log.Infof("received signal %s, shutting down", sig)
+ log.Infof(ctx, "received signal %s, shutting down", sig)
// close down all running services in order
if err := gts.Stop(ctx); err != nil {
return fmt.Errorf("error closing gotosocial service: %s", err)
}
- log.Info("done! exiting...")
+ log.Info(ctx, "done! exiting...")
return nil
}
diff --git a/cmd/gotosocial/action/testrig/testrig.go b/cmd/gotosocial/action/testrig/testrig.go
index baf63a78a..3be7907fe 100644
--- a/cmd/gotosocial/action/testrig/testrig.go
+++ b/cmd/gotosocial/action/testrig/testrig.go
@@ -155,7 +155,7 @@
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
sig := <-sigs
- log.Infof("received signal %s, shutting down", sig)
+ log.Infof(ctx, "received signal %s, shutting down", sig)
testrig.StandardDBTeardown(dbService)
testrig.StandardStorageTeardown(storageBackend)
@@ -165,6 +165,6 @@
return fmt.Errorf("error closing gotosocial service: %s", err)
}
- log.Info("done! exiting...")
+ log.Info(ctx, "done! exiting...")
return nil
}
diff --git a/docs/configuration/observability.md b/docs/configuration/observability.md
new file mode 100644
index 000000000..0d5f9e864
--- /dev/null
+++ b/docs/configuration/observability.md
@@ -0,0 +1,16 @@
+# Observability
+
+These settings let you tune and configure certain observability related behaviours.
+
+## Settings
+
+```yaml
+##################################
+##### OBSERVABILITY SETTINGS #####
+##################################
+
+# String. Header name to use to extract a request or trace ID from. Typically set by a
+# loadbalancer or proxy.
+# Default: "X-Request-Id"
+request-id-header: "X-Request-Id"
+```
diff --git a/example/config.yaml b/example/config.yaml
index 48aa021d3..2fab24ab8 100644
--- a/example/config.yaml
+++ b/example/config.yaml
@@ -692,6 +692,15 @@ syslog-protocol: "udp"
# Default: "localhost:514"
syslog-address: "localhost:514"
+##################################
+##### OBSERVABILITY SETTINGS #####
+##################################
+
+# String. Header name to use to extract a request or trace ID from. Typically set by a
+# loadbalancer or proxy.
+# Default: "X-Request-Id"
+request-id-header: "X-Request-Id"
+
#############################
##### ADVANCED SETTINGS #####
#############################
diff --git a/internal/api/client/media/mediacreate_test.go b/internal/api/client/media/mediacreate_test.go
index 320636721..8a94646ac 100644
--- a/internal/api/client/media/mediacreate_test.go
+++ b/internal/api/client/media/mediacreate_test.go
@@ -100,7 +100,7 @@ func (suite *MediaCreateTestSuite) SetupSuite() {
func (suite *MediaCreateTestSuite) TearDownSuite() {
if err := suite.db.Stop(context.Background()); err != nil {
- log.Panicf("error closing db connection: %s", err)
+ log.Panicf(nil, "error closing db connection: %s", err)
}
}
diff --git a/internal/api/client/media/mediaupdate_test.go b/internal/api/client/media/mediaupdate_test.go
index 1425d80ef..8f4470132 100644
--- a/internal/api/client/media/mediaupdate_test.go
+++ b/internal/api/client/media/mediaupdate_test.go
@@ -98,7 +98,7 @@ func (suite *MediaUpdateTestSuite) SetupSuite() {
func (suite *MediaUpdateTestSuite) TearDownSuite() {
if err := suite.db.Stop(context.Background()); err != nil {
- log.Panicf("error closing db connection: %s", err)
+ log.Panicf(nil, "error closing db connection: %s", err)
}
}
diff --git a/internal/api/client/streaming/stream.go b/internal/api/client/streaming/stream.go
index 99d8b23e1..a03f36d16 100644
--- a/internal/api/client/streaming/stream.go
+++ b/internal/api/client/streaming/stream.go
@@ -166,11 +166,12 @@ func (m *Module) StreamGETHandler(c *gin.Context) {
return
}
- l := log.WithFields(kv.Fields{
- {"account", account.Username},
- {"streamID", stream.ID},
- {"streamType", streamType},
- }...)
+ l := log.WithContext(c.Request.Context()).
+ WithFields(kv.Fields{
+ {"account", account.Username},
+ {"streamID", stream.ID},
+ {"streamType", streamType},
+ }...)
// Upgrade the incoming HTTP request, which hijacks the underlying
// connection and reuses it for the websocket (non-http) protocol.
diff --git a/internal/api/fileserver/fileserver_test.go b/internal/api/fileserver/fileserver_test.go
index 01e090cc7..5b139454e 100644
--- a/internal/api/fileserver/fileserver_test.go
+++ b/internal/api/fileserver/fileserver_test.go
@@ -99,7 +99,7 @@ func (suite *FileserverTestSuite) SetupTest() {
func (suite *FileserverTestSuite) TearDownSuite() {
if err := suite.db.Stop(context.Background()); err != nil {
- log.Panicf("error closing db connection: %s", err)
+ log.Panicf(nil, "error closing db connection: %s", err)
}
}
diff --git a/internal/api/fileserver/servefile.go b/internal/api/fileserver/servefile.go
index ec70ef9ae..a344e3e53 100644
--- a/internal/api/fileserver/servefile.go
+++ b/internal/api/fileserver/servefile.go
@@ -77,7 +77,10 @@ func (m *Module) ServeFile(c *gin.Context) {
return
}
- content, errWithCode := m.processor.FileGet(c.Request.Context(), authed, &apimodel.GetContentRequestForm{
+ // Acquire context from gin request.
+ ctx := c.Request.Context()
+
+ content, errWithCode := m.processor.FileGet(ctx, authed, &apimodel.GetContentRequestForm{
AccountID: accountID,
MediaType: mediaType,
MediaSize: mediaSize,
@@ -101,7 +104,7 @@ func (m *Module) ServeFile(c *gin.Context) {
defer func() {
// Close content when we're done, catch errors.
if err := content.Content.Close(); err != nil {
- log.Errorf("ServeFile: error closing readcloser: %s", err)
+ log.Errorf(ctx, "ServeFile: error closing readcloser: %s", err)
}
}()
@@ -130,15 +133,21 @@ func (m *Module) ServeFile(c *gin.Context) {
return
}
- // Set known content-type and serve this file range.
+ // Set known content-type and serve range.
c.Header("Content-Type", format)
- serveFileRange(c.Writer, content.Content, rng, content.ContentLength)
+ serveFileRange(
+ c.Writer,
+ c.Request,
+ content.Content,
+ rng,
+ content.ContentLength,
+ )
}
// serveFileRange serves the range of a file from a given source reader, without the
// need for implementation of io.Seeker. Instead we read the first 'start' many bytes
// into a discard reader. Code is adapted from https://codeberg.org/gruf/simplehttp.
-func serveFileRange(rw http.ResponseWriter, src io.Reader, rng string, size int64) {
+func serveFileRange(rw http.ResponseWriter, r *http.Request, src io.Reader, rng string, size int64) {
var i int
if i = strings.IndexByte(rng, '='); i < 0 {
@@ -219,7 +228,7 @@ func serveFileRange(rw http.ResponseWriter, src io.Reader, rng string, size int6
// Dump the first 'start' many bytes into the void...
if _, err := fastcopy.CopyN(io.Discard, src, start); err != nil {
- log.Errorf("error reading from source: %v", err)
+ log.Errorf(r.Context(), "error reading from source: %v", err)
return
}
@@ -239,7 +248,7 @@ func serveFileRange(rw http.ResponseWriter, src io.Reader, rng string, size int6
// Read the "seeked" source reader into destination writer.
if _, err := fastcopy.Copy(rw, src); err != nil {
- log.Errorf("error reading from source: %v", err)
+ log.Errorf(r.Context(), "error reading from source: %v", err)
return
}
}
diff --git a/internal/api/util/errorhandling.go b/internal/api/util/errorhandling.go
index 414b8d7e8..c0f02d114 100644
--- a/internal/api/util/errorhandling.go
+++ b/internal/api/util/errorhandling.go
@@ -27,6 +27,7 @@
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/log"
+ "github.com/superseriousbusiness/gotosocial/internal/middleware"
)
// TODO: add more templated html pages here for different error types
@@ -43,16 +44,20 @@
func NotFoundHandler(c *gin.Context, instanceGet func(ctx context.Context) (*apimodel.InstanceV1, gtserror.WithCode), accept string) {
switch accept {
case string(TextHTML):
- instance, err := instanceGet(c.Request.Context())
+ ctx := c.Request.Context()
+ instance, err := instanceGet(ctx)
if err != nil {
panic(err)
}
c.HTML(http.StatusNotFound, "404.tmpl", gin.H{
- "instance": instance,
+ "instance": instance,
+ "requestID": middleware.RequestID(ctx),
})
default:
- c.JSON(http.StatusNotFound, gin.H{"error": http.StatusText(http.StatusNotFound)})
+ c.JSON(http.StatusNotFound, gin.H{
+ "error": http.StatusText(http.StatusNotFound),
+ })
}
}
@@ -62,15 +67,17 @@ func NotFoundHandler(c *gin.Context, instanceGet func(ctx context.Context) (*api
func genericErrorHandler(c *gin.Context, instanceGet func(ctx context.Context) (*apimodel.InstanceV1, gtserror.WithCode), accept string, errWithCode gtserror.WithCode) {
switch accept {
case string(TextHTML):
- instance, err := instanceGet(c.Request.Context())
+ ctx := c.Request.Context()
+ instance, err := instanceGet(ctx)
if err != nil {
panic(err)
}
c.HTML(errWithCode.Code(), "error.tmpl", gin.H{
- "instance": instance,
- "code": errWithCode.Code(),
- "error": errWithCode.Safe(),
+ "instance": instance,
+ "code": errWithCode.Code(),
+ "error": errWithCode.Safe(),
+ "requestID": middleware.RequestID(ctx),
})
default:
c.JSON(errWithCode.Code(), gin.H{"error": errWithCode.Safe()})
@@ -108,11 +115,12 @@ func ErrorHandler(c *gin.Context, errWithCode gtserror.WithCode, instanceGet fun
// to pass any detailed errors (that might contain sensitive information) into the
// errWithCode.Error() field, since the client will see this. Use your noggin!
func OAuthErrorHandler(c *gin.Context, errWithCode gtserror.WithCode) {
- l := log.WithFields(kv.Fields{
- {"path", c.Request.URL.Path},
- {"error", errWithCode.Error()},
- {"help", errWithCode.Safe()},
- }...)
+ l := log.WithContext(c.Request.Context()).
+ WithFields(kv.Fields{
+ {"path", c.Request.URL.Path},
+ {"error", errWithCode.Error()},
+ {"help", errWithCode.Safe()},
+ }...)
statusCode := errWithCode.Code()
diff --git a/internal/cache/util.go b/internal/cache/util.go
index 0b22f4b49..76917c415 100644
--- a/internal/cache/util.go
+++ b/internal/cache/util.go
@@ -35,5 +35,5 @@ func tryUntil(msg string, count int, do func() bool) {
return
}
}
- log.Panicf("failed %s after %d tries", msg, count)
+ log.Panicf(nil, "failed %s after %d tries", msg, count)
}
diff --git a/internal/concurrency/workers.go b/internal/concurrency/workers.go
index a27e5d115..d782d3f42 100644
--- a/internal/concurrency/workers.go
+++ b/internal/concurrency/workers.go
@@ -66,7 +66,7 @@ func NewWorkerPool[MsgType any](workers int, queueRatio int) *WorkerPool[MsgType
}
// Log new worker creation with worker type prefix
- log.Infof("%s created with workers=%d queue=%d",
+ log.Infof(nil, "%s created with workers=%d queue=%d",
w.wtype,
workers,
workers*queueRatio,
@@ -77,7 +77,7 @@ func NewWorkerPool[MsgType any](workers int, queueRatio int) *WorkerPool[MsgType
// Start will attempt to start the underlying worker pool, or return error.
func (w *WorkerPool[MsgType]) Start() error {
- log.Infof("%s starting", w.wtype)
+ log.Infof(nil, "%s starting", w.wtype)
// Check processor was set
if w.process == nil {
@@ -94,7 +94,7 @@ func (w *WorkerPool[MsgType]) Start() error {
// Stop will attempt to stop the underlying worker pool, or return error.
func (w *WorkerPool[MsgType]) Stop() error {
- log.Infof("%s stopping", w.wtype)
+ log.Infof(nil, "%s stopping", w.wtype)
// Attempt to stop pool
if !w.workers.Stop() {
@@ -107,14 +107,14 @@ func (w *WorkerPool[MsgType]) Stop() error {
// SetProcessor will set the Worker's processor function, which is called for each queued message.
func (w *WorkerPool[MsgType]) SetProcessor(fn func(context.Context, MsgType) error) {
if w.process != nil {
- log.Panicf("%s Worker.process is already set", w.wtype)
+ log.Panicf(nil, "%s Worker.process is already set", w.wtype)
}
w.process = fn
}
// Queue will queue provided message to be processed with there's a free worker.
func (w *WorkerPool[MsgType]) Queue(msg MsgType) {
- log.Tracef("%s queueing message: %+v", w.wtype, msg)
+ log.Tracef(nil, "%s queueing message: %+v", w.wtype, msg)
// Create new process function for msg
process := func(ctx context.Context) {
diff --git a/internal/config/config.go b/internal/config/config.go
index 516fb11d6..1dea90788 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -147,6 +147,8 @@ type Configuration struct {
AdminAccountPassword string `name:"password" usage:"the password to set for this account"`
AdminTransPath string `name:"path" usage:"the path of the file to import from/export to"`
AdminMediaPruneDryRun bool `name:"dry-run" usage:"perform a dry run and only log number of items eligible for pruning"`
+
+ RequestIDHeader string `name:"request-id-header" usage:"Header to extract the Request ID from. Eg.,'X-Request-Id'"`
}
type CacheConfiguration struct {
diff --git a/internal/config/defaults.go b/internal/config/defaults.go
index 709f063ca..528419e97 100644
--- a/internal/config/defaults.go
+++ b/internal/config/defaults.go
@@ -163,4 +163,6 @@
},
AdminMediaPruneDryRun: true,
+
+ RequestIDHeader: "X-Request-Id",
}
diff --git a/internal/config/flags.go b/internal/config/flags.go
index d8c31368b..3ef44bf62 100644
--- a/internal/config/flags.go
+++ b/internal/config/flags.go
@@ -140,6 +140,8 @@ func (s *ConfigState) AddServerFlags(cmd *cobra.Command) {
cmd.Flags().Int(AdvancedRateLimitRequestsFlag(), cfg.AdvancedRateLimitRequests, fieldtag("AdvancedRateLimitRequests", "usage"))
cmd.Flags().Int(AdvancedThrottlingMultiplierFlag(), cfg.AdvancedThrottlingMultiplier, fieldtag("AdvancedThrottlingMultiplier", "usage"))
cmd.Flags().Duration(AdvancedThrottlingRetryAfterFlag(), cfg.AdvancedThrottlingRetryAfter, fieldtag("AdvancedThrottlingRetryAfter", "usage"))
+
+ cmd.Flags().String(RequestIDHeaderFlag(), cfg.RequestIDHeader, fieldtag("RequestIDHeader", "usage"))
})
}
diff --git a/internal/config/helpers.gen.go b/internal/config/helpers.gen.go
index 64e7d02f7..1a4c14a82 100644
--- a/internal/config/helpers.gen.go
+++ b/internal/config/helpers.gen.go
@@ -2977,3 +2977,28 @@ func GetAdminMediaPruneDryRun() bool { return global.GetAdminMediaPruneDryRun()
// SetAdminMediaPruneDryRun safely sets the value for global configuration 'AdminMediaPruneDryRun' field
func SetAdminMediaPruneDryRun(v bool) { global.SetAdminMediaPruneDryRun(v) }
+
+// GetRequestIDHeader safely fetches the Configuration value for state's 'RequestIDHeader' field
+func (st *ConfigState) GetRequestIDHeader() (v string) {
+ st.mutex.Lock()
+ v = st.config.RequestIDHeader
+ st.mutex.Unlock()
+ return
+}
+
+// SetRequestIDHeader safely sets the Configuration value for state's 'RequestIDHeader' field
+func (st *ConfigState) SetRequestIDHeader(v string) {
+ st.mutex.Lock()
+ defer st.mutex.Unlock()
+ st.config.RequestIDHeader = v
+ st.reloadToViper()
+}
+
+// RequestIDHeaderFlag returns the flag name for the 'RequestIDHeader' field
+func RequestIDHeaderFlag() string { return "request-id-header" }
+
+// GetRequestIDHeader safely fetches the value for global configuration 'RequestIDHeader' field
+func GetRequestIDHeader() string { return global.GetRequestIDHeader() }
+
+// SetRequestIDHeader safely sets the value for global configuration 'RequestIDHeader' field
+func SetRequestIDHeader(v string) { global.SetRequestIDHeader(v) }
diff --git a/internal/config/testdata/test.yaml b/internal/config/testdata/test.yaml
index 87fe105d2..c2d902944 100644
--- a/internal/config/testdata/test.yaml
+++ b/internal/config/testdata/test.yaml
@@ -415,4 +415,13 @@ cache:
gts:
account-max-size: 99
account-ttl: "3h"
- account-sweep-freq: "1s"
\ No newline at end of file
+ account-sweep-freq: "1s"
+
+##################################
+##### OBSERVABILITY SETTINGS #####
+##################################
+
+# String. Header name to use to extract a request or trace ID from. Typically set by a
+# loadbalancer or proxy.
+# Default: "X-Request-Id"
+request-id-header: "X-Trace-Id"
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 765739d6c..866ec1be1 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -55,7 +55,7 @@ func Validate() error {
// no problem
break
case "http":
- log.Warnf("%s was set to 'http'; this should *only* be used for debugging and tests!", ProtocolFlag())
+ log.Warnf(nil, "%s was set to 'http'; this should *only* be used for debugging and tests!", ProtocolFlag())
case "":
errs = append(errs, fmt.Errorf("%s must be set", ProtocolFlag()))
default:
diff --git a/internal/db/bundb/account.go b/internal/db/bundb/account.go
index 9fdd28342..937f4ba23 100644
--- a/internal/db/bundb/account.go
+++ b/internal/db/bundb/account.go
@@ -146,7 +146,7 @@ func (a *accountDB) getAccount(ctx context.Context, lookup string, dbQuery func(
// Set the account's related avatar
account.AvatarMediaAttachment, err = a.state.DB.GetAttachmentByID(ctx, account.AvatarMediaAttachmentID)
if err != nil {
- log.Errorf("error getting account %s avatar: %v", account.ID, err)
+ log.Errorf(ctx, "error getting account %s avatar: %v", account.ID, err)
}
}
@@ -154,7 +154,7 @@ func (a *accountDB) getAccount(ctx context.Context, lookup string, dbQuery func(
// Set the account's related header
account.HeaderMediaAttachment, err = a.state.DB.GetAttachmentByID(ctx, account.HeaderMediaAttachmentID)
if err != nil {
- log.Errorf("error getting account %s header: %v", account.ID, err)
+ log.Errorf(ctx, "error getting account %s header: %v", account.ID, err)
}
}
@@ -162,7 +162,7 @@ func (a *accountDB) getAccount(ctx context.Context, lookup string, dbQuery func(
// Set the account's related emojis
account.Emojis, err = a.state.DB.GetEmojisByIDs(ctx, account.EmojiIDs)
if err != nil {
- log.Errorf("error getting account %s emojis: %v", account.ID, err)
+ log.Errorf(ctx, "error getting account %s emojis: %v", account.ID, err)
}
}
@@ -412,7 +412,7 @@ func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, li
Where("? != '{}'", bun.Ident("status.attachments")).
Where("? != '[]'", bun.Ident("status.attachments"))
default:
- log.Panic("db dialect was neither pg nor sqlite")
+ log.Panic(ctx, "db dialect was neither pg nor sqlite")
return q
}
})
@@ -540,7 +540,7 @@ func (a *accountDB) statusesFromIDs(ctx context.Context, statusIDs []string) ([]
// Fetch from status from database by ID
status, err := a.state.DB.GetStatusByID(ctx, id)
if err != nil {
- log.Errorf("statusesFromIDs: error getting status %q: %v", id, err)
+ log.Errorf(ctx, "error getting status %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/admin.go b/internal/db/bundb/admin.go
index 3c0415dca..a4bc46a73 100644
--- a/internal/db/bundb/admin.go
+++ b/internal/db/bundb/admin.go
@@ -93,7 +93,7 @@ func (a *adminDB) IsEmailAvailable(ctx context.Context, email string) (bool, db.
func (a *adminDB) NewSignup(ctx context.Context, username string, reason string, requireApproval bool, email string, password string, signUpIP net.IP, locale string, appID string, emailVerified bool, externalID string, admin bool) (*gtsmodel.User, db.Error) {
key, err := rsa.GenerateKey(rand.Reader, rsaKeyBits)
if err != nil {
- log.Errorf("error creating new rsa key: %s", err)
+ log.Errorf(ctx, "error creating new rsa key: %s", err)
return nil, err
}
@@ -107,7 +107,7 @@ func (a *adminDB) NewSignup(ctx context.Context, username string, reason string,
Scan(ctx); err != nil {
err = a.conn.ProcessError(err)
if err != db.ErrNoEntries {
- log.Errorf("error checking for existing account: %s", err)
+ log.Errorf(ctx, "error checking for existing account: %s", err)
return nil, err
}
@@ -207,13 +207,13 @@ func (a *adminDB) CreateInstanceAccount(ctx context.Context) db.Error {
return err
}
if exists {
- log.Infof("instance account %s already exists", username)
+ log.Infof(ctx, "instance account %s already exists", username)
return nil
}
key, err := rsa.GenerateKey(rand.Reader, rsaKeyBits)
if err != nil {
- log.Errorf("error creating new rsa key: %s", err)
+ log.Errorf(ctx, "error creating new rsa key: %s", err)
return err
}
@@ -245,7 +245,7 @@ func (a *adminDB) CreateInstanceAccount(ctx context.Context) db.Error {
return err
}
- log.Infof("instance account %s CREATED with id %s", username, acct.ID)
+ log.Infof(ctx, "instance account %s CREATED with id %s", username, acct.ID)
return nil
}
@@ -265,7 +265,7 @@ func (a *adminDB) CreateInstanceInstance(ctx context.Context) db.Error {
return err
}
if exists {
- log.Infof("instance entry already exists")
+ log.Infof(ctx, "instance entry already exists")
return nil
}
@@ -290,6 +290,6 @@ func (a *adminDB) CreateInstanceInstance(ctx context.Context) db.Error {
return a.conn.ProcessError(err)
}
- log.Infof("created instance instance %s with id %s", host, i.ID)
+ log.Infof(ctx, "created instance instance %s with id %s", host, i.ID)
return nil
}
diff --git a/internal/db/bundb/basic.go b/internal/db/bundb/basic.go
index d4de3f37e..71a603593 100644
--- a/internal/db/bundb/basic.go
+++ b/internal/db/bundb/basic.go
@@ -165,6 +165,6 @@ func (b *basicDB) IsHealthy(ctx context.Context) db.Error {
}
func (b *basicDB) Stop(ctx context.Context) db.Error {
- log.Info("closing db connection")
+ log.Info(ctx, "closing db connection")
return b.conn.Close()
}
diff --git a/internal/db/bundb/bundb.go b/internal/db/bundb/bundb.go
index 990eccb6b..1d0ea4822 100644
--- a/internal/db/bundb/bundb.go
+++ b/internal/db/bundb/bundb.go
@@ -100,11 +100,11 @@ func doMigration(ctx context.Context, db *bun.DB) error {
}
if group.ID == 0 {
- log.Info("there are no new migrations to run")
+ log.Info(ctx, "there are no new migrations to run")
return nil
}
- log.Infof("MIGRATED DATABASE TO %s", group)
+ log.Infof(ctx, "MIGRATED DATABASE TO %s", group)
return nil
}
@@ -245,7 +245,7 @@ func pgConn(ctx context.Context) (*DBConn, error) {
return nil, fmt.Errorf("postgres ping: %s", err)
}
- log.Info("connected to POSTGRES database")
+ log.Info(ctx, "connected to POSTGRES database")
return conn, nil
}
@@ -268,7 +268,7 @@ func sqliteConn(ctx context.Context) (*DBConn, error) {
}
if address == ":memory:" {
- log.Warn("using sqlite in-memory mode; all data will be deleted when gts shuts down; this mode should only be used for debugging or running tests")
+ log.Warn(ctx, "using sqlite in-memory mode; all data will be deleted when gts shuts down; this mode should only be used for debugging or running tests")
// Use random name for in-memory instead of ':memory:', so
// multiple in-mem databases can be created without conflict.
@@ -319,7 +319,7 @@ func sqliteConn(ctx context.Context) (*DBConn, error) {
}
return nil, fmt.Errorf("sqlite ping: %s", err)
}
- log.Infof("connected to SQLITE database with address %s", address)
+ log.Infof(ctx, "connected to SQLITE database with address %s", address)
return conn, nil
}
@@ -464,7 +464,7 @@ func sqlitePragmas(ctx context.Context, conn *DBConn) error {
return fmt.Errorf("error scanning sqlite pragma %s: %w", pv, err)
}
- log.Infof("sqlite pragma %s set to %s", pk, res)
+ log.Infof(ctx, "sqlite pragma %s set to %s", pk, res)
}
return nil
diff --git a/internal/db/bundb/emoji.go b/internal/db/bundb/emoji.go
index afca3da33..802a57ae8 100644
--- a/internal/db/bundb/emoji.go
+++ b/internal/db/bundb/emoji.go
@@ -372,7 +372,7 @@ func (e *emojiDB) GetEmojisByIDs(ctx context.Context, emojiIDs []string) ([]*gts
for _, id := range emojiIDs {
emoji, err := e.GetEmojiByID(ctx, id)
if err != nil {
- log.Errorf("emojisFromIDs: error getting emoji %q: %v", id, err)
+ log.Errorf(ctx, "emojisFromIDs: error getting emoji %q: %v", id, err)
continue
}
@@ -405,7 +405,7 @@ func (e *emojiDB) GetEmojiCategoriesByIDs(ctx context.Context, emojiCategoryIDs
for _, id := range emojiCategoryIDs {
emojiCategory, err := e.GetEmojiCategory(ctx, id)
if err != nil {
- log.Errorf("emojiCategoriesFromIDs: error getting emoji category %q: %v", id, err)
+ log.Errorf(ctx, "error getting emoji category %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/hook.go b/internal/db/bundb/hook.go
index e4c44a294..e0a132bd0 100644
--- a/internal/db/bundb/hook.go
+++ b/internal/db/bundb/hook.go
@@ -36,17 +36,18 @@ func (queryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Con
}
// AfterQuery logs the time taken to query, the operation (select, update, etc), and the query itself as translated by bun.
-func (queryHook) AfterQuery(_ context.Context, event *bun.QueryEvent) {
+func (queryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
// Get the DB query duration
dur := time.Since(event.StartTime)
switch {
// Warn on slow database queries
case dur > time.Second:
- log.WithFields(kv.Fields{
- {"duration", dur},
- {"query", event.Query},
- }...).Warn("SLOW DATABASE QUERY")
+ log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"duration", dur},
+ {"query", event.Query},
+ }...).Warn("SLOW DATABASE QUERY")
// On trace, we log query information,
// manually crafting so DB query not escaped.
diff --git a/internal/db/bundb/media.go b/internal/db/bundb/media.go
index ee2bea6e5..6975df85f 100644
--- a/internal/db/bundb/media.go
+++ b/internal/db/bundb/media.go
@@ -58,7 +58,7 @@ func (m *mediaDB) getAttachments(ctx context.Context, ids []string) ([]*gtsmodel
// Attempt fetch from DB
attachment, err := m.GetAttachmentByID(ctx, id)
if err != nil {
- log.Errorf("error getting attachment %q: %v", id, err)
+ log.Errorf(ctx, "error getting attachment %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/mention.go b/internal/db/bundb/mention.go
index 4a50c1ebd..c894fbdd8 100644
--- a/internal/db/bundb/mention.go
+++ b/internal/db/bundb/mention.go
@@ -64,7 +64,7 @@ func (m *mentionDB) GetMentions(ctx context.Context, ids []string) ([]*gtsmodel.
// Attempt fetch from DB
mention, err := m.GetMention(ctx, id)
if err != nil {
- log.Errorf("GetMentions: error getting mention %q: %v", id, err)
+ log.Errorf(ctx, "error getting mention %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/migrations/20220916122701_emojis_in_accounts.go b/internal/db/bundb/migrations/20220916122701_emojis_in_accounts.go
index c72fc830e..207ac036a 100644
--- a/internal/db/bundb/migrations/20220916122701_emojis_in_accounts.go
+++ b/internal/db/bundb/migrations/20220916122701_emojis_in_accounts.go
@@ -38,7 +38,7 @@ func init() {
case dialect.SQLite:
q = q.ColumnExpr("? VARCHAR", bun.Ident("emojis"))
default:
- log.Panic("db dialect was neither pg nor sqlite")
+ log.Panic(ctx, "db dialect was neither pg nor sqlite")
}
if _, err := q.Exec(ctx); err != nil {
diff --git a/internal/db/bundb/notification.go b/internal/db/bundb/notification.go
index ec29f3d28..1884cbeff 100644
--- a/internal/db/bundb/notification.go
+++ b/internal/db/bundb/notification.go
@@ -94,7 +94,7 @@ func (n *notificationDB) GetNotifications(ctx context.Context, accountID string,
// Attempt fetch from DB
notif, err := n.GetNotification(ctx, id)
if err != nil {
- log.Errorf("GetNotifications: error getting notification %q: %v", id, err)
+ log.Errorf(ctx, "error getting notification %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/report.go b/internal/db/bundb/report.go
index baf11ddb0..1294bcf98 100644
--- a/internal/db/bundb/report.go
+++ b/internal/db/bundb/report.go
@@ -106,7 +106,7 @@ func (r *reportDB) GetReports(ctx context.Context, resolved *bool, accountID str
for _, id := range reportIDs {
report, err := r.GetReportByID(ctx, id)
if err != nil {
- log.Errorf("GetReports: error getting report %q: %v", id, err)
+ log.Errorf(ctx, "error getting report %q: %v", id, err)
continue
}
diff --git a/internal/db/bundb/status.go b/internal/db/bundb/status.go
index 709105f72..2bec07759 100644
--- a/internal/db/bundb/status.go
+++ b/internal/db/bundb/status.go
@@ -74,7 +74,7 @@ func (s *statusDB) GetStatuses(ctx context.Context, ids []string) ([]*gtsmodel.S
// Attempt fetch from DB
status, err := s.GetStatusByID(ctx, id)
if err != nil {
- log.Errorf("GetStatuses: error getting status %q: %v", id, err)
+ log.Errorf(ctx, "error getting status %q: %v", id, err)
continue
}
@@ -387,7 +387,7 @@ func (s *statusDB) GetStatusChildren(ctx context.Context, status *gtsmodel.Statu
// only append children, not the overall parent status
entry, ok := e.Value.(*gtsmodel.Status)
if !ok {
- log.Panic("GetStatusChildren: found status could not be asserted to *gtsmodel.Status")
+ log.Panic(ctx, "found status could not be asserted to *gtsmodel.Status")
}
if entry.ID != status.ID {
@@ -412,7 +412,7 @@ func (s *statusDB) statusChildren(ctx context.Context, status *gtsmodel.Status,
if err := q.Scan(ctx, &childIDs); err != nil {
if err != sql.ErrNoRows {
- log.Errorf("statusChildren: error getting children for %q: %v", status.ID, err)
+ log.Errorf(ctx, "error getting children for %q: %v", status.ID, err)
}
return
}
@@ -421,7 +421,7 @@ func (s *statusDB) statusChildren(ctx context.Context, status *gtsmodel.Status,
// Fetch child with ID from database
child, err := s.GetStatusByID(ctx, id)
if err != nil {
- log.Errorf("statusChildren: error getting child status %q: %v", id, err)
+ log.Errorf(ctx, "error getting child status %q: %v", id, err)
continue
}
@@ -429,7 +429,7 @@ func (s *statusDB) statusChildren(ctx context.Context, status *gtsmodel.Status,
for e := foundStatuses.Front(); e != nil; e = e.Next() {
entry, ok := e.Value.(*gtsmodel.Status)
if !ok {
- log.Panic("statusChildren: found status could not be asserted to *gtsmodel.Status")
+ log.Panic(ctx, "found status could not be asserted to *gtsmodel.Status")
}
if child.InReplyToAccountID != "" && entry.ID == child.InReplyToID {
diff --git a/internal/db/bundb/timeline.go b/internal/db/bundb/timeline.go
index 3340acf94..c499993e3 100644
--- a/internal/db/bundb/timeline.go
+++ b/internal/db/bundb/timeline.go
@@ -114,7 +114,7 @@ func (t *timelineDB) GetHomeTimeline(ctx context.Context, accountID string, maxI
// Fetch status from db for ID
status, err := t.state.DB.GetStatusByID(ctx, id)
if err != nil {
- log.Errorf("GetHomeTimeline: error fetching status %q: %v", id, err)
+ log.Errorf(ctx, "error fetching status %q: %v", id, err)
continue
}
@@ -182,7 +182,7 @@ func (t *timelineDB) GetPublicTimeline(ctx context.Context, maxID string, sinceI
// Fetch status from db for ID
status, err := t.state.DB.GetStatusByID(ctx, id)
if err != nil {
- log.Errorf("GetPublicTimeline: error fetching status %q: %v", id, err)
+ log.Errorf(ctx, "error fetching status %q: %v", id, err)
continue
}
@@ -242,7 +242,7 @@ func (t *timelineDB) GetFavedTimeline(ctx context.Context, accountID string, max
// Fetch status from db for corresponding favourite
status, err := t.state.DB.GetStatusByID(ctx, fave.StatusID)
if err != nil {
- log.Errorf("GetFavedTimeline: error fetching status for fave %q: %v", fave.ID, err)
+ log.Errorf(ctx, "error fetching status for fave %q: %v", fave.ID, err)
continue
}
diff --git a/internal/email/confirm.go b/internal/email/confirm.go
index aba09a664..087da92c2 100644
--- a/internal/email/confirm.go
+++ b/internal/email/confirm.go
@@ -42,7 +42,7 @@ func (s *sender) SendConfirmEmail(toAddress string, data ConfirmData) error {
if err != nil {
return err
}
- log.Trace(s.hostAddress + "\n" + config.GetSMTPUsername() + ":password" + "\n" + s.from + "\n" + toAddress + "\n\n" + string(msg) + "\n")
+ log.Trace(nil, s.hostAddress+"\n"+config.GetSMTPUsername()+":password"+"\n"+s.from+"\n"+toAddress+"\n\n"+string(msg)+"\n")
return smtp.SendMail(s.hostAddress, s.auth, s.from, []string{toAddress}, msg)
}
diff --git a/internal/email/noopsender.go b/internal/email/noopsender.go
index bf691b8bb..2277490e1 100644
--- a/internal/email/noopsender.go
+++ b/internal/email/noopsender.go
@@ -61,7 +61,7 @@ func (s *noopSender) SendConfirmEmail(toAddress string, data ConfirmData) error
return err
}
- log.Tracef("NOT SENDING confirmation email to %s with contents: %s", toAddress, msg)
+ log.Tracef(nil, "NOT SENDING confirmation email to %s with contents: %s", toAddress, msg)
if s.sendCallback != nil {
s.sendCallback(toAddress, string(msg))
@@ -81,7 +81,7 @@ func (s *noopSender) SendResetEmail(toAddress string, data ResetData) error {
return err
}
- log.Tracef("NOT SENDING reset email to %s with contents: %s", toAddress, msg)
+ log.Tracef(nil, "NOT SENDING reset email to %s with contents: %s", toAddress, msg)
if s.sendCallback != nil {
s.sendCallback(toAddress, string(msg))
diff --git a/internal/federation/authenticate.go b/internal/federation/authenticate.go
index 157a1830b..a966bb26a 100644
--- a/internal/federation/authenticate.go
+++ b/internal/federation/authenticate.go
@@ -124,7 +124,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
if vi == nil {
err := errors.New("http request wasn't signed or http signature was invalid")
errWithCode := gtserror.NewErrorUnauthorized(err, err.Error())
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -132,7 +132,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
if !ok {
err := errors.New("http request wasn't signed or http signature was invalid")
errWithCode := gtserror.NewErrorUnauthorized(err, err.Error())
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -141,7 +141,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
if si == nil {
err := errors.New("http request wasn't signed or http signature was invalid")
errWithCode := gtserror.NewErrorUnauthorized(err, err.Error())
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -149,7 +149,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
if !ok {
err := errors.New("http request wasn't signed or http signature was invalid")
errWithCode := gtserror.NewErrorUnauthorized(err, err.Error())
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -157,7 +157,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
requestingPublicKeyID, err := url.Parse(verifier.KeyId())
if err != nil {
errWithCode := gtserror.NewErrorBadRequest(err, fmt.Sprintf("couldn't parse public key URL %s", verifier.KeyId()))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -170,12 +170,12 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
if host := config.GetHost(); strings.EqualFold(requestingHost, host) {
// LOCAL ACCOUNT REQUEST
// the request is coming from INSIDE THE HOUSE so skip the remote dereferencing
- log.Tracef("proceeding without dereference for local public key %s", requestingPublicKeyID)
+ log.Tracef(ctx, "proceeding without dereference for local public key %s", requestingPublicKeyID)
requestingLocalAccount, err = f.db.GetAccountByPubkeyID(ctx, requestingPublicKeyID.String())
if err != nil {
errWithCode := gtserror.NewErrorInternalError(fmt.Errorf("couldn't get account with public key uri %s from the database: %s", requestingPublicKeyID.String(), err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -184,18 +184,18 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
pkOwnerURI, err = url.Parse(requestingLocalAccount.URI)
if err != nil {
errWithCode := gtserror.NewErrorBadRequest(err, fmt.Sprintf("couldn't parse public key owner URL %s", requestingLocalAccount.URI))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
} else if requestingRemoteAccount, err = f.db.GetAccountByPubkeyID(ctx, requestingPublicKeyID.String()); err == nil {
// REMOTE ACCOUNT REQUEST WITH KEY CACHED LOCALLY
// this is a remote account and we already have the public key for it so use that
- log.Tracef("proceeding without dereference for cached public key %s", requestingPublicKeyID)
+ log.Tracef(ctx, "proceeding without dereference for cached public key %s", requestingPublicKeyID)
publicKey = requestingRemoteAccount.PublicKey
pkOwnerURI, err = url.Parse(requestingRemoteAccount.URI)
if err != nil {
errWithCode := gtserror.NewErrorBadRequest(err, fmt.Sprintf("couldn't parse public key owner URL %s", requestingRemoteAccount.URI))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
} else {
@@ -205,21 +205,21 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
gone, err := f.CheckGone(ctx, requestingPublicKeyID)
if err != nil {
errWithCode := gtserror.NewErrorInternalError(fmt.Errorf("error checking for tombstone for %s: %s", requestingPublicKeyID, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
if gone {
errWithCode := gtserror.NewErrorGone(fmt.Errorf("account with public key %s is gone", requestingPublicKeyID))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
- log.Tracef("proceeding with dereference for uncached public key %s", requestingPublicKeyID)
+ log.Tracef(ctx, "proceeding with dereference for uncached public key %s", requestingPublicKeyID)
trans, err := f.transportController.NewTransportForUsername(transport.WithFastfail(ctx), requestedUsername)
if err != nil {
errWithCode := gtserror.NewErrorInternalError(fmt.Errorf("error creating transport for %s: %s", requestedUsername, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -231,16 +231,16 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
// we should add a tombstone to our database so that we can avoid trying to deref it in future
if err := f.HandleGone(ctx, requestingPublicKeyID); err != nil {
errWithCode := gtserror.NewErrorInternalError(fmt.Errorf("error marking account with public key %s as gone: %s", requestingPublicKeyID, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
errWithCode := gtserror.NewErrorGone(fmt.Errorf("account with public key %s is gone", requestingPublicKeyID))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
errWithCode := gtserror.NewErrorUnauthorized(fmt.Errorf("error dereferencing public key %s: %s", requestingPublicKeyID, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -248,7 +248,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
requestingPublicKey, err := getPublicKeyFromResponse(ctx, b, requestingPublicKeyID)
if err != nil {
errWithCode := gtserror.NewErrorUnauthorized(fmt.Errorf("error parsing public key %s: %s", requestingPublicKeyID, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -256,7 +256,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
pkPemProp := requestingPublicKey.GetW3IDSecurityV1PublicKeyPem()
if pkPemProp == nil || !pkPemProp.IsXMLSchemaString() {
errWithCode := gtserror.NewErrorUnauthorized(errors.New("publicKeyPem property is not provided or it is not embedded as a value"))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -265,14 +265,14 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
block, _ := pem.Decode([]byte(pubKeyPem))
if block == nil || block.Type != "PUBLIC KEY" {
errWithCode := gtserror.NewErrorUnauthorized(errors.New("could not decode publicKeyPem to PUBLIC KEY pem block type"))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
publicKey, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
errWithCode := gtserror.NewErrorUnauthorized(fmt.Errorf("could not parse public key %s from block bytes: %s", requestingPublicKeyID, err))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -280,7 +280,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
pkOwnerProp := requestingPublicKey.GetW3IDSecurityV1Owner()
if pkOwnerProp == nil || !pkOwnerProp.IsIRI() {
errWithCode := gtserror.NewErrorUnauthorized(errors.New("publicKeyOwner property is not provided or it is not embedded as a value"))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
pkOwnerURI = pkOwnerProp.GetIRI()
@@ -289,7 +289,7 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
// after all that, public key should be defined
if publicKey == nil {
errWithCode := gtserror.NewErrorInternalError(errors.New("returned public key was empty"))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
@@ -301,16 +301,16 @@ func (f *federator) AuthenticateFederatedRequest(ctx context.Context, requestedU
}
for _, algo := range algos {
- log.Tracef("trying algo: %s", algo)
+ log.Tracef(ctx, "trying algo: %s", algo)
err := verifier.Verify(publicKey, algo)
if err == nil {
- log.Tracef("authentication for %s PASSED with algorithm %s", pkOwnerURI, algo)
+ log.Tracef(ctx, "authentication for %s PASSED with algorithm %s", pkOwnerURI, algo)
return pkOwnerURI, nil
}
- log.Tracef("authentication for %s NOT PASSED with algorithm %s: %s", pkOwnerURI, algo, err)
+ log.Tracef(ctx, "authentication for %s NOT PASSED with algorithm %s: %s", pkOwnerURI, algo, err)
}
errWithCode := gtserror.NewErrorUnauthorized(fmt.Errorf("authentication not passed for public key owner %s; signature value was '%s'", pkOwnerURI, signature))
- log.Debug(errWithCode)
+ log.Debug(ctx, errWithCode)
return nil, errWithCode
}
diff --git a/internal/federation/dereferencing/account.go b/internal/federation/dereferencing/account.go
index ed514e493..93e0e3549 100644
--- a/internal/federation/dereferencing/account.go
+++ b/internal/federation/dereferencing/account.go
@@ -77,7 +77,7 @@ func (d *deref) GetAccountByURI(ctx context.Context, requestUser string, uri *ur
// Try to update existing account model
enriched, err := d.enrichAccount(ctx, requestUser, uri, account, false, block)
if err != nil {
- log.Errorf("error enriching remote account: %v", err)
+ log.Errorf(ctx, "error enriching remote account: %v", err)
return account, nil // fall back to returning existing
}
@@ -114,7 +114,7 @@ func (d *deref) GetAccountByUsernameDomain(ctx context.Context, requestUser stri
// Try to update existing account model
enriched, err := d.enrichAccount(ctx, requestUser, nil, account, false, block)
if err != nil {
- log.Errorf("GetAccountByUsernameDomain: error enriching account from remote: %v", err)
+ log.Errorf(ctx, "error enriching account from remote: %v", err)
return account, nil // fall back to returning unchanged existing account model
}
@@ -250,7 +250,7 @@ func (d *deref) enrichAccount(ctx context.Context, requestUser string, uri *url.
latestAcc.ID,
)
if err != nil {
- log.Errorf("error fetching remote avatar for account %s: %v", uri, err)
+ log.Errorf(ctx, "error fetching remote avatar for account %s: %v", uri, err)
// Keep old avatar for now, we'll try again in $interval.
latestAcc.AvatarMediaAttachmentID = account.AvatarMediaAttachmentID
@@ -271,7 +271,7 @@ func (d *deref) enrichAccount(ctx context.Context, requestUser string, uri *url.
latestAcc.ID,
)
if err != nil {
- log.Errorf("error fetching remote header for account %s: %v", uri, err)
+ log.Errorf(ctx, "error fetching remote header for account %s: %v", uri, err)
// Keep old header for now, we'll try again in $interval.
latestAcc.HeaderMediaAttachmentID = account.HeaderMediaAttachmentID
@@ -283,7 +283,7 @@ func (d *deref) enrichAccount(ctx context.Context, requestUser string, uri *url.
// Fetch the latest remote account emoji IDs used in account display name/bio.
_, err = d.fetchRemoteAccountEmojis(ctx, latestAcc, requestUser)
if err != nil {
- log.Errorf("error fetching remote emojis for account %s: %v", uri, err)
+ log.Errorf(ctx, "error fetching remote emojis for account %s: %v", uri, err)
}
if account.CreatedAt.IsZero() {
diff --git a/internal/federation/dereferencing/emoji.go b/internal/federation/dereferencing/emoji.go
index 7d8526c73..15d341383 100644
--- a/internal/federation/dereferencing/emoji.go
+++ b/internal/federation/dereferencing/emoji.go
@@ -111,7 +111,7 @@ func (d *deref) populateEmojis(ctx context.Context, rawEmojis []*gtsmodel.Emoji,
// have to get it from the database again
gotEmoji = e
} else if gotEmoji, err = d.db.GetEmojiByShortcodeDomain(ctx, e.Shortcode, e.Domain); err != nil && err != db.ErrNoEntries {
- log.Errorf("populateEmojis: error checking database for emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "error checking database for emoji %s: %s", shortcodeDomain, err)
continue
}
@@ -120,24 +120,24 @@ func (d *deref) populateEmojis(ctx context.Context, rawEmojis []*gtsmodel.Emoji,
if gotEmoji != nil {
// we had the emoji already, but refresh it if necessary
if e.UpdatedAt.Unix() > gotEmoji.ImageUpdatedAt.Unix() {
- log.Tracef("populateEmojis: emoji %s was updated since we last saw it, will refresh", shortcodeDomain)
+ log.Tracef(ctx, "emoji %s was updated since we last saw it, will refresh", shortcodeDomain)
refresh = true
}
if !refresh && (e.URI != gotEmoji.URI) {
- log.Tracef("populateEmojis: emoji %s changed URI since we last saw it, will refresh", shortcodeDomain)
+ log.Tracef(ctx, "emoji %s changed URI since we last saw it, will refresh", shortcodeDomain)
refresh = true
}
if !refresh && (e.ImageRemoteURL != gotEmoji.ImageRemoteURL) {
- log.Tracef("populateEmojis: emoji %s changed image URL since we last saw it, will refresh", shortcodeDomain)
+ log.Tracef(ctx, "emoji %s changed image URL since we last saw it, will refresh", shortcodeDomain)
refresh = true
}
if !refresh {
- log.Tracef("populateEmojis: emoji %s is up to date, will not refresh", shortcodeDomain)
+ log.Tracef(ctx, "emoji %s is up to date, will not refresh", shortcodeDomain)
} else {
- log.Tracef("populateEmojis: refreshing emoji %s", shortcodeDomain)
+ log.Tracef(ctx, "refreshing emoji %s", shortcodeDomain)
emojiID := gotEmoji.ID // use existing ID
processingEmoji, err := d.GetRemoteEmoji(ctx, requestingUsername, e.ImageRemoteURL, e.Shortcode, e.Domain, emojiID, e.URI, &media.AdditionalEmojiInfo{
Domain: &e.Domain,
@@ -147,12 +147,12 @@ func (d *deref) populateEmojis(ctx context.Context, rawEmojis []*gtsmodel.Emoji,
VisibleInPicker: gotEmoji.VisibleInPicker,
}, refresh)
if err != nil {
- log.Errorf("populateEmojis: couldn't refresh remote emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "couldn't refresh remote emoji %s: %s", shortcodeDomain, err)
continue
}
if gotEmoji, err = processingEmoji.LoadEmoji(ctx); err != nil {
- log.Errorf("populateEmojis: couldn't load refreshed remote emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "couldn't load refreshed remote emoji %s: %s", shortcodeDomain, err)
continue
}
}
@@ -160,7 +160,7 @@ func (d *deref) populateEmojis(ctx context.Context, rawEmojis []*gtsmodel.Emoji,
// it's new! go get it!
newEmojiID, err := id.NewRandomULID()
if err != nil {
- log.Errorf("populateEmojis: error generating id for remote emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "error generating id for remote emoji %s: %s", shortcodeDomain, err)
continue
}
@@ -172,12 +172,12 @@ func (d *deref) populateEmojis(ctx context.Context, rawEmojis []*gtsmodel.Emoji,
VisibleInPicker: e.VisibleInPicker,
}, refresh)
if err != nil {
- log.Errorf("populateEmojis: couldn't get remote emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "couldn't get remote emoji %s: %s", shortcodeDomain, err)
continue
}
if gotEmoji, err = processingEmoji.LoadEmoji(ctx); err != nil {
- log.Errorf("populateEmojis: couldn't load remote emoji %s: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "couldn't load remote emoji %s: %s", shortcodeDomain, err)
continue
}
}
diff --git a/internal/federation/dereferencing/status.go b/internal/federation/dereferencing/status.go
index da4639c5d..56545c5e0 100644
--- a/internal/federation/dereferencing/status.go
+++ b/internal/federation/dereferencing/status.go
@@ -318,20 +318,20 @@ func (d *deref) populateStatusMentions(ctx context.Context, status *gtsmodel.Sta
for _, m := range status.Mentions {
if m.ID != "" {
// we've already populated this mention, since it has an ID
- log.Debug("populateStatusMentions: mention already populated")
+ log.Debug(ctx, "mention already populated")
mentionIDs = append(mentionIDs, m.ID)
newMentions = append(newMentions, m)
continue
}
if m.TargetAccountURI == "" {
- log.Debug("populateStatusMentions: target URI not set on mention")
+ log.Debug(ctx, "target URI not set on mention")
continue
}
targetAccountURI, err := url.Parse(m.TargetAccountURI)
if err != nil {
- log.Debugf("populateStatusMentions: error parsing mentioned account uri %s: %s", m.TargetAccountURI, err)
+ log.Debugf(ctx, "error parsing mentioned account uri %s: %s", m.TargetAccountURI, err)
continue
}
@@ -342,7 +342,7 @@ func (d *deref) populateStatusMentions(ctx context.Context, status *gtsmodel.Sta
if a, err := d.db.GetAccountByURI(ctx, targetAccountURI.String()); err != nil {
errs = append(errs, err.Error())
} else {
- log.Debugf("populateStatusMentions: got target account %s with id %s through GetAccountByURI", targetAccountURI, a.ID)
+ log.Debugf(ctx, "got target account %s with id %s through GetAccountByURI", targetAccountURI, a.ID)
targetAccount = a
}
@@ -352,13 +352,13 @@ func (d *deref) populateStatusMentions(ctx context.Context, status *gtsmodel.Sta
if a, err := d.GetAccountByURI(ctx, requestingUsername, targetAccountURI, false); err != nil {
errs = append(errs, err.Error())
} else {
- log.Debugf("populateStatusMentions: got target account %s with id %s through GetRemoteAccount", targetAccountURI, a.ID)
+ log.Debugf(ctx, "got target account %s with id %s through GetRemoteAccount", targetAccountURI, a.ID)
targetAccount = a
}
}
if targetAccount == nil {
- log.Debugf("populateStatusMentions: couldn't get target account %s: %s", m.TargetAccountURI, strings.Join(errs, " : "))
+ log.Debugf(ctx, "couldn't get target account %s: %s", m.TargetAccountURI, strings.Join(errs, " : "))
continue
}
@@ -419,13 +419,13 @@ func (d *deref) populateStatusAttachments(ctx context.Context, status *gtsmodel.
Blurhash: &a.Blurhash,
})
if err != nil {
- log.Errorf("populateStatusAttachments: couldn't get remote media %s: %s", a.RemoteURL, err)
+ log.Errorf(ctx, "couldn't get remote media %s: %s", a.RemoteURL, err)
continue
}
attachment, err := processingMedia.LoadAttachment(ctx)
if err != nil {
- log.Errorf("populateStatusAttachments: couldn't load remote attachment %s: %s", a.RemoteURL, err)
+ log.Errorf(ctx, "couldn't load remote attachment %s: %s", a.RemoteURL, err)
continue
}
diff --git a/internal/federation/dereferencing/thread.go b/internal/federation/dereferencing/thread.go
index e89b2da7a..517d44e7a 100644
--- a/internal/federation/dereferencing/thread.go
+++ b/internal/federation/dereferencing/thread.go
@@ -45,10 +45,11 @@
//
// This does not return error, as for robustness we do not want to error-out on a status because another further up / down has issues.
func (d *deref) DereferenceThread(ctx context.Context, username string, statusIRI *url.URL, status *gtsmodel.Status, statusable ap.Statusable) {
- l := log.WithFields(kv.Fields{
- {"username", username},
- {"statusIRI", status.URI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"username", username},
+ {"statusIRI", status.URI},
+ }...)
// Log function start
l.Trace("beginning")
@@ -72,10 +73,11 @@ func (d *deref) dereferenceStatusAncestors(ctx context.Context, username string,
ogIRI := status.URI
// Start log entry with fields
- l := log.WithFields(kv.Fields{
- {"username", username},
- {"statusIRI", ogIRI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"username", username},
+ {"statusIRI", ogIRI},
+ }...)
// Log function start
l.Trace("beginning")
@@ -132,10 +134,11 @@ func (d *deref) dereferenceStatusDescendants(ctx context.Context, username strin
ogIRI := statusIRI
// Start log entry with fields
- l := log.WithFields(kv.Fields{
- {"username", username},
- {"statusIRI", ogIRI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"username", username},
+ {"statusIRI", ogIRI},
+ }...)
// Log function start
l.Trace("beginning")
diff --git a/internal/federation/federatingactor.go b/internal/federation/federatingactor.go
index 029149a9b..71e6e8fb6 100644
--- a/internal/federation/federatingactor.go
+++ b/internal/federation/federatingactor.go
@@ -56,7 +56,7 @@ func newFederatingActor(c pub.CommonBehavior, s2s pub.FederatingProtocol, db pub
// method will guaranteed work for non-custom Actors. For custom actors,
// care should be used to not call this method if only C2S is supported.
func (f *federatingActor) Send(c context.Context, outbox *url.URL, t vocab.Type) (pub.Activity, error) {
- log.Infof("federating actor: send activity %s via outbox %s", t.GetTypeName(), outbox)
+ log.Infof(c, "send activity %s via outbox %s", t.GetTypeName(), outbox)
return f.actor.Send(c, outbox, t)
}
diff --git a/internal/federation/federatingdb/create.go b/internal/federation/federatingdb/create.go
index 62784e68d..bf3e7f75d 100644
--- a/internal/federation/federatingdb/create.go
+++ b/internal/federation/federatingdb/create.go
@@ -53,8 +53,9 @@ func (f *federatingDB) Create(ctx context.Context, asType vocab.Type) error {
if err != nil {
return err
}
- l := log.WithField("create", i)
- l.Debug("entering Create")
+ l := log.WithContext(ctx).
+ WithField("create", i)
+ l.Trace("entering Create")
}
receivingAccount, requestingAccount := extractFromCtx(ctx)
@@ -164,10 +165,11 @@ func (f *federatingDB) activityCreate(ctx context.Context, asType vocab.Type, re
// createNote handles a Create activity with a Note type.
func (f *federatingDB) createNote(ctx context.Context, note vocab.ActivityStreamsNote, receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account) error {
- l := log.WithFields(kv.Fields{
- {"receivingAccount", receivingAccount.URI},
- {"requestingAccount", requestingAccount.URI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"receivingAccount", receivingAccount.URI},
+ {"requestingAccount", requestingAccount.URI},
+ }...)
// Check if we have a forward.
// In other words, was the note posted to our inbox by at least one actor who actually created the note, or are they just forwarding it?
diff --git a/internal/federation/federatingdb/delete.go b/internal/federation/federatingdb/delete.go
index 22434f63e..a1890b56b 100644
--- a/internal/federation/federatingdb/delete.go
+++ b/internal/federation/federatingdb/delete.go
@@ -35,9 +35,10 @@
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) Delete(ctx context.Context, id *url.URL) error {
- l := log.WithFields(kv.Fields{
- {"id", id},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"id", id},
+ }...)
l.Debug("entering Delete")
receivingAccount, requestingAccount := extractFromCtx(ctx)
diff --git a/internal/federation/federatingdb/exists.go b/internal/federation/federatingdb/exists.go
index 51e7399aa..a235770c6 100644
--- a/internal/federation/federatingdb/exists.go
+++ b/internal/federation/federatingdb/exists.go
@@ -32,10 +32,11 @@
// The library makes this call only after acquiring a lock first.
//
// Implementation note: this just straight up isn't implemented, and doesn't *really* need to be either.
-func (f *federatingDB) Exists(c context.Context, id *url.URL) (exists bool, err error) {
- l := log.WithFields(kv.Fields{
- {"id", id},
- }...)
+func (f *federatingDB) Exists(ctx context.Context, id *url.URL) (exists bool, err error) {
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"id", id},
+ }...)
l.Debug("entering Exists")
return false, nil
}
diff --git a/internal/federation/federatingdb/followers.go b/internal/federation/federatingdb/followers.go
index 9a80d5f0b..c47a2b625 100644
--- a/internal/federation/federatingdb/followers.go
+++ b/internal/federation/federatingdb/followers.go
@@ -18,9 +18,10 @@
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) Followers(ctx context.Context, actorIRI *url.URL) (followers vocab.ActivityStreamsCollection, err error) {
- l := log.WithFields(kv.Fields{
- {"id", actorIRI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"id", actorIRI},
+ }...)
l.Debug("entering Followers")
acct, err := f.getAccountForIRI(ctx, actorIRI)
diff --git a/internal/federation/federatingdb/following.go b/internal/federation/federatingdb/following.go
index 2290b72f4..f4f07bb25 100644
--- a/internal/federation/federatingdb/following.go
+++ b/internal/federation/federatingdb/following.go
@@ -36,9 +36,10 @@
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) Following(ctx context.Context, actorIRI *url.URL) (following vocab.ActivityStreamsCollection, err error) {
- l := log.WithFields(kv.Fields{
- {"id", actorIRI},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"id", actorIRI},
+ }...)
l.Debug("entering Following")
acct, err := f.getAccountForIRI(ctx, actorIRI)
diff --git a/internal/federation/federatingdb/get.go b/internal/federation/federatingdb/get.go
index a55cb0280..92a79d70f 100644
--- a/internal/federation/federatingdb/get.go
+++ b/internal/federation/federatingdb/get.go
@@ -33,7 +33,8 @@
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) Get(ctx context.Context, id *url.URL) (value vocab.Type, err error) {
- l := log.WithFields(kv.Fields{{"id", id}}...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{{"id", id}}...)
l.Debug("entering Get")
switch {
diff --git a/internal/federation/federatingdb/owns.go b/internal/federation/federatingdb/owns.go
index 070036df7..def0fa518 100644
--- a/internal/federation/federatingdb/owns.go
+++ b/internal/federation/federatingdb/owns.go
@@ -35,9 +35,10 @@
// the database has an entry for the IRI.
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) Owns(ctx context.Context, id *url.URL) (bool, error) {
- l := log.WithFields(kv.Fields{
- {"id", id},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"id", id},
+ }...)
l.Debug("entering Owns")
// if the id host isn't this instance host, we don't own this IRI
diff --git a/internal/federation/federatingdb/util.go b/internal/federation/federatingdb/util.go
index b5a9feab1..1eb27dc03 100644
--- a/internal/federation/federatingdb/util.go
+++ b/internal/federation/federatingdb/util.go
@@ -304,7 +304,7 @@ func extractFromCtx(ctx context.Context) (receivingAccount, requestingAccount *g
var ok bool
receivingAccount, ok = receivingAccountI.(*gtsmodel.Account)
if !ok {
- log.Panicf("extractFromCtx: context entry with key %s could not be asserted to *gtsmodel.Account", ap.ContextReceivingAccount)
+ log.Panicf(ctx, "context entry with key %s could not be asserted to *gtsmodel.Account", ap.ContextReceivingAccount)
}
}
@@ -313,7 +313,7 @@ func extractFromCtx(ctx context.Context) (receivingAccount, requestingAccount *g
var ok bool
requestingAccount, ok = requestingAcctI.(*gtsmodel.Account)
if !ok {
- log.Panicf("extractFromCtx: context entry with key %s could not be asserted to *gtsmodel.Account", ap.ContextRequestingAccount)
+ log.Panicf(ctx, "context entry with key %s could not be asserted to *gtsmodel.Account", ap.ContextRequestingAccount)
}
}
diff --git a/internal/federation/federatingprotocol.go b/internal/federation/federatingprotocol.go
index d75570dd6..e60f278c7 100644
--- a/internal/federation/federatingprotocol.go
+++ b/internal/federation/federatingprotocol.go
@@ -138,10 +138,11 @@ func (f *federator) PostInboxRequestBodyHook(ctx context.Context, r *http.Reques
// authenticated must be true and error nil. The request will continue
// to be processed.
func (f *federator) AuthenticatePostInbox(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, bool, error) {
- l := log.WithFields(kv.Fields{
- {"useragent", r.UserAgent()},
- {"url", r.URL.String()},
- }...)
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"useragent", r.UserAgent()},
+ {"url", r.URL.String()},
+ }...)
l.Trace("received request to authenticate")
if !uris.IsInboxPath(r.URL) {
@@ -242,7 +243,7 @@ func (f *federator) AuthenticatePostInbox(ctx context.Context, w http.ResponseWr
// blocked must be false and error nil. The request will continue
// to be processed.
func (f *federator) Blocked(ctx context.Context, actorIRIs []*url.URL) (bool, error) {
- log.Debugf("entering BLOCKED function with IRI list: %+v", actorIRIs)
+ log.Tracef(ctx, "entering BLOCKED function with IRI list: %+v", actorIRIs)
// check domain blocks first for the given actor IRIs
blocked, err := f.db.AreURIsBlocked(ctx, actorIRIs)
@@ -257,7 +258,7 @@ func (f *federator) Blocked(ctx context.Context, actorIRIs []*url.URL) (bool, er
otherInvolvedIRIsI := ctx.Value(ap.ContextOtherInvolvedIRIs)
otherInvolvedIRIs, ok := otherInvolvedIRIsI.([]*url.URL)
if !ok {
- log.Error("other involved IRIs not set on request context")
+ log.Error(ctx, "other involved IRIs not set on request context")
return false, errors.New("other involved IRIs not set on request context, so couldn't determine blocks")
}
blocked, err = f.db.AreURIsBlocked(ctx, otherInvolvedIRIs)
@@ -272,13 +273,13 @@ func (f *federator) Blocked(ctx context.Context, actorIRIs []*url.URL) (bool, er
receivingAccountI := ctx.Value(ap.ContextReceivingAccount)
receivingAccount, ok := receivingAccountI.(*gtsmodel.Account)
if !ok {
- log.Error("receiving account not set on request context")
+ log.Error(ctx, "receiving account not set on request context")
return false, errors.New("receiving account not set on request context, so couldn't determine blocks")
}
requestingAccountI := ctx.Value(ap.ContextRequestingAccount)
requestingAccount, ok := requestingAccountI.(*gtsmodel.Account)
if !ok {
- log.Error("requesting account not set on request context")
+ log.Error(ctx, "requesting account not set on request context")
return false, errors.New("requesting account not set on request context, so couldn't determine blocks")
}
// the receiver shouldn't block the sender
@@ -384,10 +385,11 @@ func(ctx context.Context, announce vocab.ActivityStreamsAnnounce) error {
// type and extension, so the unhandled ones are passed to
// DefaultCallback.
func (f *federator) DefaultCallback(ctx context.Context, activity pub.Activity) error {
- l := log.WithFields(kv.Fields{
- {"aptype", activity.GetTypeName()},
- }...)
- l.Debugf("received unhandle-able activity type so ignoring it")
+ l := log.WithContext(ctx).
+ WithFields(kv.Fields{
+ {"aptype", activity.GetTypeName()},
+ }...)
+ l.Debug("received unhandle-able activity type so ignoring it")
return nil
}
diff --git a/internal/httpclient/client.go b/internal/httpclient/client.go
index 6de975bbd..45f0c3447 100644
--- a/internal/httpclient/client.go
+++ b/internal/httpclient/client.go
@@ -180,12 +180,13 @@ func (c *Client) Do(req *http.Request) (*http.Response, error) {
if !ok {
// No spot acquired, log warning
- log.WithFields(kv.Fields{
- {K: "queue", V: len(wait)},
- {K: "method", V: req.Method},
- {K: "host", V: req.Host},
- {K: "uri", V: req.URL.RequestURI()},
- }...).Warn("full request queue")
+ log.WithContext(req.Context()).
+ WithFields(kv.Fields{
+ {K: "queue", V: len(wait)},
+ {K: "method", V: req.Method},
+ {K: "host", V: req.Host},
+ {K: "uri", V: req.URL.RequestURI()},
+ }...).Warn("full request queue")
select {
case <-req.Context().Done():
diff --git a/internal/log/entry.go b/internal/log/entry.go
index 0d4e16e2b..d782be9f7 100644
--- a/internal/log/entry.go
+++ b/internal/log/entry.go
@@ -19,6 +19,7 @@
package log
import (
+ "context"
"fmt"
"syscall"
@@ -27,91 +28,97 @@
)
type Entry struct {
- fields []kv.Field
+ ctx context.Context
+ kvs []kv.Field
}
-func (e Entry) WithField(key string, value interface{}) Entry {
- e.fields = append(e.fields, kv.Field{K: key, V: value})
+func (e Entry) WithContext(ctx context.Context) Entry {
+ e.ctx = ctx
return e
}
-func (e Entry) WithFields(fields ...kv.Field) Entry {
- e.fields = append(e.fields, fields...)
+func (e Entry) WithField(key string, value interface{}) Entry {
+ e.kvs = append(e.kvs, kv.Field{K: key, V: value})
+ return e
+}
+
+func (e Entry) WithFields(kvs ...kv.Field) Entry {
+ e.kvs = append(e.kvs, kvs...)
return e
}
func (e Entry) Trace(a ...interface{}) {
- logf(3, level.TRACE, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.TRACE, e.kvs, args(len(a)), a...)
}
func (e Entry) Tracef(s string, a ...interface{}) {
- logf(3, level.TRACE, e.fields, s, a...)
+ logf(e.ctx, 3, level.TRACE, e.kvs, s, a...)
}
func (e Entry) Debug(a ...interface{}) {
- logf(3, level.DEBUG, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.DEBUG, e.kvs, args(len(a)), a...)
}
func (e Entry) Debugf(s string, a ...interface{}) {
- logf(3, level.DEBUG, e.fields, s, a...)
+ logf(e.ctx, 3, level.DEBUG, e.kvs, s, a...)
}
func (e Entry) Info(a ...interface{}) {
- logf(3, level.INFO, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.INFO, e.kvs, args(len(a)), a...)
}
func (e Entry) Infof(s string, a ...interface{}) {
- logf(3, level.INFO, e.fields, s, a...)
+ logf(e.ctx, 3, level.INFO, e.kvs, s, a...)
}
func (e Entry) Warn(a ...interface{}) {
- logf(3, level.WARN, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.WARN, e.kvs, args(len(a)), a...)
}
func (e Entry) Warnf(s string, a ...interface{}) {
- logf(3, level.WARN, e.fields, s, a...)
+ logf(e.ctx, 3, level.WARN, e.kvs, s, a...)
}
func (e Entry) Error(a ...interface{}) {
- logf(3, level.ERROR, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.ERROR, e.kvs, args(len(a)), a...)
}
func (e Entry) Errorf(s string, a ...interface{}) {
- logf(3, level.ERROR, e.fields, s, a...)
+ logf(e.ctx, 3, level.ERROR, e.kvs, s, a...)
}
func (e Entry) Fatal(a ...interface{}) {
defer syscall.Exit(1)
- logf(3, level.FATAL, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.FATAL, e.kvs, args(len(a)), a...)
}
func (e Entry) Fatalf(s string, a ...interface{}) {
defer syscall.Exit(1)
- logf(3, level.FATAL, e.fields, s, a...)
+ logf(e.ctx, 3, level.FATAL, e.kvs, s, a...)
}
func (e Entry) Panic(a ...interface{}) {
defer panic(fmt.Sprint(a...))
- logf(3, level.PANIC, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, level.PANIC, e.kvs, args(len(a)), a...)
}
func (e Entry) Panicf(s string, a ...interface{}) {
defer panic(fmt.Sprintf(s, a...))
- logf(3, level.PANIC, e.fields, s, a...)
+ logf(e.ctx, 3, level.PANIC, e.kvs, s, a...)
}
func (e Entry) Log(lvl level.LEVEL, a ...interface{}) {
- logf(3, lvl, e.fields, args(len(a)), a...)
+ logf(e.ctx, 3, lvl, e.kvs, args(len(a)), a...)
}
func (e Entry) Logf(lvl level.LEVEL, s string, a ...interface{}) {
- logf(3, lvl, e.fields, s, a...)
+ logf(e.ctx, 3, lvl, e.kvs, s, a...)
}
func (e Entry) Print(a ...interface{}) {
- printf(3, e.fields, args(len(a)), a...)
+ printf(3, e.kvs, args(len(a)), a...)
}
func (e Entry) Printf(s string, a ...interface{}) {
- printf(3, e.fields, s, a...)
+ printf(3, e.kvs, s, a...)
}
diff --git a/internal/log/log.go b/internal/log/log.go
index 78fb143b6..9240d1e79 100644
--- a/internal/log/log.go
+++ b/internal/log/log.go
@@ -19,6 +19,7 @@
package log
import (
+ "context"
"fmt"
"log/syslog"
"os"
@@ -38,13 +39,21 @@
// lvlstrs is the lookup table of log levels to strings.
lvlstrs = level.Default()
- // Syslog output, only set if enabled.
+ // syslog output, only set if enabled.
sysout *syslog.Writer
// timefmt is the logging time format used.
timefmt = "02/01/2006 15:04:05.000"
+
+ // ctxhooks allows modifying log content based on context.
+ ctxhooks []func(context.Context, []kv.Field) []kv.Field
)
+// Hook adds the given hook to the global logger context hooks stack.
+func Hook(hook func(ctx context.Context, kvs []kv.Field) []kv.Field) {
+ ctxhooks = append(ctxhooks, hook)
+}
+
// Level returns the currently set log level.
func Level() level.LEVEL {
return level.LEVEL(loglvl.Load())
@@ -60,82 +69,86 @@ func New() Entry {
return Entry{}
}
+func WithContext(ctx context.Context) Entry {
+ return Entry{ctx: ctx}
+}
+
func WithField(key string, value interface{}) Entry {
- return Entry{fields: []kv.Field{{K: key, V: value}}}
+ return New().WithField(key, value)
}
func WithFields(fields ...kv.Field) Entry {
- return Entry{fields: fields}
+ return New().WithFields(fields...)
}
-func Trace(a ...interface{}) {
- logf(3, level.TRACE, nil, args(len(a)), a...)
+func Trace(ctx context.Context, a ...interface{}) {
+ logf(ctx, 3, level.TRACE, nil, args(len(a)), a...)
}
-func Tracef(s string, a ...interface{}) {
- logf(3, level.TRACE, nil, s, a...)
+func Tracef(ctx context.Context, s string, a ...interface{}) {
+ logf(ctx, 3, level.TRACE, nil, s, a...)
}
-func Debug(a ...interface{}) {
- logf(3, level.DEBUG, nil, args(len(a)), a...)
+func Debug(ctx context.Context, a ...interface{}) {
+ logf(ctx, 3, level.DEBUG, nil, args(len(a)), a...)
}
-func Debugf(s string, a ...interface{}) {
- logf(3, level.DEBUG, nil, s, a...)
+func Debugf(ctx context.Context, s string, a ...interface{}) {
+ logf(ctx, 3, level.DEBUG, nil, s, a...)
}
-func Info(a ...interface{}) {
- logf(3, level.INFO, nil, args(len(a)), a...)
+func Info(ctx context.Context, a ...interface{}) {
+ logf(ctx, 3, level.INFO, nil, args(len(a)), a...)
}
-func Infof(s string, a ...interface{}) {
- logf(3, level.INFO, nil, s, a...)
+func Infof(ctx context.Context, s string, a ...interface{}) {
+ logf(ctx, 3, level.INFO, nil, s, a...)
}
-func Warn(a ...interface{}) {
- logf(3, level.WARN, nil, args(len(a)), a...)
+func Warn(ctx context.Context, a ...interface{}) {
+ logf(ctx, 3, level.WARN, nil, args(len(a)), a...)
}
-func Warnf(s string, a ...interface{}) {
- logf(3, level.WARN, nil, s, a...)
+func Warnf(ctx context.Context, s string, a ...interface{}) {
+ logf(ctx, 3, level.WARN, nil, s, a...)
}
-func Error(a ...interface{}) {
- logf(3, level.ERROR, nil, args(len(a)), a...)
+func Error(ctx context.Context, a ...interface{}) {
+ logf(ctx, 3, level.ERROR, nil, args(len(a)), a...)
}
-func Errorf(s string, a ...interface{}) {
- logf(3, level.ERROR, nil, s, a...)
+func Errorf(ctx context.Context, s string, a ...interface{}) {
+ logf(ctx, 3, level.ERROR, nil, s, a...)
}
-func Fatal(a ...interface{}) {
+func Fatal(ctx context.Context, a ...interface{}) {
defer syscall.Exit(1)
- logf(3, level.FATAL, nil, args(len(a)), a...)
+ logf(ctx, 3, level.FATAL, nil, args(len(a)), a...)
}
-func Fatalf(s string, a ...interface{}) {
+func Fatalf(ctx context.Context, s string, a ...interface{}) {
defer syscall.Exit(1)
- logf(3, level.FATAL, nil, s, a...)
+ logf(ctx, 3, level.FATAL, nil, s, a...)
}
-func Panic(a ...interface{}) {
+func Panic(ctx context.Context, a ...interface{}) {
defer panic(fmt.Sprint(a...))
- logf(3, level.PANIC, nil, args(len(a)), a...)
+ logf(ctx, 3, level.PANIC, nil, args(len(a)), a...)
}
-func Panicf(s string, a ...interface{}) {
+func Panicf(ctx context.Context, s string, a ...interface{}) {
defer panic(fmt.Sprintf(s, a...))
- logf(3, level.PANIC, nil, s, a...)
+ logf(ctx, 3, level.PANIC, nil, s, a...)
}
// Log will log formatted args as 'msg' field to the log at given level.
-func Log(lvl level.LEVEL, a ...interface{}) {
- logf(3, lvl, nil, args(len(a)), a...)
+func Log(ctx context.Context, lvl level.LEVEL, a ...interface{}) {
+ logf(ctx, 3, lvl, nil, args(len(a)), a...)
}
// Logf will log format string as 'msg' field to the log at given level.
-func Logf(lvl level.LEVEL, s string, a ...interface{}) {
- logf(3, lvl, nil, s, a...)
+func Logf(ctx context.Context, lvl level.LEVEL, s string, a ...interface{}) {
+ logf(ctx, 3, lvl, nil, s, a...)
}
// Print will log formatted args to the stdout log output.
@@ -186,7 +199,7 @@ func printf(depth int, fields []kv.Field, s string, a ...interface{}) {
putBuf(buf)
}
-func logf(depth int, lvl level.LEVEL, fields []kv.Field, s string, a ...interface{}) {
+func logf(ctx context.Context, depth int, lvl level.LEVEL, fields []kv.Field, s string, a ...interface{}) {
var out *os.File
// Check if enabled.
@@ -220,6 +233,13 @@ func logf(depth int, lvl level.LEVEL, fields []kv.Field, s string, a ...interfac
buf.B = append(buf.B, lvlstrs[lvl]...)
buf.B = append(buf.B, ' ')
+ if ctx != nil {
+ // Pass context through hooks.
+ for _, hook := range ctxhooks {
+ fields = hook(ctx, fields)
+ }
+ }
+
// Append formatted fields with msg
kv.Fields(append(fields, kv.Field{
K: "msg", V: fmt.Sprintf(s, a...),
diff --git a/internal/log/syslog_test.go b/internal/log/syslog_test.go
index baa4dac6c..0fb46923c 100644
--- a/internal/log/syslog_test.go
+++ b/internal/log/syslog_test.go
@@ -66,14 +66,14 @@ func (suite *SyslogTestSuite) TearDownTest() {
}
func (suite *SyslogTestSuite) TestSyslog() {
- log.Info("this is a test of the emergency broadcast system!")
+ log.Info(nil, "this is a test of the emergency broadcast system!")
entry := <-suite.syslogChannel
suite.Regexp(regexp.MustCompile(`timestamp=.* func=.* level=INFO msg="this is a test of the emergency broadcast system!"`), entry["content"])
}
func (suite *SyslogTestSuite) TestSyslogLongMessage() {
- log.Warn(longMessage)
+ log.Warn(nil, longMessage)
funcName := log.Caller(2)
prefix := fmt.Sprintf(`timestamp="02/01/2006 15:04:05.000" func=%s level=WARN msg="`, funcName)
@@ -104,7 +104,7 @@ func (suite *SyslogTestSuite) TestSyslogLongMessageUnixgram() {
testrig.InitTestLog()
- log.Warn(longMessage)
+ log.Warn(nil, longMessage)
funcName := log.Caller(2)
prefix := fmt.Sprintf(`timestamp="02/01/2006 15:04:05.000" func=%s level=WARN msg="`, funcName)
diff --git a/internal/media/manager.go b/internal/media/manager.go
index ba89aff13..36282cc45 100644
--- a/internal/media/manager.go
+++ b/internal/media/manager.go
@@ -454,8 +454,8 @@ func scheduleCleanupJobs(m *manager) {
m.state.Workers.Scheduler.Schedule(sched.NewJob(func(now time.Time) {
err := m.PruneAll(doneCtx, config.GetMediaRemoteCacheDays(), true)
if err != nil {
- log.Errorf("error during prune: %v", err)
+ log.Errorf(nil, "error during prune: %v", err)
}
- log.Infof("finished pruning all in %s", time.Since(now))
+ log.Infof(nil, "finished pruning all in %s", time.Since(now))
}).EveryAt(midnight, day))
}
diff --git a/internal/media/processingemoji.go b/internal/media/processingemoji.go
index 0a36174b0..0c3e83e6b 100644
--- a/internal/media/processingemoji.go
+++ b/internal/media/processingemoji.go
@@ -67,7 +67,7 @@ func (p *ProcessingEmoji) LoadEmoji(ctx context.Context) (*gtsmodel.Emoji, error
if !done {
// Provided context was cancelled, e.g. request cancelled
// early. Queue this item for asynchronous processing.
- log.Warnf("reprocessing emoji %s after canceled ctx", p.emoji.ID)
+ log.Warnf(ctx, "reprocessing emoji %s after canceled ctx", p.emoji.ID)
go p.mgr.state.Workers.Media.Enqueue(p.Process)
}
@@ -77,7 +77,7 @@ func (p *ProcessingEmoji) LoadEmoji(ctx context.Context) (*gtsmodel.Emoji, error
// Process allows the receiving object to fit the runners.WorkerFunc signature. It performs a (blocking) load and logs on error.
func (p *ProcessingEmoji) Process(ctx context.Context) {
if _, _, err := p.load(ctx); err != nil {
- log.Errorf("error processing emoji: %v", err)
+ log.Errorf(ctx, "error processing emoji: %v", err)
}
}
@@ -167,7 +167,7 @@ func (p *ProcessingEmoji) store(ctx context.Context) error {
// Ensure post callback gets called.
if err := p.postFn(ctx); err != nil {
- log.Errorf("error executing postdata function: %v", err)
+ log.Errorf(ctx, "error executing postdata function: %v", err)
}
}()
@@ -180,7 +180,7 @@ func (p *ProcessingEmoji) store(ctx context.Context) error {
defer func() {
// Ensure data reader gets closed on return.
if err := rc.Close(); err != nil {
- log.Errorf("error closing data reader: %v", err)
+ log.Errorf(ctx, "error closing data reader: %v", err)
}
}()
@@ -251,7 +251,7 @@ func (p *ProcessingEmoji) store(ctx context.Context) error {
// This shouldn't already exist, but we do a check as it's worth logging.
if have, _ := p.mgr.state.Storage.Has(ctx, p.emoji.ImagePath); have {
- log.Warnf("emoji already exists at storage path: %s", p.emoji.ImagePath)
+ log.Warnf(ctx, "emoji already exists at storage path: %s", p.emoji.ImagePath)
// Attempt to remove existing emoji at storage path (might be broken / out-of-date)
if err := p.mgr.state.Storage.Delete(ctx, p.emoji.ImagePath); err != nil {
@@ -267,8 +267,9 @@ func (p *ProcessingEmoji) store(ctx context.Context) error {
// Once again check size in case none was provided previously.
if size := bytesize.Size(sz); size > maxSize {
+
if err := p.mgr.state.Storage.Delete(ctx, p.emoji.ImagePath); err != nil {
- log.Errorf("error removing too-large-emoji from storage: %v", err)
+ log.Errorf(ctx, "error removing too-large-emoji from storage: %v", err)
}
return fmt.Errorf("calculated emoji size %s greater than max allowed %s", size, maxSize)
}
@@ -308,8 +309,7 @@ func (p *ProcessingEmoji) finish(ctx context.Context) error {
// This shouldn't already exist, but we do a check as it's worth logging.
if have, _ := p.mgr.state.Storage.Has(ctx, p.emoji.ImageStaticPath); have {
- log.Warnf("static emoji already exists at storage path: %s", p.emoji.ImagePath)
-
+ log.Warnf(ctx, "static emoji already exists at storage path: %s", p.emoji.ImagePath)
// Attempt to remove static existing emoji at storage path (might be broken / out-of-date)
if err := p.mgr.state.Storage.Delete(ctx, p.emoji.ImageStaticPath); err != nil {
return fmt.Errorf("error removing static emoji from storage: %v", err)
diff --git a/internal/media/processingmedia.go b/internal/media/processingmedia.go
index b4eda4072..c00c203a6 100644
--- a/internal/media/processingmedia.go
+++ b/internal/media/processingmedia.go
@@ -67,7 +67,7 @@ func (p *ProcessingMedia) LoadAttachment(ctx context.Context) (*gtsmodel.MediaAt
if !done {
// Provided context was cancelled, e.g. request cancelled
// early. Queue this item for asynchronous processing.
- log.Warnf("reprocessing media %s after canceled ctx", p.media.ID)
+ log.Warnf(ctx, "reprocessing media %s after canceled ctx", p.media.ID)
go p.mgr.state.Workers.Media.Enqueue(p.Process)
}
@@ -77,7 +77,7 @@ func (p *ProcessingMedia) LoadAttachment(ctx context.Context) (*gtsmodel.MediaAt
// Process allows the receiving object to fit the runners.WorkerFunc signature. It performs a (blocking) load and logs on error.
func (p *ProcessingMedia) Process(ctx context.Context) {
if _, _, err := p.load(ctx); err != nil {
- log.Errorf("error processing media: %v", err)
+ log.Errorf(ctx, "error processing media: %v", err)
}
}
@@ -151,7 +151,7 @@ func (p *ProcessingMedia) store(ctx context.Context) error {
// ensure post callback gets called.
if err := p.postFn(ctx); err != nil {
- log.Errorf("error executing postdata function: %v", err)
+ log.Errorf(ctx, "error executing postdata function: %v", err)
}
}()
@@ -164,7 +164,7 @@ func (p *ProcessingMedia) store(ctx context.Context) error {
defer func() {
// Ensure data reader gets closed on return.
if err := rc.Close(); err != nil {
- log.Errorf("error closing data reader: %v", err)
+ log.Errorf(ctx, "error closing data reader: %v", err)
}
}()
@@ -220,7 +220,7 @@ func (p *ProcessingMedia) store(ctx context.Context) error {
// This shouldn't already exist, but we do a check as it's worth logging.
if have, _ := p.mgr.state.Storage.Has(ctx, p.media.File.Path); have {
- log.Warnf("media already exists at storage path: %s", p.media.File.Path)
+ log.Warnf(ctx, "media already exists at storage path: %s", p.media.File.Path)
// Attempt to remove existing media at storage path (might be broken / out-of-date)
if err := p.mgr.state.Storage.Delete(ctx, p.media.File.Path); err != nil {
@@ -333,7 +333,7 @@ func (p *ProcessingMedia) finish(ctx context.Context) error {
// This shouldn't already exist, but we do a check as it's worth logging.
if have, _ := p.mgr.state.Storage.Has(ctx, p.media.Thumbnail.Path); have {
- log.Warnf("thumbnail already exists at storage path: %s", p.media.Thumbnail.Path)
+ log.Warnf(ctx, "thumbnail already exists at storage path: %s", p.media.Thumbnail.Path)
// Attempt to remove existing thumbnail at storage path (might be broken / out-of-date)
if err := p.mgr.state.Storage.Delete(ctx, p.media.Thumbnail.Path); err != nil {
diff --git a/internal/media/prune.go b/internal/media/prune.go
index bb0993759..975a82e33 100644
--- a/internal/media/prune.go
+++ b/internal/media/prune.go
@@ -48,34 +48,34 @@ func (m *manager) PruneAll(ctx context.Context, mediaCacheRemoteDays int, blocki
if err != nil {
errs = append(errs, fmt.Sprintf("error pruning unused local media (%s)", err))
} else {
- log.Infof("pruned %d unused local media", pruned)
+ log.Infof(ctx, "pruned %d unused local media", pruned)
}
pruned, err = m.PruneUnusedRemote(innerCtx, dry)
if err != nil {
errs = append(errs, fmt.Sprintf("error pruning unused remote media: (%s)", err))
} else {
- log.Infof("pruned %d unused remote media", pruned)
+ log.Infof(ctx, "pruned %d unused remote media", pruned)
}
pruned, err = m.UncacheRemote(innerCtx, mediaCacheRemoteDays, dry)
if err != nil {
errs = append(errs, fmt.Sprintf("error uncacheing remote media older than %d day(s): (%s)", mediaCacheRemoteDays, err))
} else {
- log.Infof("uncached %d remote media older than %d day(s)", pruned, mediaCacheRemoteDays)
+ log.Infof(ctx, "uncached %d remote media older than %d day(s)", pruned, mediaCacheRemoteDays)
}
pruned, err = m.PruneOrphaned(innerCtx, dry)
if err != nil {
errs = append(errs, fmt.Sprintf("error pruning orphaned media: (%s)", err))
} else {
- log.Infof("pruned %d orphaned media", pruned)
+ log.Infof(ctx, "pruned %d orphaned media", pruned)
}
if err := m.state.Storage.Storage.Clean(innerCtx); err != nil {
errs = append(errs, fmt.Sprintf("error cleaning storage: (%s)", err))
} else {
- log.Info("cleaned storage")
+ log.Info(ctx, "cleaned storage")
}
return errs.Combine()
@@ -87,7 +87,7 @@ func (m *manager) PruneAll(ctx context.Context, mediaCacheRemoteDays int, blocki
go func() {
if err := f(context.Background()); err != nil {
- log.Error(err)
+ log.Error(ctx, err)
}
}()
diff --git a/internal/media/refetch.go b/internal/media/refetch.go
index 3d572e4b9..8c2a62c94 100644
--- a/internal/media/refetch.go
+++ b/internal/media/refetch.go
@@ -51,7 +51,7 @@ func (m *manager) RefetchEmojis(ctx context.Context, domain string, dereferenceM
if err != nil {
if !errors.Is(err, db.ErrNoEntries) {
// an actual error has occurred
- log.Errorf("error fetching emojis from database: %s", err)
+ log.Errorf(ctx, "error fetching emojis from database: %s", err)
}
break
}
@@ -79,10 +79,10 @@ func (m *manager) RefetchEmojis(ctx context.Context, domain string, dereferenceM
// bail early if we've got nothing to do
toRefetchCount := len(refetchIDs)
if toRefetchCount == 0 {
- log.Debug("no remote emojis require a refetch")
+ log.Debug(ctx, "no remote emojis require a refetch")
return 0, nil
}
- log.Debugf("%d remote emoji(s) require a refetch, doing that now...", toRefetchCount)
+ log.Debugf(ctx, "%d remote emoji(s) require a refetch, doing that now...", toRefetchCount)
var totalRefetched int
for _, emojiID := range refetchIDs {
@@ -94,13 +94,13 @@ func (m *manager) RefetchEmojis(ctx context.Context, domain string, dereferenceM
shortcodeDomain := util.ShortcodeDomain(emoji)
if emoji.ImageRemoteURL == "" {
- log.Errorf("remote emoji %s could not be refreshed because it has no ImageRemoteURL set", shortcodeDomain)
+ log.Errorf(ctx, "remote emoji %s could not be refreshed because it has no ImageRemoteURL set", shortcodeDomain)
continue
}
emojiImageIRI, err := url.Parse(emoji.ImageRemoteURL)
if err != nil {
- log.Errorf("remote emoji %s could not be refreshed because its ImageRemoteURL (%s) is not a valid uri: %s", shortcodeDomain, emoji.ImageRemoteURL, err)
+ log.Errorf(ctx, "remote emoji %s could not be refreshed because its ImageRemoteURL (%s) is not a valid uri: %s", shortcodeDomain, emoji.ImageRemoteURL, err)
continue
}
@@ -116,16 +116,16 @@ func (m *manager) RefetchEmojis(ctx context.Context, domain string, dereferenceM
VisibleInPicker: emoji.VisibleInPicker,
}, true)
if err != nil {
- log.Errorf("emoji %s could not be refreshed because of an error during processing: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "emoji %s could not be refreshed because of an error during processing: %s", shortcodeDomain, err)
continue
}
if _, err := processingEmoji.LoadEmoji(ctx); err != nil {
- log.Errorf("emoji %s could not be refreshed because of an error during loading: %s", shortcodeDomain, err)
+ log.Errorf(ctx, "emoji %s could not be refreshed because of an error during loading: %s", shortcodeDomain, err)
continue
}
- log.Tracef("refetched emoji %s successfully from remote", shortcodeDomain)
+ log.Tracef(ctx, "refetched emoji %s successfully from remote", shortcodeDomain)
totalRefetched++
}
diff --git a/internal/media/video.go b/internal/media/video.go
index 38b2dbdce..30e7e8864 100644
--- a/internal/media/video.go
+++ b/internal/media/video.go
@@ -44,7 +44,7 @@ func decodeVideoFrame(r io.Reader) (*gtsVideo, error) {
}
defer func() {
if err := tfs.Close(); err != nil {
- log.Errorf("error closing temp file seeker: %s", err)
+ log.Errorf(nil, "error closing temp file seeker: %s", err)
}
}()
diff --git a/internal/middleware/requestid.go b/internal/middleware/requestid.go
new file mode 100644
index 000000000..56161355b
--- /dev/null
+++ b/internal/middleware/requestid.go
@@ -0,0 +1,111 @@
+/*
+ GoToSocial
+ Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see
If you believe this 404 was an error, you can contact
- the instance admin.
+ the instance admin. Provide them with the following request
+ Request ID: {{.requestID}}
.
{{.error}}+ Request ID
{{.requestID}}