github.com/aswedchain/aswed@v1.0.1/log/handler_rotate.go (about)

     1  // Copyright 2020 YOUCHAIN FOUNDATION LTD.
     2  // This file is part of the go-youchain library.
     3  //
     4  // The go-youchain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-youchain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-youchain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package log
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path"
    23  	"path/filepath"
    24  
    25  	"gopkg.in/natefinch/lumberjack.v2"
    26  )
    27  
    28  type RotateConfig struct {
    29  	LogDir     string `json:"log_dir"`
    30  	Filename   string `json:"filename"` // file name
    31  	MaxAge     int    `json:"max_age"`  // max age
    32  	MaxSize    int    `json:"max_size"` // MB
    33  	MaxBackups int    `json:"max_backups"`
    34  }
    35  
    36  var defaultConfig = &RotateConfig{
    37  	LogDir:     "logs",
    38  	Filename:   "chain.log",
    39  	MaxSize:    100,
    40  	MaxAge:     7,
    41  	MaxBackups: 10,
    42  }
    43  
    44  func NewRotateConfig() *RotateConfig {
    45  	conf := *defaultConfig
    46  	return &conf
    47  }
    48  
    49  func NewFileRotateHandler(config *RotateConfig, format Format) Handler {
    50  	if err := config.setup(); err != nil {
    51  		fmt.Println(err.Error())
    52  		return nil
    53  	}
    54  
    55  	logDir := config.LogDir
    56  	if !filepath.IsAbs(logDir) {
    57  		logDir, _ = filepath.Abs(logDir)
    58  	}
    59  	log := lumberjack.Logger{
    60  		Filename:   path.Join(logDir, config.Filename),
    61  		MaxSize:    config.MaxSize, // megabytes
    62  		MaxBackups: config.MaxBackups,
    63  		MaxAge:     config.MaxAge, // days
    64  		LocalTime:  true,
    65  		Compress:   true, // disabled by default
    66  	}
    67  
    68  	h := StreamHandler(&log, format)
    69  
    70  	return FuncHandler(func(r *Record) error {
    71  		return h.Log(r)
    72  	})
    73  }
    74  
    75  func (c *RotateConfig) setup() error {
    76  	if len(c.LogDir) == 0 {
    77  		panic("Failed to parse logger folder:" + c.LogDir + ".")
    78  	}
    79  
    80  	if err := os.MkdirAll(c.LogDir, 0700); err != nil {
    81  		panic("Failed to create logger folder:" + c.LogDir + ". err:" + err.Error())
    82  	}
    83  	return nil
    84  }