IoWriter4SplitFile 日志分割文件 不同级别的日志 不同的文件

 

 

IoWriter.go

package main

import (
    "github.com/natefinch/lumberjack"
    "io"
)

// github.com\natefinch\lumberjack@v2.0.0+incompatible\lumberjack.go

type SplitFileArgs struct {
    // Filename is the file to write logs to.  Backup log files will be retained
    // in the same directory.  It uses <processname>-lumberjack.log in
    // os.TempDir() if empty.
    Filename string `json:"filename" yaml:"filename"`

    // MaxSize is the maximum size in megabytes of the log file before it gets
    // rotated. It defaults to 100 megabytes.
    MaxSize int `json:"maxsize" yaml:"maxsize"`

    // MaxAge is the maximum number of days to retain old log files based on the
    // timestamp encoded in their filename.  Note that a day is defined as 24
    // hours and may not exactly correspond to calendar days due to daylight
    // savings, leap seconds, etc. The default is not to remove old log files
    // based on age.
    MaxAge int `json:"maxage" yaml:"maxage"`

    // MaxBackups is the maximum number of old log files to retain.  The default
    // is to retain all old log files (though MaxAge may still cause them to get
    // deleted.)
    MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

    // LocalTime determines if the time used for formatting the timestamps in
    // backup files is the computer's local time.  The default is to use UTC
    // time.
    LocalTime bool `json:"localtime" yaml:"localtime"`

    // Compress determines if the rotated log files should be compressed
    // using gzip. The default is not to perform compression.
    Compress bool `json:"compress" yaml:"compress"`

    size int64
}

func IoWriter4SplitFile(path string) io.Writer {
    return &lumberjack.Logger{
        Filename:   path,
        MaxSize:    2,
        MaxBackups: 8,
        MaxAge:     32,
        Compress:   true,
    }
}

 

 

logger.go

 

package main

import (
    "os"

    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

const PathSeparator = string(os.PathSeparator)

var logger *(zap.Logger)

// zap package - go.uber.org/zap - pkg.go.dev https://pkg.go.dev/go.uber.org/zap
func init() {
    // For some users, the presets offered by the NewProduction, NewDevelopment,
    // and NewExample constructors won't be appropriate. For most of those
    // users, the bundled Config struct offers the right balance of flexibility
    // and convenience. (For more complex needs, see the AdvancedConfiguration
    // example.)
    //
    // See the documentation for Config and zapcore.EncoderConfig for all the
    // available options.
   
    // First, define our level-handling logic.
    highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
        return lvl >= zapcore.ErrorLevel
    })
    lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
        return lvl < zapcore.ErrorLevel
    })

    en := func() zapcore.EncoderConfig {
        return zapcore.EncoderConfig{
            TimeKey:        "ts",
            LevelKey:       "level",
            NameKey:        "logger",
            CallerKey:      "caller",
            FunctionKey:    zapcore.OmitKey,
            MessageKey:     "msg",
            StacktraceKey:  "stacktrace",
            LineEnding:     zapcore.DefaultLineEnding,
            EncodeLevel:    zapcore.CapitalLevelEncoder,
            EncodeTime:     zapcore.ISO8601TimeEncoder,
            EncodeDuration: zapcore.SecondsDurationEncoder,
            EncodeCaller:   zapcore.ShortCallerEncoder,
        }
    }
    // zap package - go.uber.org/zap - pkg.go.dev https://pkg.go.dev/go.uber.org/zap
    // The bundled Config struct only supports the most common configuration
    // options. More complex needs, like splitting logs between multiple files
    // or writing to non-file outputs, require use of the zapcore package.
    coreHighPriority := zapcore.NewCore(
        zapcore.NewConsoleEncoder(en()),
        zapcore.NewMultiWriteSyncer(
            zapcore.AddSync(os.Stdout),
            zapcore.AddSync(IoWriter4SplitFile("logs"+PathSeparator+"ERROR-"+".log")),
        ),
        highPriority)
    coreLowPriority := zapcore.NewCore(
        zapcore.NewJSONEncoder(en()),
        zapcore.NewMultiWriteSyncer(
            zapcore.AddSync(os.Stdout),
            zapcore.AddSync(IoWriter4SplitFile("logs"+PathSeparator+"DEBUG-"+".log")),
        ),
        lowPriority)
    opts := []zap.Option{
        zap.AddStacktrace(zapcore.WarnLevel),
    }
    core := zapcore.NewTee(
        coreHighPriority,
        coreLowPriority,
    )
    logger = zap.New(core, opts...)
    defer logger.Sync()
    logger.Info("logger construction succeeded")
}

 

 

 

调用

package main
func main() {
    logger.Info("cron.New()")
}

 

posted @ 2022-01-11 17:39  papering  阅读(92)  评论(0编辑  收藏  举报