don't stop believing

How to write log file 본문

Golang/Gin

How to write log file

Tongchun 2019. 3. 14. 12:04

로그 파일을 만들어 보겠습니다.

https://github.com/gin-gonic/gin#how-to-write-log-file


코드는 몇지 되지 않습니다.

먼저 command 창에 로그를 찍지 않도록 합니다.

gin.DisableConsoleColor()


로그 파일 이름을 지정하기 위해 날짜를 받아와 로그파일 이름을 만들어 줍니다.

t := time.Now()

startTime := t.Format("2006-01-02 15:04:05")

logFile := "example/ngleLog-" + startTime


그리고 os.Create()로 로그 파일을 만들어 줍니다.

f, err := os.Create(logFile)


로그파일을 gin.DefaultWriter에 넣습니다.

gin.DefaultWriter = io.MultiWriter(f)


package main

import (
	"io"
	"log"
	"os"
	"time"

	"github.com/gin-gonic/gin"
)

func setupRouter() *gin.Engine {
	// Disable Console Color
	gin.DisableConsoleColor()

	t := time.Now()
	startTime := t.Format("2006-01-02 15:04:05")
	logFile := "example/ngleLog-" + startTime

	// Logging to a file.
	f, err := os.Create(logFile)
	if err != nil {
		log.Fatal(err)
	}

	gin.DefaultWriter = io.MultiWriter(f)

	// Use the following code if you need to write the logs to file and console at the same time.
	// gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	r := gin.Default()

	r.GET("/ping", pong)

	return r
}

// I don't know how to get the data.
func pong(c *gin.Context) {
	c.String(200, "pong")
}

func main() {
	r := setupRouter()

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}

위 코드를 실행하면 지정된 경로 (example) 및에 ngleLog-와 날짜로 지정된 파일이 생성됩니다.


몇 번 실행하니 아래와 같이 로그 파일이 쌓입니다.

$ ll example/
total 8
drwxr-xr-x  8 tongchunkim  staff   256B  3 14 14:05 .
drwxr-xr-x  6 tongchunkim  staff   192B  3 14 11:43 ..
-rw-r--r--  1 tongchunkim  staff     0B  3 14 11:58 ngleLog-2019-03-14 11:58:26
-rw-r--r--  1 tongchunkim  staff     0B  3 14 14:05 ngleLog-2019-03-14 14:05:16
-rw-r--r--  1 tongchunkim  staff   795B  3 14 11:58 server.go
drwxr-xr-x  2 tongchunkim  staff    64B  2 26 19:06 statics
drwxr-xr-x  5 tongchunkim  staff   160B  2 27 16:20 templates
drwxr-xr-x  6 tongchunkim  staff   192B  2 28 18:28 upload

로그가 잘 쌓이네요.

로그 Format을 변경한다면 아래 링크를 참고하세요.

https://github.com/gin-gonic/gin#custom-log-format


'Golang > Gin' 카테고리의 다른 글

Goroutines inside a middleware  (0) 2019.03.14
Bind Uri  (0) 2019.03.14
Only Bind Query String  (0) 2019.03.09
Bind Query String or Post Data  (0) 2019.03.09
Model binding and validation  (0) 2019.03.06
Comments