golang 로그 프레임 워 크 logrus

3790 단어
golang 자체 로그 프레임 워 크 기능 은 간단 합 니 다. print, panic, fatal 세 가지 방법 만 제공 하고 일반적인 로그 절단 등 기능 은 지원 되 지 않 습 니 다.sirupsen / logrus 로그 라 이브 러 리 를 추천 합 니 다.
logrus feature
  • 구조 화 되 고 삽입 가능 한 로그 모듈
  • 공식 로그 라 이브 러 리 인터페이스 완전 호 환
  • Field 메커니즘
  • 확장 가능 한 HOOK 메커니즘
  • TEXT 와 JSON 두 가지 선택 가능 한 형식
  • 단순 사용 예시
    std Logger
    공식 로그 와 유사 하 게 logrus 도 std 라 는 표준 로 거 를 제공 합 니 다. 대외 적 으로 내 보 내 는 여러 가지 방법 은 std 기록 로 그 를 직접 사용 합 니 다. 보통 다음 과 같은 방식 으로 사용 할 수 있 습 니 다.
    package main
    
    import log "github.com/sirupsen/logrus"
    
    func main() {
    
        log.Info("hello, world.")
    }
    

    자체 Logger 인 스 턴 스
    package main
    
    import (
      "os"
      "github.com/sirupsen/logrus"
    )
    
    // Create a new instance of the logger. You can have any number of instances.
    var log = logrus.New()
    
    func main() {
      // The API for setting attributes is a little different than the package level
      // exported logger. See Godoc.
      log.Out = os.Stdout
    
      // You could set this to any `io.Writer` such as a file
      // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
      // if err == nil {
      //  log.Out = file
      // } else {
      //  log.Info("Failed to log to file, using default stderr")
      // }
    
      log.WithFields(logrus.Fields{
        "animal": "walrus",
        "size":   10,
      }).Info("A group of walrus emerges from the ocean")
    }
    

    로 컬 파일 시스템 으로 출력
    로 컬 파일 시스템 에 훅 을 통 해 로 그 를 출력 하고 로그 절단 기능 을 제공 합 니 다.
    import (
        "github.com/lestrrat/go-file-rotatelogs"
        "github.com/rifflock/lfshook"
        log "github.com/sirupsen/logrus"
        "time"
        "os"
        "github.com/pkg/errors"
        "path"
    )
    // config logrus log to local filesystem, with file rotation
    func ConfigLocalFilesystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
        baseLogPaht := path.Join(logPath, logFileName)
        writer, err := rotatelogs.New(
            baseLogPaht+".%Y%m%d%H%M",
            rotatelogs.WithLinkName(baseLogPaht), //     ,        
            rotatelogs.WithMaxAge(maxAge), //         
            rotatelogs.WithRotationTime(rotationTime), //         
        )
        if err != nil {
            log.Errorf("config local file system logger error. %+v", errors.WithStack(err))
        }
        lfHook := lfshook.NewHook(lfshook.WriterMap{
            log.DebugLevel: writer, //               
            log.InfoLevel:  writer,
            log.WarnLevel:  writer,
            log.ErrorLevel: writer,
            log.FatalLevel: writer,
            log.PanicLevel: writer,
        })
        log.AddHook(lfHook)
    }
    

    MQ 나 ES 로 출력
    다음 예제 코드 는 hook 을 통 해 로 그 를 amqp 메시지 큐 나 es 에 출력 합 니 다.
    import (
        "github.com/vladoatanasov/logrus_amqp"
        "gopkg.in/olivere/elastic.v5"
        "gopkg.in/sohlich/elogrus.v2"
        log "github.com/sirupsen/logrus"
        "github.com/pkg/errors"
    )
    
    // config logrus log to amqp
    func ConfigAmqpLogger(server, username, password, exchange, exchangeType, virtualHost, routingKey string) {
        hook := logrus_amqp.NewAMQPHookWithType(server, username, password, exchange, exchangeType, virtualHost, routingKey)
        log.AddHook(hook)
    }
    
    // config logrus log to es
    func ConfigESLogger(esUrl string, esHOst string, index string) {
        client, err := elastic.NewClient(elastic.SetURL(esUrl))
        if err != nil {
            log.Errorf("config es logger error. %+v", errors.WithStack(err))
        }
        esHook, err := elogrus.NewElasticHook(client, esHOst, log.DebugLevel, index)
        if err != nil {
            log.Errorf("config es logger error. %+v", errors.WithStack(err))
        }
        log.AddHook(esHook)
    }

    좋은 웹페이지 즐겨찾기