Skip to content

Using logrus with multiple files for each level

//WriterHook writes to different log files for different levels.
type WriterHook struct {
	Writer    io.Writer
	LogLevels []log.Level
}

var logger *log.Logger

func initLogger() {
	logger = log.New()
	// with Json Formatter
	logger.Formatter = &log.JSONFormatter{}
	_ = os.Mkdir("log", 0755)
	setupLogFiles()
}

//GetLogger returns logrus logger
func GetLogger() *log.Logger {
	if logger == nil {
		initLogger()
	}
	return logger
}

//Fire hook
func (hook *WriterHook) Fire(entry *log.Entry) error {
	line, err := entry.String()
	if err != nil {
		return err
	}
	_, err = hook.Writer.Write([]byte(line))
	return err
}

//Levels for logrus.Hook
func (hook *WriterHook) Levels() []log.Level {
	return hook.LogLevels
}

//createFiles creates log files
func createFiles() []*os.File {
	config := config.GetConfig()
	var files []*os.File

	for _, level := range log.AllLevels {
		fpath := fmt.Sprintf("%s%s.log", config.GetString("app.log"), level.String())
		f, _ := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
		files = append(files, f)
	}

	return files
}

func setupLogFiles() {
	logger.SetOutput(ioutil.Discard)

	files := createFiles()
	for _, file := range files {
		for _, level := range log.AllLevels {
			if strings.Contains(file.Name(), level.String()) {
				logger.AddHook(&WriterHook{
					Writer: file,
					LogLevels: []log.Level{
						level,
					},
				})
				break
			}
		}
	}
}
Published inGolang

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *