支援日誌切分的日誌記錄器(日期、大小、普通)-博文

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//@description日誌記錄工具類/*日誌格式:時間(系統時間)日誌類型(方法設定)日誌內容(動態輸入)日誌類包含兩個同步鎖:緩衝區鎖-mu_buf檔案鎖-mu_file日誌輸入操作PrintfPrintln1.擷取緩衝區鎖2.寫入緩衝區3.釋放緩衝區鎖4.A.調用bufWrite,B.等待定時調用bufWrite日誌輸出操作bufWrite1.擷取檔案鎖2.判斷緩衝區,不需寫入則返回3.擷取緩衝區鎖4.寫入緩衝區5.釋放緩衝區鎖日誌監聽操作fileMonitorA.檔案監聽定時器到期fileCheck1.判斷是否需要檔案重名,並後續操作1.1.擷取檔案鎖1.2.再次判斷檔案是否需要重名1.3.重新命名檔案1.4.釋放檔案鎖B.定時寫入定時器到期bufWrite檔案定時寫入bufWrite與檔案監聽fileMonitor時間間隔 t1,t2防止檔案碰撞(秒為單位時)需要滿足(n-1)t1%60 != (n-1)t2%60順序擷取鎖:緩衝鎖-->檔案鎖*///@author hanse//@data 2016-08-0413:39調試代碼無報錯//2017-04-0817:04修改bufWrite擷取鎖機制,寫入方式採用線程實現,增加必要的設計說明//2017-05-2421:11代碼結構調整,合并非不需方法,對檢測及寫入事件進行動態設定,並對定時器進行重設package loggorimport ("bytes""encoding/json""fmt""io""log""math""os""path""runtime/debug""sync""time")const (_VERSION_          = "1.0.1"               //版本DATEFORMAT         = "2006-01-02"          //日期格式(用於檔案命名)TIMEFORMAT         = "2006/01/02 15:04:05" //時間格式(日誌時間格式)_SPACE             = " "                   //參數分割_TABLE             = "\t"                  //記錄檔行分隔字元_JOIN              = "&"                   //參數串連符_FILE_OPERAT_MODE_ = 0644                  //檔案操作許可權模式_FILE_CREAT_MODE_  = 0666                  //檔案建立許可權模式_LABEL_            = "[_loggor_]"          //標籤)const (//記錄檔儲存模式LOG_FILE_SAVE_USUAL = 1 //普通模式,不分割LOG_FILE_SAVE_SIZE  = 2 //大小分割LOG_FILE_SAVE_DATE  = 3 //日期分割)const (//檔案大小單位_        = iotaKB int64 = 1 << (iota * 10)MBGBTB)const (_EXTEN_NAME_               = ".log"                  //記錄檔尾碼名_CHECK_TIME_ time.Duration = 900 * time.Millisecond  //定時檢測是否分割檢測周期_WRITE_TIME_ time.Duration = 1300 * time.Millisecond //定時寫入檔案周期)var (IS_DEBUG     = false //偵錯模式TIMEER_WRITE = false //定時寫入檔案)type LOGGER interface {SetDebug(bool)                                      //設定記錄檔路徑及名稱SetType(uint)                                       //設定日誌類型SetRollingFile(string, string, int32, int64, int64) //按照檔案大小分割SetRollingDaily(string, string)                     //按照日期分割SetRollingNormal(string, string)                    //設定普通模式Close()                                             //關閉Println(a ...interface{})                           //列印日誌Printf(format string, a ...interface{})             //格式化輸出}//==================================================================日誌記錄器type Logger struct {log_type     uint          //日誌類型path         string        //記錄檔路徑dir          string        //目錄filename     string        //檔案名稱maxFileSize  int64         //檔案大小maxFileCount int32         //檔案個數dailyRolling bool          //日分割sizeRolling  bool          //大小分割nomalRolling bool          //普通模式(不分割)_suffix      int           //大小分割檔案的當前序號_date        *time.Time    //檔案時間mu_buf       *sync.Mutex   //緩衝鎖mu_file      *sync.Mutex   //檔案鎖logfile      *os.File      //檔案控制代碼timer        *time.Timer   //監視定時器writeTimer   *time.Timer   //批量寫入定時器buf          *bytes.Buffer //緩衝區(公用buf保證資料寫入的順序性)}/**擷取日誌對象**/func New() *Logger {this := &Logger{}this.buf = &bytes.Buffer{}this.mu_buf = new(sync.Mutex)this.mu_file = new(sync.Mutex)return this}/**格式行輸出**/func (this *Logger) Printf(format string, a ...interface{}) {defer func() {if !TIMEER_WRITE {go this.bufWrite()}}()tp := fmt.Sprintf(format, a...)this.mu_buf.Lock()defer this.mu_buf.Unlock()this.buf.WriteString(fmt.Sprintf("%s\t%d\t%s\n",time.Now().Format(TIMEFORMAT),this.log_type,tp,),)}/**逐行輸出**/func (this *Logger) Println(a ...interface{}) {defer func() {if !TIMEER_WRITE {go this.bufWrite()}}()tp := fmt.Sprint(a...)this.mu_buf.Lock()defer this.mu_buf.Unlock()this.buf.WriteString(fmt.Sprintf("%s\t%d\t%s\n",time.Now().Format(TIMEFORMAT),this.log_type,tp,),)}/**測試模式**/func (this *Logger) SetDebug(is_debug bool) {IS_DEBUG = is_debug}/**定時寫入**/func (this *Logger) SetTimeWrite(time_write bool) *Logger {TIMEER_WRITE = time_writereturn this}/**日誌類型**/func (this *Logger) SetType(tp uint) {this.log_type = tp}/**大小分割**/func (this *Logger) SetRollingFile(dir, _file string, maxn int32, maxs int64, _u int64) {//0.輸入合法性if this.sizeRolling ||this.dailyRolling ||this.nomalRolling {log.Println(_LABEL_, "mode can't be changed!")return}//1.設定各模式標誌符this.sizeRolling = truethis.dailyRolling = falsethis.nomalRolling = false//2.設定日誌器各參數this.maxFileCount = maxnthis.maxFileSize = maxs * int64(_u)this.dir = dirthis.filename = _filefor i := 1; i <= int(maxn); i++ {sizeFile := fmt.Sprintf(dir,_file,_EXTEN_NAME_,".",fmt.Sprintf("%05d", i),)if isExist(sizeFile) {this._suffix = i} else {break}}//3.即時檔案寫入this.path = fmt.Sprint(dir,_file,_EXTEN_NAME_,)this.startLogger(this.path)}/**日期分割**/func (this *Logger) SetRollingDaily(dir, _file string) {//0.輸入合法性if this.sizeRolling ||this.dailyRolling ||this.nomalRolling {log.Println(_LABEL_, "mode can't be changed!")return}//1.設定各模式標誌符this.sizeRolling = falsethis.dailyRolling = truethis.nomalRolling = false//2.設定日誌器各參數this.dir = dirthis.filename = _filethis._date = getNowFormDate(DATEFORMAT)this.startLogger(fmt.Sprint(this.dir,this.filename,_EXTEN_NAME_,".",this._date.Format(DATEFORMAT),),)}/**普通模式**/func (this *Logger) SetRollingNormal(dir, _file string) {//0.輸入合法性if this.sizeRolling ||this.dailyRolling ||this.nomalRolling {log.Println(_LABEL_, "mode can't be changed!")return}//1.設定各模式標誌符this.sizeRolling = falsethis.dailyRolling = falsethis.nomalRolling = true//2.設定日誌器各參數this.dir = dirthis.filename = _filethis.startLogger(fmt.Sprint(dir,_file,_EXTEN_NAME_,),)}/**關閉日誌器**/func (this *Logger) Close() {//0.擷取鎖this.mu_buf.Lock()defer this.mu_buf.Unlock()this.mu_file.Lock()defer this.mu_file.Unlock()//1.關閉if nil != this.timer {this.timer.Stop()}if nil != this.writeTimer {this.writeTimer.Stop()}if this.logfile != nil {err := this.logfile.Close()if err != nil {log.Println(_LABEL_, "file close err", err)}} else {log.Println(_LABEL_, "file has been closed!")}//2.清理this.sizeRolling = falsethis.dailyRolling = falsethis.nomalRolling = false}//==================================================================內部工具方法//初始日誌記錄器(各日誌器統一調用)func (this *Logger) startLogger(tp string) {defer func() {if e, ok := recover().(error); ok {log.Println(_LABEL_, "WARN: panic - %v", e)log.Println(_LABEL_, string(debug.Stack()))}}()//1.初始化空間var err errorthis.buf = &bytes.Buffer{}this.mu_buf = new(sync.Mutex)this.mu_file = new(sync.Mutex)this.path = tpcheckFileDir(tp)this.logfile, err = os.OpenFile(tp,os.O_RDWR|os.O_APPEND|os.O_CREATE,_FILE_OPERAT_MODE_,)if nil != err {log.Println(_LABEL_, "OpenFile err!")}//2.開啟監控線程go func() {this.timer = time.NewTimer(_CHECK_TIME_)this.writeTimer = time.NewTimer(_WRITE_TIME_)if !TIMEER_WRITE {this.writeTimer.Stop()}for {select {//定時檢測是否分割case <-this.timer.C:this.fileCheck()if IS_DEBUG && false {log.Printf("*") //心跳}break//定時寫入檔案(定時寫入,會導致延時)case <-this.writeTimer.C:this.bufWrite()if IS_DEBUG && false {log.Printf(".") //心跳}break}}}()if IS_DEBUG {jstr, err := json.Marshal(this)if nil == err {log.Println(_LABEL_, _VERSION_, string(jstr))}}}//檔案檢測(會鎖定檔案)func (this *Logger) fileCheck() {//0.邊界判斷if nil == this.mu_file ||nil == this.logfile ||"" == this.path {return}defer func() {if e, ok := recover().(error); ok {log.Println(_LABEL_, "WARN: panic - %v", e)log.Println(_LABEL_, string(debug.Stack()))}}()//1.重新命名判斷var RENAME_FLAG bool = falsevar CHECK_TIME time.Duration = _CHECK_TIME_this.timer.Stop()defer this.timer.Reset(CHECK_TIME)if this.dailyRolling {//日分割模式now := getNowFormDate(DATEFORMAT)if nil != now &&nil != this._date &&now.After(*this._date) {//逾時重名RENAME_FLAG = true} else {//活動訊號間隔時間動態調整du := this._date.UnixNano() - now.UnixNano()abs := math.Abs(float64(du))CHECK_TIME = CHECK_TIME * time.Duration(abs/abs)}} else if this.sizeRolling {//檔案大小模式if "" != this.path &&this.maxFileCount >= 1 &&fileSize(this.path) >= this.maxFileSize {//超量重名RENAME_FLAG = true}} else if this.nomalRolling {//普通模式RENAME_FLAG = false}//2.重名操作if RENAME_FLAG {this.mu_file.Lock()defer this.mu_file.Unlock()if IS_DEBUG {log.Println(_LABEL_, this.path, "is need rename.")}this.fileRename()}return}//重新命名檔案func (this *Logger) fileRename() {//1.組建檔案名稱var err errorvar newName stringvar oldName stringdefer func() {if IS_DEBUG {log.Println(_LABEL_,oldName,"->",newName,":",err,)}}()if this.dailyRolling {//日期分割模式(檔案不重新命名)oldName = this.pathnewName = this.paththis._date = getNowFormDate(DATEFORMAT)this.path = fmt.Sprint(this.dir,this.filename,_EXTEN_NAME_,".",this._date.Format(DATEFORMAT),)} else if this.sizeRolling {//大小分割模式(1,2,3....)suffix := int(this._suffix%int(this.maxFileCount) + 1)oldName = this.pathnewName = fmt.Sprint(this.path,".",fmt.Sprintf("%05d", suffix),)this._suffix = suffixthis.path = this.path} else if this.nomalRolling {//常規模式}//2.處理舊檔案this.logfile.Close()if "" != oldName && "" != newName && oldName != newName {if isExist(newName) {//刪除舊檔案err := os.Remove(newName)if nil != err {log.Println(_LABEL_, "remove file err", err.Error())}}err = os.Rename(oldName, newName)if err != nil {//重名舊檔案log.Println(_LABEL_, "rename file err", err.Error())}}//3.建立新檔案this.logfile, err = os.OpenFile(this.path,os.O_RDWR|os.O_APPEND|os.O_CREATE,_FILE_OPERAT_MODE_,)if err != nil {log.Println(_LABEL_, "creat file err", err.Error())}return}//緩衝寫入檔案func (this *Logger) bufWrite() {//0.邊界處理if nil == this.buf ||"" == this.path ||nil == this.logfile ||nil == this.mu_buf ||nil == this.mu_file ||this.buf.Len() <= 0 {return}//1.資料寫入var WRITE_TIME time.Duration = _WRITE_TIME_if nil != this.writeTimer {this.writeTimer.Stop()defer this.writeTimer.Reset(WRITE_TIME)}this.mu_file.Lock()defer this.mu_file.Unlock()this.mu_buf.Lock()defer this.mu_buf.Unlock()defer this.buf.Reset()n, err := io.WriteString(this.logfile, this.buf.String())if nil != err {//寫入失敗,校正檔案,不存在則建立checkFileDir(this.path)this.logfile, err = os.OpenFile(this.path,os.O_RDWR|os.O_APPEND|os.O_CREATE,_FILE_OPERAT_MODE_,)if nil != err {log.Println(_LABEL_, "log bufWrite() err!")}}//根據緩衝壓力進行動態設定寫入間隔if n == 0 {WRITE_TIME = _WRITE_TIME_} else {WRITE_TIME = WRITE_TIME * time.Duration(n/n)}}//==================================================================輔助方法//擷取檔案大小func fileSize(file string) int64 {this, e := os.Stat(file)if e != nil {if IS_DEBUG {log.Println(_LABEL_, e.Error())}return 0}return this.Size()}//判斷路徑是否存在func isExist(path string) bool {_, err := os.Stat(path)return err == nil || os.IsExist(err)}//檢查檔案路徑檔案夾,不存在則建立func checkFileDir(tp string) {p, _ := path.Split(tp)d, err := os.Stat(p)if err != nil || !d.IsDir() {if err := os.MkdirAll(p, _FILE_CREAT_MODE_); err != nil {log.Println(_LABEL_, "CheckFileDir() Creat dir faile!")}}}//擷取當前指定格式的日期func getNowFormDate(form string) *time.Time {t, err := time.Parse(form, time.Now().Format(form))if nil != err {log.Println(_LABEL_, "getNowFormDate()", err.Error())t = time.Time{}return &t}return &t}//==================================================================測試案例func Test() {logg := New()logg.SetType(1)logg.SetRollingNormal("./logs", "logg")logg.Println("hello world!")}

簡單的使用用例:

var synLoger Logger = Logger{} synLoger.SetType(config.LOG_TYPE_UNKNOW) synLoger.SetRollingNormal(path.Split(config.LOG_PATH_ROOT + "/" + config.LOG_PATH_SYNCER))

1616 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.