golang程序日志记录
packagemain import( "flag" "fmt" "log" "os" "runtime" ) var( logFileName=flag.String("log","cServer.log","Logfilename") ) funcmain(){ runtime.GOMAXPROCS(runtime.Numcpu()) flag.Parse() //setlogfileStdout logFile,logErr:=os.OpenFile(*logFileName,os.O_CREATE|os.O_RDWR|os.O_APPEND,0666) iflogErr!=nil{ fmt.Println("Failtofind",*logFile,"cServerstartFailed") os.Exit(1) } log.SetOutput(logFile) log.SetFlags(log.Ldate|log.Ltime|log.Lshortfile) //writelog log.Printf("Serverabort!Cause:%v\n","testlogfile") }
说明:
一、在主程序启动之前初始化log的格式后,以后用log.xxx 都将记录在初始的cServer.log文件中
2013/03/1910:44:26main.go:29:Serverabort!Cause:testlogfile 2013/03/1910:44:27main.go:29:Serverabort!Cause:testlogfile
三、可以通过log.SetFlags()自定议你想要表达的格式
四、设置输出目的地log.SetOutput()
五、os.OpenFile(*logFileName,0666)这是创建log文件.
5.1如果log文件不存在,创建一个新的文件os.O_CREATE
5.2打开文件的读写os.O_RDWR
原文链接:https://www.f2er.com/go/191056.html