어플리케이션 파일 레코더
func main() {
app := iris.Default()
// 파일로 기록
// 파일에 기록할 때 자동으로 색상 비활성화
f, _ := os.Create("iris.log")
app.Logger().SetOutput(f)
// 파일과 콘솔에 로그를 작성해야 할 경우 다음 코드를 사용합니다
// app.Logger().AddOutput(os.Stdout)
app.Get("/ping", func(ctx iris.Context) {
ctx.WriteString("pong")
})
app.Listen(":8080")
}
로그 출력 색상 제어
기본적으로 콘솔에 로그 출력은 감지된 TTY에 기반하여 색상이 입혀집니다.
정규 사례에서 수준 제목, 텍스트, 색상 및 스타일을 사용자 정의합니다.
golog
및 pio
를 가져옵니다:
import (
"github.com/kataras/golog"
"github.com/kataras/pio"
// [...]
)
DebugLevel
과 같은 수준을 가져와 사용자 정의합니다:
level := golog.Levels[golog.DebugLevel]
수준의 텍스트, 제목 및 스타일을 완전히 제어할 수 있습니다:
// 수준 이름
// 소문자 이름은 올바른 수준 유형으로 문자열 수준을 변환하는 데 사용될 것입니다
Name string
// 이 특정 로그 수준에 해당하는 대체 이름입니다
// Name = "warn"과 같은 경우
// AlternativeNames = []string{"warning"}, 선택 사항입니다
// 그래서 Name을 간단한 문자열로 유지하고 새로운 필드를 생성합시다.
AlternativeNames []string
// 제목은 로그 수준의 접두어입니다
// `ColorCode`와 `Style`도 있습니다
// `ColorCode`와 `Style`은 작성자 간에 일관성이 있어야 합니다
Title string
// `Title`의 색상입니다
ColorCode int
// `Title`의 하나 이상의 풍부한 옵션입니다
Style []pio.RichOption
예제 코드:
level := golog.Levels[golog.DebugLevel]
level.Name = "debug" // 기본값
level.Title = "[DBUG]" // 기본값
level.ColorCode = pio.Yellow // 기본값
출력 형식 변경:
app.Logger().SetFormat("json", " ")
사용자 정의 포매터 등록:
app.Logger().RegisterFormatter(new(myFormatter))
golog.Formatter 인터페이스는 다음과 같습니다:
// Formatter는 로거의 작성자에게 로그를 인쇄할 책임이 있습니다.
type Formatter interface {
// 포매터의 이름입니다.
String() string
// 옵션을 설정하고 일반적인 경우 복제된 개체를 반환합니다. `Logger.SetFormat` 참조
Options(opts ...interface{}) Formatter
// "dest" 로거에 "log"를 씁니다.
Format(dest io.Writer, log *Log) bool
}
수준에 따라 출력 및 형식 변경:
app.Logger().SetLevelOutput("error", os.Stderr)
app.Logger().SetLevelFormat("json")
요청 로깅
위에서 본 응용프로그램 로거는 주로 응용프로그램과 관련된 정보 및 오류를 기록하는 데 사용됩니다. 한편, 아래에서 볼 수 있는 액세스 로거는 주로 들어오는 HTTP 요청과 응답을 기록하는 데 사용됩니다.
package main
import (
"os"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/accesslog"
)
// 예제 및 해당 주석을 주의 깊게 읽으십시오.
func makeAccessLog() *accesslog.AccessLog {
// 새로운 액세스 로그 미들웨어를 초기화합니다.
ac := accesslog.File("./access.log")
// 콘솔에 로깅을 비활성화하려면 이 줄을 제거하십시오:
ac.AddOutput(os.Stdout)
// 기본 구성:
ac.Delim = '|'
ac.TimeFormat = "2006-01-02 15:04:05"
ac.Async = false
ac.IP = true
ac.BytesReceivedBody = true
ac.BytesSentBody = true
ac.BytesReceived = false
ac.BytesSent = false
ac.BodyMinify = true
ac.RequestBody = true
ac.ResponseBody = false
ac.KeepMultiLineError = true
ac.PanicLog = accesslog.LogHandler
// 만약 형식 지정기가 누락된 경우 기본 라인 형식을 사용하십시오:
// Time|Delay|Status|Method|Path|IP|Path Query Parameters|Received Bytes|Sent Bytes|Request|Response|
//
// 사용자 정의 포매터 설정:
ac.SetFormatter(&accesslog.JSON{
Indent: " ",
HumanTime: true,
})
// ac.SetFormatter(&accesslog.CSV{})
// ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
return ac
}
func main() {
ac := makeAccessLog()
defer ac.Close() // 파일을 닫습니다.
app := iris.New()
// 미들웨어 등록 (UseRouter 사용 시 HTTP 오류도 잡을 수 있습니다).
app.UseRouter(ac.Handler)
app.Get("/", indexHandler)
app.Listen(":8080")
}
func indexHandler(ctx iris.Context) {
ctx.WriteString("OK")
}
더 많은 예제는 여기서 확인하십시오: _examples/logging/request-logger.