您可以使用lumberjack.v2,通过它您可以为每个用户定义一个自定义日志文件。
在下面的代码片段中,我使用一个简单的布尔值来确定日志内容是否应该添加到日志文件中,或者不是为每个用户添加。
package main
import (
"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)
}
这将创建一组新的滚动日志文件与记录每个用户在打开。
- “user_log_1.log” 为USER1
- “user_log_3.log” 为用户3
- 并为用户2