1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package logger
- import (
- "fmt"
- "log"
- "os"
- "path/filepath"
- "strconv"
- "time"
- )
- /*
- ArozOS System Logger
- This script is designed to make a managed log for the ArozOS system
- and replace the ton of log.Println in the system core
- */
- type Logger struct {
- LogToFile bool
- file *os.File
- }
- func NewLogger(logFilePrefix string, logFolder string, logToFile bool) (*Logger, error) {
- err := os.MkdirAll(logFolder, 0775)
- if err != nil {
- return nil, err
- }
- year, month, _ := time.Now().Date()
- logFilePath := filepath.Join(logFolder, logFilePrefix+"_"+strconv.Itoa(year)+"-"+strconv.Itoa(int(month))+".log")
- f, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
- if err != nil {
- return nil, err
- }
- return &Logger{
- LogToFile: logToFile,
- file: f,
- }, nil
- }
- func (l *Logger) PrintAndLog(title string, message string, originalError error) {
- l.Log(title, message, originalError)
- log.Println("[" + title + "] " + message)
- }
- func (l *Logger) Log(title string, errorMessage string, originalError error) {
- if l.LogToFile {
- if originalError == nil {
- l.file.WriteString(time.Now().Format("2006-01-02 15:04:05.000000") + "|" + fmt.Sprintf("%-16s", title) + " [INFO]" + errorMessage + "\n")
- } else {
- l.file.WriteString(time.Now().Format("2006-01-02 15:04:05.000000") + "|" + fmt.Sprintf("%-16s", title) + " [ERROR]" + errorMessage + " " + originalError.Error() + "\n")
- }
- }
- }
- func (l *Logger) Close() {
- l.file.Close()
- }
|