搜尋
首頁後端開發Python教學詳細介紹golang中的log模組

詳細介紹golang中的log模組

Jun 16, 2017 am 10:57 AM
golang

下面小編就為大家帶來一篇golang之log rotate詳解。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧

作業系統: CentOS 6.9_x64

go語言版本: 1.8.3

##問題描述

golang的log模組提供的有寫日誌功能,範例程式碼如下:

/*
golang log example

*/
package main

import (
  "log"
  "os"
)

func main() {
  logFile,err := os.Create("test1.log")
  defer logFile.Close()
  if err != nil {
    log.Fatalln("open file error!")
  }
  logger := log.New(logFile,"[Debug]",log.Ldate | log.Ltime | log.Lshortfile)
  logger.Println("test debug message")
  logger.SetPrefix("[Info]")
  logger.Println("test info message")

}

執行效果:

[root@local t2]# go build logTest1.go
[root@local t2]# ./logTest1
[root@local t2]# cat test1.log
[Debug]2017/06/13 23:18:36 logTest1.go:19: test debug message
[Info]2017/06/13 23:18:36 logTest1.go:21: test info message
[root@local t2]#

go語言的log模組沒有提供log rotate接口,但實際開發中我們需要該功能:

我們不希望單一日誌過大,否則文字編輯器無法打開,查看比較困難;

更不希望佔用太大的存儲空間,可以指定最多存多少個日誌檔。

解決方案

借助帶有緩衝的channel來實現。

範例程式碼如下:

/*
  golang log rotate example

*/

package main

import (
  "fmt"
  "log"
  "os"
  "time"
)

const (
  BACKUP_COUNT = 5
  MAX_FILE_BYTES = 2 * 1024
)

func doRotate(fPrefix string) {
  for j := BACKUP_COUNT; j >= 1; j-- {
    curFileName := fmt.Sprintf("%s_%d.log",fPrefix,j)
    k := j-1
    preFileName := fmt.Sprintf("%s_%d.log",fPrefix,k)

    if k == 0 {
      preFileName = fmt.Sprintf("%s.log", fPrefix)
    }
    _,err := os.Stat(curFileName)
    if err == nil {
      os.Remove(curFileName)
      fmt.Println("remove : ", curFileName)
    }
    _,err = os.Stat(preFileName)
    if err == nil {
      fmt.Println("rename : ", preFileName, " => ", curFileName)
      err = os.Rename(preFileName, curFileName)
      if err != nil {
        fmt.Println(err)
      }
    }
  }
}

func NewLogger(fPrefix string) (*log.Logger, *os.File) {
  var logger *log.Logger
  fileName := fmt.Sprintf("%s.log", fPrefix)
  fmt.Println("fileName :", fileName)
  logFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

  if err != nil {
    fmt.Println("open file error!")
  } else {
    logger = log.New(logFile, "[Debug]", log.Ldate|log.Ltime|log.Lshortfile)
  }
  return logger, logFile
}

func logWorker(msgQueue <-chan string) {
  fPrefix := "msg"
  logger, logFile := NewLogger(fPrefix)
  for msg := range msgQueue {
    logger.Println(msg)
    fi, err2 := logFile.Stat()
    if err2 == nil {
      if fi.Size() > MAX_FILE_BYTES {
        logFile.Close()
        doRotate(fPrefix)
        logger,logFile = NewLogger(fPrefix)
      }
    }
  }
  logFile.Close()
}

func main() {
  msgQueue := make(chan string, 1000)
  go logWorker(msgQueue)

  for j := 1; j <= 1000; j++ {
    msgQueue <- fmt.Sprintf("msg_%d", j)
    time.Sleep(1 * time.Second)
  }
  close(msgQueue)
  return
}

運行效果如下:

[root@local t2]# ./logRotateTest1
fileName : msg.log
rename : msg.log => msg_1.log
fileName : msg.log
rename : msg_1.log => msg_2.log
rename : msg.log => msg_1.log
fileName : msg.log
rename : msg_2.log => msg_3.log
rename : msg_1.log => msg_2.log
rename : msg.log => msg_1.log
fileName : msg.log
^C

討論

這裡只是個簡單的範例程式碼,實作了log rotate,更多功能需自行開發。

好,就這些了,希望對你有幫助。

以上是詳細介紹golang中的log模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您應該檢查腳本是否使用錯誤的Python版本執行?您應該檢查腳本是否使用錯誤的Python版本執行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),