100行代码不到实现一个日志系统,支持多协程

我看你有戏 2016-10-10 04:06:23

package main
import (
"fmt"
"os"
"time"
"runtime"
)

/*
type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes for regular files; system-dependent for others
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // abbreviation for Mode().IsDir()
Sys() interface{} // underlying data source (can return nil)
}

const (
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
)
const (
SEEK_SET int = 0 // seek relative to the origin of the file
SEEK_CUR int = 1 // seek relative to the current offset
SEEK_END int = 2 // seek relative to the end
)
*/

type asyLogData struct {
LogData []byte
}

type GameLog struct{
sLogPath string
logName string
eventLogChanel chan *asyLogData
}
func (st *GameLog)WorkThread() {
for asydata := range st.eventLogChanel {
var sLogFilePath string
sLogFilePath = st.sLogPath+"/"+st.logName+"_"+time.Now().Format("2006-01-02")+".txt"
fmt.Println(sLogFilePath)
f, _ := os.OpenFile(sLogFilePath, os.O_RDWR|os.O_CREATE, 0777) //|os.O_TRUNC
f.Seek(0,os.SEEK_END)
f.Write([]byte(asydata.LogData))
f.Close()
}
}
func (st *GameLog)SetLog(pLogPath string,pLogName string) {
st.sLogPath = pLogPath
st.logName = pLogName

fmt.Println(st.sLogPath)
err:=os.MkdirAll(st.sLogPath,0777)
if err!=nil{
fmt.Println(err)
}

st.eventLogChanel= make(chan *asyLogData,4096)
go st.WorkThread()
}

func (st *GameLog)WriteGameLog(pLog string) {
_,gofile,line,_ := runtime.Caller(1)
var s string
s = fmt.Sprintf("%s\t[%d]%s\t%s\r\n",time.Now().Format("15:04:05"),line,gofile,pLog)


var pAsyData = new(asyLogData)
pAsyData.LogData = []byte(s)[0:]
st.eventLogChanel<- pAsyData

}

func main() {
fmt.Println(time.Now().Format("2006-01-02"))
var ab GameLog
file, _ := os.Getwd()
ab.SetLog(file+"/log/数据模块","测试日志")
ab.WriteGameLog("小测试,哈哈哈")

time.Sleep(time.Second*5)
}
...全文
249 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
我看你有戏 2016-10-13
  • 打赏
  • 举报
回复
竟然没人回复,晕

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧