Ariel Shaqed (Scolnicov)
07/14/2025, 10:36 AMdefer
a call to an anonymous func that logs relevant parameters and return values.
• Because this is the first deferred func, it runs last -- if another deferred func also modified the return values, it still logs the right one.
In my case it was a ReadAt implementation, so I started off by saying:
func (f *myFile) ReadAt(buf []byte, off int64) (n int, err error) {
defer func() {
f.log().
WithFields(logging.Fields{
"off": off,
"n": n,
// BUG: do NOT log read values in released code
"out", string(buf[:n])).
WithError(err).
Trace("[DEBUG] done!")
}()
(Of course, this func logs data read so we marked a bug. But without out
, we could keep it if needed).Yoni Peleg
07/14/2025, 1:46 PMdefer
can change these variables (source and source). But defer
can observe local variables just fine: see playground.Ariel Shaqed (Scolnicov)
07/14/2025, 1:47 PMYoni Peleg
07/14/2025, 1:48 PMfunc (f *myFile) ReadAt(buf []byte, off int64) (int, error) {
var err error
var n int
defer func() { /* log n and err */ }()
// rest of the code
}
Yoni Peleg
07/14/2025, 1:55 PM