golang

Golang: 개발중에만 log 출력이 되어야 한다면

주먹불끈 2023. 6. 10. 21:09

개요

Golang 개발시에만 로그가 출력되었으면 하는 경우가 있다. 이럴때는 환경변수와 로그 설정을 활용할 수 있다.

단순한 내용이지만 기록해둔다.

코드 예시

  1. 환경변수 RUN_MODE를 읽어들여서 그 값이 dev 가 아니라면 log의 출력을 io.Discard로 내보낸다(== 버려버린다) 
  2. dev 라면 discard 되지 않고 출력이 된다.

💡 Discard is an io.Writer on which all Write calls succeed without doing anything.

// Go 1.20
package main

import (
  "io"
  "log"
  "os"
)

func main() {
  runMode := os.Getenv("RUN_MODE")
  if runMode != "dev" {
    log.SetOutput(io.Discard)
  }
  log.SetFlags(log.LstdFlags | log.Lshortfile)

  log.Println("This log will be seen only when RUN_MODE is 'dev'")
  fmt.Println("Program started")
}

결과

그냥 실행

$ go run .
Program started

환경변수와 함께 실행

$ RUN_MODE=dev go run .
2009/11/10 23:00:00 prog.go:18: This log will be seen only when RUN_MODE is 'dev'
Program started
반응형