Log Package With Prefix And Flags
log.New builds a logger with a prefix and flags; SetOutput swaps the sink to io.Discard to silence or a bytes.Buffer to capture in tests.
Code
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
"strings"
)
func main() {
// 自定义 logger:前缀 + flags 决定每行的形状
logger := log.New(os.Stdout, "[api] ", log.Ldate|log.Ltime|log.Lshortfile)
logger.Println("request routed")
// 静音:io.Discard 吞掉输出,调用点一行不改
logger.SetOutput(io.Discard)
logger.Println("never shown")
// 测试捕获:换上 bytes.Buffer 就能对日志做断言
var buf bytes.Buffer
logger.SetOutput(&buf)
logger.Println("captured by test")
fmt.Println("captured:", strings.TrimSpace(buf.String()))
// 全局标准 log:前缀与 UTC 时间戳
log.SetFlags(log.Ltime | log.LUTC)
log.SetPrefix("boot: ")
log.Println("starting")
}What the code does
The load-bearing part is the function main — everything else is wiring.
Watch out for
- There is nothing to declare: the runtime already provides every API this file touches.
Applying it
The definition reads func main()
The run emits 1 labeled section — captured: — one per step.
Statements that carry the logic
logger := log.New(os.Stdout, "[api] ", log.Ldate|log.Ltime|log.Lshortfile)
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Log Package With Prefix And Flags print when run?
- No setup needed: run the file and look for labeled lines like `captured:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.