kataras/iris · error
accesslog: SetFormatter called with nil Writer
Error message
accesslog: SetFormatter called with nil Writer
What it means
AccessLog.SetFormatter panics immediately if the AccessLog's Writer field is nil (middleware/accesslog/accesslog.go:672), because a formatter has nowhere to write output. The check runs before the formatter is even inspected.
Source
Thrown at middleware/accesslog/accesslog.go:672
err = fmt.Errorf("%v, %v", err, tErr)
}
}
}
ac.mu.Unlock()
return err
}
// SetFormatter sets a custom formatter to print the logs.
// Any custom output writers should be
// already registered before calling this method.
// Returns this AccessLog instance.
//
// Usage:
// ac.SetFormatter(&accesslog.JSON{Indent: " "})
func (ac *AccessLog) SetFormatter(f Formatter) *AccessLog {
if ac.Writer == nil {
panic("accesslog: SetFormatter called with nil Writer")
}
if f == nil {
return ac
}
if flusher, ok := ac.formatter.(Flusher); ok {
// PREPEND formatter flushes, they should run before destination's ones.
ac.Flushers = append([]Flusher{flusher}, ac.Flushers...)
}
// Inject the writer (AccessLog) here, the writer
// is protected with mutex.
f.SetOutput(ac)
ac.formatter = f
return ac
}View on GitHub (pinned to 7bedaf55a0)
Solutions
- Initialize the AccessLog with accesslog.New(io.Writer) so Writer is always set.
- Set ac.Writer to a valid io.Writer (e.g. an *os.File) before calling SetFormatter.
- Reorder code so SetFormatter is called after Writer assignment when building AccessLog manually.
Example fix
// before
ac := &accesslog.AccessLog{}
ac.SetFormatter(&accesslog.JSON{}) // panics: nil Writer
// after
f := accesslog.File("./access.log")
ac := accesslog.New(f)
ac.SetFormatter(&accesslog.JSON{}) Defensive patterns
Strategy: validation
Validate before calling
// Guard before calling SetFormatter
if ac.Writer == nil {
return errors.New("accesslog writer not initialized")
}
ac.SetFormatter(&accesslog.JSON{}) Type guard
func writerSet(ac *accesslog.AccessLog) bool {
return ac != nil && ac.Writer != nil
} Try / catch
defer func() {
if r := recover(); r != nil {
log.Fatalf("SetFormatter: %v", r)
}
}() Prevention
- Always build AccessLog via accesslog.New(writer), never as a bare struct literal.
- Set Writer before any formatter configuration in initialization code.
- Add an init-time assertion that ac.Writer != nil.
When it happens
Trigger: Creating an AccessLog struct manually (not via accesslog.New, which requires a writer) with Writer left nil and then calling ac.SetFormatter(&accesslog.JSON{...}).
Common situations: Constructing &accesslog.AccessLog{} directly and setting fields piecemeal; assigning a nil writer variable by mistake; reordering initialization so SetFormatter runs before Writer is set.
Related errors
AI-assisted analysis of kataras/iris@7bedaf55a0 (2026-08-30).
Data as JSON: /api/errors/abc7917f6b8687d8.
Report an issue: GitHub.