Append Log Writes With O_APPEND Handles
Open log files with O_APPEND|O_CREATE so every write lands at the end without truncating, and see the O_TRUNC contrast for whole-file rewrites.
Code
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "append-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "events.log")
// O_APPEND|O_CREATE|O_WRONLY:句柄只追加,不截断已有内容
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
panic(err)
}
for i := 1; i <= 3; i++ {
// 每次写入都落到文件末尾,不覆盖之前的行
if _, err := fmt.Fprintf(f, "event %d\n", i); err != nil {
panic(err)
}
}
f.Close()
data, err := os.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Printf("content after 3 appends:\n%s", data)
}What the code does
Append Log Writes With O_APPEND Handles is built around the function main.
Iteration happens inside for i := 1; i <= 3; i++ — everything outside it runs once. Nothing continues past an unchecked error — 4 if err != nil branches, each ending in panic(err). A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
What to watch for
- Adapting this to library code usually means replacing the
panic(err)calls with error returns the caller can branch on.
Using it
Look for the content after 3 appends:\n prefixes when the file runs; they tie each line to its step.
Key statements
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How should callers handle failures?
- By terminating the run: `panic(err)` fires at each of the 4 checks, so callers see failures only as a stopped program.
- What does Append Log Writes With O_APPEND Handles print when run?
- Invoke the file as-is — the `content after 3 appends:\n` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.