main.go 3.18 KB
package gologger

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"sync"
	"time"
)

const (
	MaxLogSize5MB   int64 = 5 * 1024 * 1024
	MaxLogSize1MB   int64 = 1 * 1024 * 1024
	MaxLogSize500KB int64 = 500 * 1024
	MaxLogSize100KB int64 = 100 * 1024
	MaxLogSize512B  int64 = 512
	logDirName            = "log"
)

type Logger struct {
	mu         *sync.Mutex
	outputFile *os.File

	outputFileName string
	maxFileSize    int64
}

func New(name string, maxFileSize int64) (logger *Logger, err error) {
	logger = &Logger{}

	logger.outputFileName = name + "-log"
	logger.mu = &sync.Mutex{}
	logger.maxFileSize = maxFileSize

	err = os.Mkdir(logDirName, os.ModePerm)
	if err != nil {
		if !os.IsExist(err) {
			fmt.Printf("logger: mkdir: couldn't create event log directory\n")
			return nil, err
		}
	}

	timestamp := "_" + time.Now().Format(time.RFC3339)
	path := filepath.Join(logDirName, logger.outputFileName+timestamp+".txt")
	logger.outputFile, err = os.Create(path)
	if err != nil {
		fmt.Printf("logger: new: couldn't create event log file\n")
		return nil, err
	}

	return logger, nil
}

func (logger *Logger) Print(format string, v ...interface{}) {
	msg := fmt.Sprintf(format, v...)
	fmt.Printf(time.Now().Format(time.RFC3339) + ": " + msg + "\n")
}

func (logger *Logger) Log(format string, v ...interface{}) {
	if logger.outputFile != nil {
		logger.mu.Lock()
		defer logger.mu.Unlock()

		msg := fmt.Sprintf(format, v...)
		s := time.Now().Format(time.RFC3339) + ": " + msg + "\n"
		if logger.shouldSplit(len(s)) {
			logger.split()
		}
		logger.outputFile.WriteString(s)
	}
}

// TODO(marko)
/*
func (logger *Logger) LogHTTPRequest(req *http.Request) {
	if logger.outputFile != nil {
		logger.mu.Lock()
		defer logger.mu.Unlock()

		msg := fmt.Sprintf(format, v...)
		if logger.shouldSplit(len(s)) {
			logger.split()
		}
		logger.outputFile.WriteString(time.Now().Format(time.RFC3339) + ": " + msg + "\n")
	}
}
*/

func (logger *Logger) Trace(format string, v ...interface{}) {
	if logger.outputFile != nil {
		logger.mu.Lock()
		defer logger.mu.Unlock()
		_, file, line, ok := runtime.Caller(1)

		s := ""
		msg := fmt.Sprintf(format, v...)
		if ok {
			s = fmt.Sprintf("%s: %s %d: %s\n", time.Now().Format(time.RFC3339), file, line, msg)
		} else {
			s = fmt.Sprintf(time.Now().Format(time.RFC3339) + ": [can't retreive stack details]:" + msg + "\n")
		}
		if logger.shouldSplit(len(s)) {
			logger.split()
		}
		logger.outputFile.WriteString(s)
	}
}

func (logger *Logger) Close() {
	if logger.outputFile != nil {
		err := logger.outputFile.Close()
		if err != nil {
			fmt.Printf("logger: on exit: couldn't close event log file\n")
		}
	}
}

func (l *Logger) split() {
	timestamp := "_" + time.Now().Format(time.RFC3339)
	// close old file
	err := l.outputFile.Close()
	if err != nil {
		fmt.Printf("logger: split: couldn't close event file\n")
		return
	}
	// open new file
	var errnew error
	path := filepath.Join(logDirName, l.outputFileName+timestamp)
	l.outputFile, errnew = os.Create(path)

	if errnew != nil {
		fmt.Printf("logger: split: couldn't create event log file\n")
	}
}

func (l *Logger) shouldSplit(nextEntrySize int) bool {
	stats, _ := l.outputFile.Stat()
	return int64(nextEntrySize) >= (l.maxFileSize - stats.Size())
}