Overview
MultiWriter writes to multiple io.Writer destinations simultaneously. This enables logging to both file and console at the same time, or any combination of outputs.
The writer continues operation even if individual writers fail, making it resilient to partial failures.
Type Definition
Constructor Functions
NewMultiWriter
Creates a new MultiWriter that writes to all provided writers.writers- Variable number of io.Writer instances
*MultiWriter- Configured multi-writer
- If no writers provided, behaves like io.Discard
- Writes to all writers in sequence
- Returns success if at least one writer succeeds
NewWriterWithErrorHandler
Creates a MultiWriter with custom error handling.errorHandler- Function called when a writer failswriters- Variable number of io.Writer instances
*MultiWriter- Configured multi-writer with error handler
Methods
Write
Writes data to all writers.p- Byte slice to write
n- Number of bytes written (maximum across successful writers)err- Error only if all writers failed, nil if at least one succeeded
- Writes to all writers in sequence
- Collects errors from individual writers
- Calls error handler for each error (if configured)
- Returns success if at least one writer succeeds
- Thread-safe (uses read lock)
AddWriter
Adds a new writer dynamically.w- Writer to add
RemoveWriter
Removes a writer from the multi-writer.w- Writer to remove (compared by pointer equality)
SetErrorHandler
Sets or updates the error handler.handler- Function to call when a writer fails
Writers
Returns a copy of the current writers slice.[]io.Writer- Copy of writers (safe to modify)
Close
Closes all writers that implement io.Closer.error- Last error encountered, or nil
- Calls Close on writers that implement io.Closer
- Continues closing all writers even if some fail
- Returns last error encountered
Sync
Syncs all writers that implement the Syncer interface.error- Last error encountered, or nil
- Calls Sync on writers that implement Syncer
- Continues syncing all writers even if some fail
- Returns last error encountered
Usage Examples
File + Console Logging
Different Formats for Different Outputs
Error Handling
Dynamic Writer Management
Separate Error and Info Logs
Testing with Buffer
Resilient Multi-Writer
Best Practices
Thread Safety
All methods are thread-safe:sync.RWMutex:
- Write operations use read lock (multiple concurrent writes)
- Add/Remove operations use write lock (exclusive access)
Performance
MultiWriter overhead is minimal:- Each write iterates through writers sequentially
- No allocations for the iteration
- Lock contention only during Add/Remove
Related
- RotatingFileWriter - File rotation writer
- SamplingWriter - Rate-limited writer
- Logger Options - WithOutput option