The following editor will bring you a detailed explanation of log rotate in golang. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look
Operating system: CentOS 6.9_x64
go language version: 1.8.3
Problem description
The log module of golang provides the log writing function. The sample code is as follows:
/* 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") }
Operating effect:
[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]#
The log module of the go language does not provide log rotate interface, but in actual development we need this function:
We don’t want a single log to be too large, otherwise the text editor cannot open it and it will be difficult to view;
We also don’t want to occupy too much storage Space, you can specify the maximum number of log files to store.
Solution
Achieved with the help of buffered channel.
The sample code is as follows:
/* 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 }
The running effect is as follows:
[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
Discussion
This is just a simple sample code that implements log rotate. More functions need to be developed by yourself.
Okay, that’s all, I hope it helps.
The above is the detailed content of Detailed introduction to the log module in golang. For more information, please follow other related articles on the PHP Chinese website!

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
