개요
이 가이드에서는 드라이버를 사용하여 애플리케이션에 대한 로깅 을 구성하는 방법을 배울 수 있습니다. 로깅의 목적은 드라이버 이벤트를 기록하는 것입니다.
로거는 사용자가 지정할 수 있는 심각도 또는 상세도 수준으로 메시지를 기록합니다. 애플리케이션에서 로거를 활성화하면 높은 수준, 자세한 수준 또는 그 중간 수준에서 애플리케이션 활동에 대한 정보를 수신할 수 있습니다.
팁
로깅 심각도 수준에 대해 자세히 학습하려면 메시지 로깅에 대한 Syslog 표준에 대한 Wikipedia 항목을 참조하세요.
로깅 활성화
Client 인스턴스에서 로거를 구성하려면 ClientOptions 객체를 생성할 때 SetLoggerOptions() 메서드를 호출합니다. SetLoggerOptions() 메서드는 LoggerOptions 유형을 매개변수로 사용합니다. 애플리케이션에 대한 로거를 구성하려면 이 LoggerOptions 유형을 설정합니다.
다음 코드는 로깅을 활성화한 상태에서 클라이언트를 만드는 방법을 보여줍니다.
loggerOptions := options. Logger(). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions) client, err := mongo.Connect(clientOptions)
로거 구성
LoggerOptions 객체를 만들려면 options.Logger() 메서드를 호출합니다. 다음 표에서는 LoggerOptions 유형의 속성을 설정하여 로거를 구성하는 방법을 설명합니다. 첫 번째 열은 LoggerOptions 속성을 나열하고, 두 번째 열은 속성을 설명하며, 세 번째 열은 각 속성에 해당하는 setter 메서드 및 매개 변수를 나열합니다.
속성 | 설명 | 세터 메서드 |
|---|---|---|
| 구성 요소를 로그 심각도 수준에 매핑합니다. 드라이버는 각 |
|
| 운전자 메시지를 로그 데 사용하는 로깅 인터페이스입니다. |
|
| 드라이버가 내보내는 각 로그 메시지의 최대 길이(바이트)입니다. 메시지가 이 값보다 크면 드라이버는 메시지를 자르고 부분 로그 메시지에 줄임표를 추가합니다. |
|
팁
특정 파일에 로그 쓰기
기본적으로 표준 로거는 콘솔(stderr)에 메시지를 기록합니다. MONGODB_LOG_PATH 환경 변수를 stdout 또는 파일 경로로 설정하여 로깅 대상을 지정할 수 있습니다.
로그 구성 요소 및 심각도 수준
드라이버가 기록하는 구성 요소를 지정하려면 LogComponent 유형을 설정합니다. 다음 표에서는 LogComponent 에 대한 기본 제공 사양을 설명합니다.
설정 | 설명 | 열거형 값 |
|---|---|---|
| 모든 구성 요소에 대한 로깅 활성화 |
|
| 명령 모니터 로깅 활성화 |
|
| 토폴로지 로깅 활성화 |
|
| 서버 선택 로깅 활성화 |
|
| 연결 서비스 로깅 활성화 |
|
설정 이름이나 설정의 열거형 값을 사용하여 로그 구성 요소를 지정할 수 있습니다. 다음 코드는 명령 모니터링을 활성화하는 동일한 방법을 보여줍니다.
// Using named value comp := options.LogComponentCommand // Using enumeration comp := options.LogComponent(1)
로그 심각도 수준을 지정하려면 LogLevel 유형을 설정합니다. 다음 코드는 LevelDebug 수준에서 로깅을 사용 설정하는 방법을 보여줍니다.
lvl := options.LogLevelDebug
중요
고 (Go) 운전자 현재 LevelDebug 수준 메시지만 내보내지만 LogLevel에 대한 다른 사양도 지원합니다. 자세한 학습 은 LogLevel API 설명서를 참조하세요.
예시
이 예에서는 다음 사양으로 표준 로거를 구성하는 방법을 보여줍니다.
최대 문서 길이는
25바이트입니다.로그 구성 요소는
LogComponentCommand입니다.로깅 심각도 수준은
LevelDebug입니다.
loggerOptions := options. Logger(). SetMaxDocumentLength(25). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
다음 코드는 로그 메시지를 생성하는 삽입 작업을 수행합니다.
type Item struct { Name string } coll := client.Database("db").Collection("testColl") _, err = coll.InsertOne(context.TODO(), Item{Name: "grapefruit"})
{"command":"{\"insert\": \"testColl\",\"or...","commandName":"insert","databaseName":"db","driverConnectionId":1,"message":"Command started","operationId":0,"requestId":13,"serverConnectionId":97377,"serverHost":"...","serverPort":27017,"timestamp":...} {"commandName":"insert","driverConnectionId":1,"durationMS":19,"message":"Command succeeded","operationId":0,"reply":"{\"n\": {\"$numberInt\":\"1\"},...","requestId":13,"serverConnectionId":97377,"serverHost":"...","serverPort":27017,"timestamp":...}
사용자 지정 로거 사용
표준 로깅 라이브러리가 요구 사항을 충족하지 않는 경우 사용자 지정 로거를 구현할 수 있습니다. 로깅 구성을 사용자 지정하면 로그 메시지의 내용, 형식 및 빈도를 더 효과적으로 제어할 수 있습니다.
사용자 지정 로거를 사용하려면 로거 구조체를 정의하고 구조체에 Info() 및 Error() 메서드를 구현합니다. 다음으로 LoggerOptions 인스턴스에서 SetSink() 메서드를 호출하여 로거를 Client용 LogSink로 설정합니다.
예시
이 예제에서는 사용자 지정 로거를 정의하고 구현하는 방법을 보여줍니다.
사용자 지정 로그 메시지 형식을 사용하여 Info() 및 Error() 메서드를 구현합니다.
func (logger *CustomLogger) Info(level int, msg string, _ ...any) { logger.mu.Lock() defer logger.mu.Unlock() if options.LogLevel(level+1) == options.LogLevelDebug { fmt.Fprintf(logger, "level: %d DEBUG, message: %s\n", level, msg) } else { fmt.Fprintf(logger, "level: %d INFO, message: %s\n", level, msg) } } func (logger *CustomLogger) Error(err error, msg string, _ ...any) { logger.mu.Lock() defer logger.mu.Unlock() fmt.Fprintf(logger, "error: %v, message: %s\n", err, msg) }
로거에 Writer 를 할당하고 이를 Client의 Sink 로 설정하다.
이 예시에서 로거는 LevelDebug 수준에서 명령과 연결 이벤트를 기록합니다.
buf := bytes.NewBuffer(nil) sink := &CustomLogger{Writer: buf} loggerOptions := options. Logger(). SetSink(sink). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug). SetComponentLevel(options.LogComponentConnection, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
작업을 수행합니다.
다음 코드는 로그 메시지를 생성하는 삽입 작업을 수행합니다.
type Item struct { Name string } coll := client.Database("db").Collection("testColl") _, err = coll.InsertOne(context.TODO(), Item{Name: "grapefruit"})
level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection checkout started level: 1 DEBUG, message: Connection created level: 1 DEBUG, message: Connection ready level: 1 DEBUG, message: Connection checked out level: 1 DEBUG, message: Command started level: 1 DEBUG, message: Command succeeded level: 1 DEBUG, message: Connection checked in
타사 로거 통합
Go에서는 많은 타사 로깅 패키지를 사용할 수 있습니다. 애플리케이션에서 타사 로거를 사용하려면 로거를 생성하고 이를 LoggerOptions 인스턴스에서 싱크로 할당합니다.
예시
이 예제에서는 타사 로깅 패키지인 logrus 을 애플리케이션에 통합하는 방법을 보여줍니다.
logrus 로거를 정의합니다.
다음 코드는 이러한 사양으로 logrus 로거를 생성합니다.
로거는 콘솔에 메시지를 기록합니다.
로거는
DebugLevel수준에서 메시지를 기록합니다.로거는
JSONFormatter포맷터를 사용하여 메시지 형식을 지정합니다.
myLogger := &logrus.Logger{ Out: os.Stderr, Level: logrus.DebugLevel, Formatter: &logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05", PrettyPrint: true, }, }
로거를 Sink 로 Client의 설정합니다.
다음 코드 예시에서는 LevelDebug 수준에서 명령을 기록하도록 로거를 구성합니다.
sink := logrusr.New(myLogger).GetSink() // Sets options when configuring the logrus logger loggerOptions := options. Logger(). SetSink(sink). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
작업을 수행합니다.
다음 코드는 로그 메시지를 생성하는 몇 가지 CRUD 작업을 수행합니다.
type Item struct { Name string } coll := client.Database("db").Collection("testColl") docs := []any{ Item{Name: "starfruit"}, Item{Name: "kiwi"}, Item{Name: "cantaloupe"}, } _, err = coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } _, err = coll.DeleteOne(context.TODO(), Item{Name: "kiwi"}) if err != nil { panic(err) }
{ "command": "{\"insert\": \"testColl\", ...}", "commandName": "insert", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "insert", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" } { "command": "{\"delete\": \"testColl\", ...}", "commandName": "delete", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "delete", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" }
팁
로깅 패키지
타사 로깅 패키지에 대한 자세한 내용은 해당 GitHub 리포지토리에서 확인할 수 있습니다.
이러한 로거를 통합하는 전체 코드 예제를 보려면 고 (Go) 운전자 Github 리포지토리의 로깅 테스트를 참조하세요.
추가 정보
클라이언트 옵션 설정에 대한 자세한 내용은 MongoClient 만들기 가이드를 참조하세요.
API 문서
이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.