绝地无双
您可以使用lumberjack.v2,通过它您可以为每个用户定义一个自定义日志文件。在以下代码段中,我使用一个简单的布尔值来确定是否应将每个用户的日志内容添加到日志文件中。package mainimport ( "gopkg.in/natefinch/lumberjack.v2" "io/ioutil" "log" "strconv")type user struct { id int logger *log.Logger}func createUser(id int, logWanted bool) user { var l *log.Logger if logWanted { // Here the log content will be added in the user log file userFIle := &lumberjack.Logger{ Filename: "user_log_" + strconv.Itoa(id) + ".log", MaxSize: 250, // mb MaxBackups: 5, MaxAge: 10, // in days } l = log.New(userFIle, "User: ", log.Ldate|log.Ltime|log.Lshortfile) } else { // Here the log content will go nowhere l = log.New(ioutil.Discard, "User: ", log.Ldate|log.Ltime|log.Lshortfile) } return user{id, l}}func doSomething(u user) { u.logger.Printf("Log content: user id %v \n", u.id)}func main() { user1 := createUser(1, true) user2 := createUser(2, false) user3 := createUser(3, true) doSomething(user1) doSomething(user2) doSomething(user3)}这将创建一个新的组滚动日志文件与原来的日志中的每个用户上。user1 的“user_log_1.log”user3 的“user_log_3.log”并且没有用户 2 的日志文件