From b21a6530857264088bd098be13e5ec2736f4f6c4 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Mon, 15 Sep 2014 13:53:59 -0500 Subject: [PATCH] Truncate logged strings and byte slices --- conn.go | 4 ++-- logger.go | 27 +++++++++++++++++++++++++++ query.go | 4 ++-- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/conn.go b/conn.go index abcdb443..ee225c91 100644 --- a/conn.go +++ b/conn.go @@ -569,9 +569,9 @@ func (c *Conn) Exec(sql string, arguments ...interface{}) (commandTag CommandTag defer func() { if err == nil { endTime := time.Now() - c.logger.Info("Exec", "sql", sql, "args", arguments, "time", endTime.Sub(startTime), "commandTag", commandTag) + c.logger.Info("Exec", "sql", sql, "args", logQueryArgs(arguments), "time", endTime.Sub(startTime), "commandTag", commandTag) } else { - c.logger.Error("Exec", "sql", sql, "args", arguments, "error", err) + c.logger.Error("Exec", "sql", sql, "args", logQueryArgs(arguments), "error", err) } }() diff --git a/logger.go b/logger.go index 6a5671f1..822b8c24 100644 --- a/logger.go +++ b/logger.go @@ -1,5 +1,10 @@ package pgx +import ( + "encoding/hex" + "fmt" +) + // Logger is the interface used to get logging from pgx internals. // https://github.com/inconshreveable/log15 is the recommended logging package. // This logging interface was extracted from there. However, it should be simple @@ -43,3 +48,25 @@ func (l *connLogger) Error(msg string, ctx ...interface{}) { ctx = append(ctx, "pid", l.pid) l.logger.Error(msg, ctx...) } + +func logQueryArgs(args ...interface{}) []interface{} { + logArgs := make([]interface{}, 0, len(args)) + + for _, a := range args { + switch v := a.(type) { + case []byte: + if len(v) < 64 { + a = hex.EncodeToString(v) + } else { + a = fmt.Sprintf("%x (truncated %d bytes)", v[:64], len(v)-64) + } + case string: + if len(v) > 64 { + a = fmt.Sprintf("%s (truncated %d bytes)", v[:64], len(v)-64) + } + } + logArgs = append(logArgs, a) + } + + return logArgs +} diff --git a/query.go b/query.go index 6e357178..1c2cc82b 100644 --- a/query.go +++ b/query.go @@ -70,9 +70,9 @@ func (rows *Rows) close() { if rows.err == nil { endTime := time.Now() - rows.logger.Info("Query", "sql", rows.sql, "args", rows.args, "time", endTime.Sub(rows.startTime), "rowCount", rows.rowCount) + rows.logger.Info("Query", "sql", rows.sql, "args", logQueryArgs(rows.args), "time", endTime.Sub(rows.startTime), "rowCount", rows.rowCount) } else { - rows.logger.Error("Query", "sql", rows.sql, "args", rows.args) + rows.logger.Error("Query", "sql", rows.sql, "args", logQueryArgs(rows.args)) } }