Go에 있는 log 패키지를 알아보자

2 minute read

소스코드: https://github.com/BaeJi77/blog-code/tree/main/2021-11/go-log

log

로그파일: 컴퓨팅에서 로그파일은 운영 체제나 다른 소프트웨어가 실행 중에 발생하는 이벤트나 각기 다른 사용자의 통신 소프트웨어 간의 메시지를 기록한 파일이다. 로그를 기록하는 행위는 로깅이라고 한다 wiki백과

기본적으로 우리는 프로그래밍 개발을 했을 경우 특정 상황에서 정보를 얻기 위해서 로그를 남긴다고 합니다.

go에서는 표준 패키지에서 log라는 패키지를 제공해주고 있어서 추가적인 패키지 없이 바로 사용할 수 있습니다.

go 안에서 log

logger와 default

type Logger struct {
	mu     sync.Mutex // ensures atomic writes; protects the following fields
	prefix string     // prefix on each line to identify the logger (but see Lmsgprefix)
	flag   int        // properties
	out    io.Writer  // destination for output
	buf    []byte     // for accumulating text to write
}

func New(out io.Writer, prefix string, flag int) *Logger {
	return &Logger{out: out, prefix: prefix, flag: flag}
}

var std = New(os.Stderr, "", LstdFlags)

위에 있는 코드는 log 패키지 안에 있는 코드입니다. 여기서 우리가 아무 선언도 하지 않았지만 logger를 바로 사용할 수 있는 이유가 있습니다.

바로 std라는 변수가 log 패키지 내부에 있는데요. 해당 변수가 선언 되어 있기 때문에 우리는 어떤 선언도 하지 않아도 바로 log.Printf()와 같은 메소드를 바로 사용할 수 있습니다.

logger 설정

// These flags define which text to prefix to each log entry generated by the Logger.
// Bits are or'ed together to control what's printed.
// With the exception of the Lmsgprefix flag, there is no
// control over the order they appear (the order listed here)
// or the format they present (as described in the comments).
// The prefix is followed by a colon only when Llongfile or Lshortfile
// is specified.
// For example, flags Ldate | Ltime (or LstdFlags) produce,
//	2009/01/23 01:23:23 message
// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
const (
	Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	Lmsgprefix                    // move the "prefix" from the beginning of the line to before the message
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

logger에서 flag 값을 설정할 수 있습니다. 해당 flag 값을 가지고 log에 형식을 변경할 수가 있습니다.

func main() {
	logger11 := log.New(os.Stdout, "hello:::::", log.LUTC | log.Llongfile)
	logger11.Println("hello")
}

---
결과: 
hello:::::/Users/user/GolandProjects/awesomeProject/main.go:12: hello

위에 모습처럼 우리가 설정한 모습처럼 결과를 볼수가 있습니다.

file로 output

우리는 file로 output을 설정할 수 있는 방법이 2가지가 있습니다.

첫번째로는 SetOutput() 메소드를 이용하여서 output 설정을 변경하는 것입니다.

func main() {
	logger11 := log.New(os.Stdout, "hello:::::", log.LUTC | log.Llongfile)
	logger11.Println("hello")

	file, _ := os.OpenFile("hello.log", os.O_CREATE | os.O_RDWR, 0644)
	logger11.SetOutput(file)
	logger11.Println("hello")
}
---
console:
hello:::::/Users/user/GolandProjects/awesomeProject/main.go:12: hello

go-log-file

위에 사진을 보게되면 console뿐만 아니라 파일로도 데이터가 저장됩니다.

두번째는 처음 logger을 만들때 output 설정하는 방법입니다. 해당 방법은 처음 설정한 이후에 변경이 어렵습니다.

func main() {
	file, _ := os.OpenFile("hello.log", os.O_CREATE | os.O_RDWR, 0644)
	logger11 := log.New(file, "hello:::::", log.LUTC | log.Llongfile) // output을 file로 설정
	logger11.Println("hello")
}

더 나아가기

  • logrus: log 패키지를 기본적으로 제공해주면서 log를 다양한 형식으로 표현하고 사용할 수 있도록 api를 제공해주는 패키지입니다.
  • lumberjack: for writing logs to rolling files.. log은 어떤 설정도 없다면 끝도 없이 커질것이며 삭제되지도 않을 것입니다. 그런 경우를 위해서 log 파일에 대한 설정을 제공해줍니다.

ref

Leave a comment