Iris 웹 프레임워크용 accesslog 미들웨어는 수신되는 HTTP 요청에 대한 자세한 로깅을 제공합니다. 이 미들웨어는 고도로 구성 가능하며 사용자 정의 필드를 포함하여 요청 및 응답의 다양한 측면을 기록할 수 있습니다.
특징
- 요청 및 응답 세부정보를 기록합니다.
- 다양한 출력 형식(JSON, CSV, 맞춤 템플릿)을 지원합니다.
- 여러 대상(파일, stdout 등)에 로그인할 수 있습니다.
- 비동기 로깅을 지원합니다.
- 사용자 정의 가능한 로그 필드.
- 미들웨어를 조건부로 적용할 수 있습니다.
설치
accesslog 미들웨어를 사용하려면 Iris 애플리케이션에서 이를 가져와야 합니다.
import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/middleware/accesslog" )
기본 사용법
다음은 Iris 애플리케이션에서 accesslog 미들웨어를 사용하는 방법에 대한 기본 예입니다.
package main import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/middleware/accesslog" ) func makeAccessLog() *accesslog.AccessLog { ac := accesslog.File("./access.log") 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.RequestBody = true ac.ResponseBody = false ac.KeepMultiLineError = true ac.PanicLog = accesslog.LogHandler ac.SetFormatter(&accesslog.JSON{ Indent: " ", HumanTime: true, }) return ac } func main() { ac := makeAccessLog() defer ac.Close() app := iris.New() app.UseRouter(ac.Handler) app.Get("/", func(ctx iris.Context) { ctx.WriteString("OK") }) app.Listen(":8080") }
구성 옵션
출력 대상
파일 또는 새로 만들기 기능을 사용하여 로그의 출력 대상을 설정할 수 있습니다.
ac := accesslog.File("./access.log") // or ac := accesslog.New(os.Stdout)
로그 형식
기본 로그 형식은 다음과 같습니다.
Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
다양한 포맷터를 사용하여 로그 형식을 맞춤설정할 수 있습니다.
JSON 포맷터
ac.SetFormatter(&accesslog.JSON{ Indent: " ", HumanTime: true, })
CSV 포맷터
ac.SetFormatter(&accesslog.CSV{})
사용자 정의 템플릿 포맷터
ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"})
사용자 정의 필드
로그 항목에 사용자 정의 필드를 추가할 수 있습니다.
ac.AddFields(func(ctx iris.Context, f *accesslog.Fields) { for k, v := range ctx.Request().Header { value := strings.Join(v, ", ") f.Set("request.header."+k, value) } })
비동기 로깅
성능 향상을 위해 비동기 로깅 활성화:
ac.Async = true
조건부 로깅
특정 경로나 조건에 대한 로깅을 건너뛸 수 있습니다.
app.UseRouter(accesslog.SkipHandler)
고급 사용법
여러 대상에 로깅
io.MultiWriter를 사용하여 여러 대상에 로그인할 수 있습니다.
ac.SetOutput(io.MultiWriter(os.Stdout, accesslog.File("./access.log")))
맞춤 시계
테스트에 유용한 로그 타임스탬프에 대한 사용자 정의 시계를 설정할 수 있습니다.
ac.Clock = accesslog.TClock(time.Now())
미들웨어 통합
accesslog 미들웨어를 다른 미들웨어와 통합:
app.UseRouter(ac.Handler) app.UseRouter(otherMiddleware)
예
JSON 파일에 요청 기록
ac := accesslog.File("access_log.json") ac.SetFormatter(&accesslog.JSON{ Indent: " ", HumanTime: true, }) app.UseRouter(ac.Handler)
로그 회전 사용
자세한 내용은 로그 회전 예시를 참고하세요.
사용자 정의 필드 및 템플릿
자세한 내용은 사용자 정의 필드 및 템플릿 예시를 참조하세요.
클라이언트에 대한 로그 수신 및 렌더링
자세한 내용은 로그 브로커 예시를 참고하세요.
결론
Iris용 accesslog 미들웨어는 HTTP 요청 및 응답을 기록하는 강력한 도구입니다. 유연한 구성 옵션과 사용자 정의 필드 및 형식 지원을 통해 모든 애플리케이션의 요구 사항에 맞게 맞춤화할 수 있습니다.
더 많은 예시와 자세한 사용법은 Iris 공식 문서를 참고하세요.
위 내용은 Iris용 AccessLog 미들웨어의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

WhentestinggocodewithInitFunctions, useExplicitSetUpFunctionsOrsParateTestOvoiddenceNInItfictionSideffects.1) useExplicitSetUpFunctoControlGlobalVariableInitialization.2) CreateSeparateTesteSpilestobySinitFunctions 및 testesten

go'serrorhandlingreturnserrorsvalues whithuseexceptions와 달리 1) Go'sMethodensuresexpliciterRorhandling, promotingrobustcodebutincreasingverbosity.2) Javaandthon'sexextionslowercodebutcodebutcodebutcanlederforlortorifneterfortorifneteriflerortorifnetrorirederiflofertorifneateRoferfortoriflogertoflortoflerortofneateRofer

AneffectiveInterfaceingoisminimal, Clear, and Promotesloosecoupling.1) Minimizetheinterfaceforflexibilityandeasofimplementation.2) usicfacesforabStractionToswapimementationswhangingCallingCode.3) DesignStabilitySUsingInterfacestomockDep

중앙 집중식 오류 처리는 GO 언어에서 코드의 가독성과 유지 가능성을 향상시킬 수 있습니다. 구현 방법 및 장점에는 다음이 포함됩니다. 1. 비즈니스 로직에서 별도의 오류 처리 로직 및 코드를 단순화합니다. 2. 중앙 처리로 오류 처리의 일관성을 확인하십시오. 3. 연기 및 복구를 사용하여 공황을 포착하고 처리하여 프로그램 견고성을 향상시킵니다.

Ingo, alternativestoinitFunctionsincustomInitializationFenctionsandsingletons.1) CustomInitializationFunctionsallowExplicitControlover wheninInitializationOccurs, lexplodElayEdorConditionalSetUps.2) SingletEntensureOne-TimeInitializationIncOncurrent

gohandlesinterfacesandtypeassertionsefectively, codeflexibleandrobustness.1) typeSertionsOncaLownallowRuntImeTypeChecking, asseengehapeInterfaceAndCircLetype.2) TypeStwitchEshandleMultipleTypesePesePesePesePesePese -pervariousShapesimplementing Gry

GO 언어 오류 처리는 오류와 오류를 통해 더욱 유연하고 읽을 수 있습니다. 1.Errors.is는 오류가 지정된 오류와 동일한 지 확인하는 데 사용되며 오류 체인의 처리에 적합합니다. 2. 오류. 오류 유형을 확인할 수있을뿐만 아니라 오류를 특정 유형으로 변환 할 수 있으며 오류 정보 추출에 편리합니다. 이러한 기능을 사용하면 오류 처리 로직을 단순화 할 수 있지만 오류 체인의 올바른 전달에주의를 기울이고 코드 복잡성을 방지하기 위해 과도한 의존성을 피하십시오.

TomakeGoApplicationSRUNFASTERONDERFISTING, 사용 프로파일 링 툴, leverageConcurrency, andManageMemoryEffice.1) usepprofforcpuandMemoryProfingToIndifyBottLenecks.2) UtizeGoroutinesandChannelStoparAllelizetAskSandimProvePercormance.3) 3)


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경