nats-io/nats-server · error

can set log size limit only for file logger

Error message

can set log size limit only for file logger

What it means

Logger.SetSizeLimit applies a size cap to rotating file-backed loggers. The limit lives on the file logger (l.fl); if the Logger was not created/opened as a file logger (SetFileName/OpenFile never called), fl is nil and the method returns this error instead.

Source

Thrown at logger/log.go:302

func (l *fileLogger) close() error {
	l.Lock()
	if l.closed {
		l.Unlock()
		return nil
	}
	l.closed = true
	l.Unlock()
	return l.f.Close()
}

// SetSizeLimit sets the size of a logfile after which a backup
// is created with the file name + "year.month.day.hour.min.sec.nanosec"
// and the current log is truncated.
func (l *Logger) SetSizeLimit(limit int64) error {
	l.Lock()
	if l.fl == nil {
		l.Unlock()
		return fmt.Errorf("can set log size limit only for file logger")
	}
	fl := l.fl
	l.Unlock()
	fl.setLimit(limit)
	return nil
}

// SetMaxNumFiles sets the number of archived log files that will be retained
func (l *Logger) SetMaxNumFiles(max int) error {
	l.Lock()
	if l.fl == nil {
		l.Unlock()
		return fmt.Errorf("can set log max number of files only for file logger")
	}
	fl := l.fl
	l.Unlock()
	fl.setMaxNumFiles(max)
	return nil

View on GitHub (pinned to 3a66a489d2)

Solutions

  1. Call SetFileName/OpenFile (configure the file logger) before invoking SetSizeLimit
  2. Skip SetSizeLimit when file logging is disabled, or return silently in that branch
  3. Check that configuration actually enables file output before applying size limits

Example fix

// before
logger.SetSizeLimit(10 * 1024 * 1024) // fl == nil, errors
// after
if err := logger.SetFileName("/var/log/app.log"); err == nil {
    logger.SetSizeLimit(10 * 1024 * 1024)
}
Defensive patterns

Strategy: try-catch

Try / catch

if err := logger.SetSizeLimit(limit); err != nil {
    if strings.Contains(err.Error(), "only for file logger") {
        // console logger: size limit not applicable, skip
        return nil
    }
    return err
}

Prevention

When it happens

Trigger: Calling SetSizeLimit on a Logger instance used only for stderr/stdout (no file sink configured) — e.g. logger created with a default constructor without SetFileName before calling.

Common situations: Apps configuring rotation limits on a logger whose file target was set conditionally (e.g. file logging disabled in dev); ordering bugs where SetSizeLimit is called before the file logger is opened.

Related errors


AI-assisted analysis of nats-io/nats-server@3a66a489d2 (2026-09-02). Data as JSON: /api/errors/e32a614a7b706969. Report an issue: GitHub.