A Logging Decorator for Go Notifiers: One Wrapper, Any Sender
Go: Adding Logs to Notification Sends with Decorators
When I was learning the decorator pattern, I used a very specific requirement: the email sender was already written, and now we want to log before and after every send. Later, SMS and app push will need these two log lines too. How can we write it so that all three senders share this logic?
What · What is the decorator pattern?
Think of it as wrapping a gift. The gift is ready, and you can add a gift box and a blessing card as needed.
Put it in code: the email sender is the wrapped object, and the logging decorator is the outer layer. The caller still calls Send, but this time it enters the decorator first. The decorator prints the start log, lets the inner email sender work, and then prints the end log.
Caller calls Send("Order shipped")
↓
Log decorator prints "start sending"
↓
Email sender executes Send, returns result
↓
Log decorator prints "send finished", hands result back to caller
Why · Why wrap with another layer?
If only email needed logging, you could just put the two log lines directly in the email sender. But when SMS and push also need the same logs, writing them in each sender means maintaining three copies. For example, if the log format changes, all three places need to be changed.
The decorator centralizes this logic. It saves the inner object as a Notifier interface; as long as that object has a Send method that matches the convention, it can be wrapped. So the same logging decorator can wrap both the email sender and the SMS sender.
How · Implement a logging decorator in Go
This example uses returned text to simulate sending email. Create a main.go and write the following code.
package main
import (
"fmt"
"io"
"os"
)
// Both the email sender and the logging decorator implement this interface.
type Notifier interface {
Send(message string) string
}
type EmailNotifier struct{}
func (EmailNotifier) Send(message string) string {
return "Email notification: " + message
}
type LoggingNotifier struct {
next Notifier // wrapped sender
log io.Writer // where logs go
}
func (logger LoggingNotifier) Send(message string) string {
fmt.Fprintln(logger.log, "[log] start sending")
result := logger.next.Send(message)
fmt.Fprintln(logger.log, "[log] send finished")
return result
}
func main() {
email := EmailNotifier{}
var sender Notifier = LoggingNotifier{
next: email,
log: os.Stdout, // print logs to the terminal
}
fmt.Println(sender.Send("Order shipped"))
}
When I read this code, I start from next: email. It puts the email sender into the decorator's next field. When execution reaches logger.next.Send(message), logger represents the decorator currently in use, and logger.next is the email sender we just put in. It is this line that explicitly calls the inner Send and delegates the work to it.
Both EmailNotifier and LoggingNotifier have the Send(message string) string method, so they can both be assigned to a Notifier variable. Whether to add logging is decided when assembling the sender; the later call to sender.Send(...) is the same.
Run it in Cursor
- Create a practice folder, e.g.,
decorator-demo, open it in Cursor. - Create
main.goin the left file list, enter the code, save with⌘S. - Open Cursor's integrated terminal, confirm the current directory is
decorator-demo, and rungo run main.go.
The output is:
[log] start sending
[log] send finished
Email notification: Order shipped
The email result appears last because main waits until the entire sender.Send(...) returns before running the outer fmt.Println.
Write a test to observe two results
Create main_test.go in the same directory. When running the program, logs go to the terminal. In the test, write logs to a bytes.Buffer so you can inspect the log content.
package main
import (
"bytes"
"testing"
)
func TestLoggingNotifier(t *testing.T) {
var logs bytes.Buffer
email := EmailNotifier{}
sender := LoggingNotifier{next: email, log: &logs}
got := sender.Send("Order shipped")
if got != "Email notification: Order shipped" {
t.Errorf("incorrect send result: %q", got)
}
wantLogs := "[log] start sending\n[log] send finished\n"
if logs.String() != wantLogs {
t.Errorf("incorrect log content: %q", logs.String())
}
}
Run go test -v main.go main_test.go in the same terminal. Both the example and the test pass.
Where · How to recognize it in real code?
Go's standard library io.TeeReader embodies this approach. It takes an io.Reader and returns an io.Reader. Whenever the caller reads data, it reads from the original reader and also writes the read data to a specified location. The caller still uses Read. Go standard library docs
Decorators can also be stacked. For example, wrap the email sender with logging, then wrap logging with timing; timing will include the logging time. If you reverse the order, the timing scope becomes smaller. The more layers, the more you need to be careful about the wrapping order when reading the code.
How is this different from the adapter pattern I learned before?
Both may store another object in a struct, so just looking at the fields can be confusing. Now I look at the call in the method body to distinguish.
| Pattern | External method | Internal method | Problem solved in this example |
|---|---|---|---|
| Adapter | Send(message) |
SendSMS(phone, message) |
Connect the new program's calling style to the old SMS service |
| Decorator | Send(message) |
Send(message) |
Add logging before and after the sending process |
Like this example in my learning, I want to add a log to make it clearer when troubleshooting later.
After learning this example, when I see logger.next.Send(message), I know why this line sits between the two log lines. When calling Send, the program first goes to the outer logging decorator, then enters the inner email sender. After the inner layer returns a result, the outer layer adds the end log and hands the result back to the caller.
If later I only want to add logging to SMS, I can assemble the sender only with a LoggingNotifier around SMS. When email also needs the same logging, I apply the same decorator to email. So which senders need logging can be decided per scenario.
In the future, when I encounter a similar need, I will first ask myself: Will this extra behavior be reused by multiple objects? Do I need to add it per scenario? If the answer is yes, I have a reason to write it as a decorator.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
Did you type this code out yourself in Cursor? Did you jump to see how each standard library function is implemented? While writing code, did you wonder why the receiver is a value instead of a pointer? In various programming languages, there are interface definitions - what problem does that solve? Why does Go only have structs but no classes, while other languages have classes? You should look into these with questions in mind. Although AI understands these things better than you, it is necessary for beginners to have some understanding of the above.