如何移除Go Logger日志输出的前缀时间戳?
Got it, let's break down how to fix this. You're using Go's standard log package alongside lumberjack for log rotation, and you want to ditch that default timestamp prefix so only your actual log content shows up. Here's exactly what you need to do:
Step 1: Understand the Default Log Flags
The log package adds that timestamp prefix because its default flags include log.Ldate | log.Ltime. To remove all auto-generated prefixes (including the timestamp), we just need to reset these flags to 0.
Step 2: Combine with Lumberjack Rotation
You already know how to set up lumberjack for rotation, but we need to hook it up to the log package correctly while stripping the prefix. Here's a complete working example:
package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func initLogger() { // Configure your lumberjack rotation settings logRotator := &lumberjack.Logger{ Filename: "/var/log/myapp/app.log", // Update to your log path MaxSize: 20, // Rotate after 20MB MaxBackups: 10, // Keep up to 10 backup logs MaxAge: 90, // Retain logs for 90 days Compress: true, // Compress old logs to save space } // Set the log package to write to the lumberjack rotator log.SetOutput(logRotator) // Critical line: Disable all default prefixes (timestamp included) log.SetFlags(0) } func main() { initLogger() // This will log ONLY "Payment processed: order #1234" with no timestamp prefix log.Println("Payment processed: order #1234") }
Extra Notes
- If you ever want to add a custom prefix (like a service name) later (instead of the timestamp), you can use
log.SetPrefix("my-service: ")while keepinglog.SetFlags(0)—this way you get your custom prefix without the auto-generated timestamp. - Since you're getting timestamps from another source, just include that timestamp directly in your log message when you call
log.Println()orlog.Printf(), and it'll show up as part of the log content without any extra prefixes from thelogpackage.
This setup keeps all of lumberjack's rotation functionality intact while giving you clean, prefix-free logs exactly as your company's spec requires.
内容的提问来源于stack exchange,提问作者btald1331

