I am writing an application in which i need to record logs in two different files. For Example weblogs.go and debuglogs.go. I tried using the log4go but my requirement is i need the logger to be created in main file and be accessible in sub directory as major of decoding and logging is done in sub file. Can anybody please help with that?
1条回答 默认 最新
- duangou1953 2019-02-22 13:40关注
Here's one way to do it, using the standard
log
package:package main import ( "io" "log" "os" ) func main() { f1, err := os.Create("/tmp/file1") if err != nil { panic(err) } defer f1.Close() f2, err := os.Create("/tmp/file2") if err != nil { panic(err) } defer f2.Close() w := io.MultiWriter(os.Stdout, f1, f2) logger := log.New(w, "logger", log.LstdFlags) myfunc(logger) } func myfunc(logger *log.Logger) { logger.Print("Hello, log file!!") }
Notes:
-
io.MultiWriter
is used to combine several writers together. Here, it creates a writerw
- a write tow
will go toos.Stdout
as well as two files -
log.New
lets us create a newlog.Logger
object with a custom writer - The
log.Logger
object can be passed around to functions and used by them to log things
解决 无用评论 打赏 举报 -
悬赏问题
- ¥15 计组这些题应该咋做呀
- ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
- ¥15 让node服务器有自动加载文件的功能
- ¥15 jmeter脚本回放有的是对的有的是错的
- ¥15 r语言蛋白组学相关问题
- ¥15 Python时间序列如何拟合疏系数模型
- ¥15 求学软件的前人们指明方向🥺
- ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
- ¥20 双层网络上信息-疾病传播
- ¥50 paddlepaddle pinn