You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除Go Logger日志输出的前缀时间戳?

Remove Default Timestamp Prefix from Go Logs with Lumberjack Rotation

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 keeping log.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() or log.Printf(), and it'll show up as part of the log content without any extra prefixes from the log package.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:22:56