4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goで時間でファイルをローテートする

Last updated at Posted at 2016-09-13

単純に時間で分割してほしいだけだったんですが、ピンポイントのものがなかったので作ってみました

package trfile

import (
	"os"
	"path"
	"time"
)

type TimeRotateFile struct {
	fileNameFormat string
	file           *os.File
}

var (
	FileMode    os.FileMode = 0644
	DirFileMode os.FileMode = 0755
)

func NewFormat(fileNameFormat string) (*TimeRotateFile, error) {
	trf := &TimeRotateFile{
		fileNameFormat: fileNameFormat,
	}

	if err := trf.fileSet(); err != nil {
		return nil, err
	}

	return trf, nil
}

func (trf *TimeRotateFile) fileNameNow() string {
	return time.Now().Format(trf.fileNameFormat)
}

func (trf *TimeRotateFile) fileSet() error {
	fileNameNow := trf.fileNameNow()

	if dir, _ := path.Split(fileNameNow); len(dir) > 0 {
		if err := os.MkdirAll(dir, DirFileMode); err != nil {
			return err
		}
	}

	file, err := os.OpenFile(fileNameNow, os.O_RDWR|os.O_CREATE|os.O_APPEND, FileMode)

	if err != nil {
		return err
	}

	trf.file = file

	return nil
}

func (trf *TimeRotateFile) Write(b []byte) (int, error) {
	if fileNameNow := trf.fileNameNow(); fileNameNow != trf.file.Name() {
		if err := trf.file.Close(); err != nil {
			return 0, err
		}

		if err := trf.fileSet(); err != nil {
			return 0, err
		}
	}

	return trf.file.Write(b)
}

func (trf *TimeRotateFile) Name() string {
	return trf.file.Name()
}

func (trf *TimeRotateFile) Close() error {
	return trf.file.Close()
}

Golangの "2006-01-02 Mon 15:04:05" みたいなタイムフォーマット用いてファイル名やディレクトリを指定します

package main

import (
    "log"
    "os"

    "github.com/ngc224/trfile"
)

var fileNameFormat = "logs/2006/01/02/halo.log"

func main() {
    w, err := trfile.NewFormat(fileNameFormat)

    if err != nil {
        os.Exit(1)
    }

    log.SetOutput(w)
    log.Println("Halo World!")
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?