Created
February 10, 2023 14:09
-
-
Save ronaldwolvers/ade445d35ab6bfb89ec0f741c75250aa to your computer and use it in GitHub Desktop.
Writing logs to a file in Go using a buffer (Go version 1.19)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package logging | |
| import ( | |
| "fmt" | |
| "os" | |
| "time" | |
| ) | |
| var enable_logging bool = true | |
| const LOGS_BUFFER_SIZE = 50 | |
| var logs_buffer []string = make([]string, 0, LOGS_BUFFER_SIZE) | |
| func Print(a ...any) { | |
| if (enable_logging == false) { | |
| return | |
| } | |
| fmt.Print(a...) | |
| addStringToLogsBuffer(fmt.Sprint(a...)) | |
| } | |
| func Printf(format string, a ...any) { | |
| if (enable_logging == false) { | |
| return | |
| } | |
| fmt.Printf(format, a...) | |
| addStringToLogsBuffer(fmt.Sprintf(format, a...)) | |
| } | |
| func Println(a ...any) { | |
| if (enable_logging == false) { | |
| return | |
| } | |
| fmt.Println(a...) | |
| addStringToLogsBuffer(fmt.Sprintln(a...)) | |
| } | |
| func addStringToLogsBuffer(logString string) { | |
| currentTimeMillis := time.Now() | |
| timeString := fmt.Sprint(currentTimeMillis.Format("Mon Jan 2 15:04:05")) | |
| index := len(logs_buffer) | |
| if (index < cap(logs_buffer)) { | |
| logs_buffer = append(logs_buffer, timeString + ": \t" + logString) | |
| } | |
| if (index == LOGS_BUFFER_SIZE - 1) { | |
| fmt.Println("Logs buffer is full...") | |
| //Buffer is full, write logs to logs file and clear the buffer. | |
| for _, logInBuffer := range logs_buffer { | |
| logsWriter := createLogsFile() | |
| if (logsWriter == nil) { | |
| return | |
| } | |
| defer logsWriter.Close() | |
| fmt.Fprint(logsWriter, logInBuffer) | |
| logs_buffer = make([]string, 0, LOGS_BUFFER_SIZE) | |
| } | |
| } | |
| } | |
| func createLogsFile() *os.File { | |
| //Create logs folder | |
| os.Mkdir("logs", 0755) | |
| f, err := os.OpenFile("logs/logs", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) | |
| if err != nil { | |
| fmt.Println("Something went wrong while creating logs/logs file: ", err.Error()) | |
| return nil | |
| } | |
| return f | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not synchronized and therefore not suitable for use by multiple threads at once!