AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

로깅

이 가이드에서는 드라이버를 사용하여 애플리케이션에 대한 로깅 을 구성하는 방법을 배울 수 있습니다. 로깅의 목적은 드라이버 이벤트를 기록하는 것입니다.

로거는 사용자가 지정할 수 있는 심각도 또는 상세도 수준으로 메시지를 기록합니다. 애플리케이션에서 로거를 활성화하면 높은 수준, 자세한 수준 또는 그 중간 수준에서 애플리케이션 활동에 대한 정보를 수신할 수 있습니다.

로깅 심각도 수준에 대해 자세히 학습하려면 메시지 로깅에 대한 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 메서드 및 매개 변수를 나열합니다.

속성
설명
세터 메서드

ComponentLevels

유형: map[LogComponent]LogLevel

구성 요소를 로그 심각도 수준에 매핑합니다. 드라이버는 각 LogComponent 에 대해 LogLevel 을 사용하여 로그 메시지 생성 여부를 결정합니다.

LogComponentLogLevel 유형에 대해 자세히 알아보려면 이 가이드의 로그 구성 요소 및 심각도 수준 섹션을 참조하세요.

SetComponentLevel()

매개변수: LogComponent, LogLevel

Sink

유형: LogSink

운전자 메시지를 로그 데 사용하는 로깅 인터페이스입니다. LogSink 유형은 사용자 지정 싱크를 제공하거나 드라이버 로그에 대한 타사 로거를 통합하기 위해 구현 수 있는 인터페이스입니다. 이 속성을 설정하지 않으면 드라이버는 표준 로깅 라이브러리를 사용합니다.

자세한 학습 은 이 가이드 의 사용자 지정 로거 사용타사 로거 통합 섹션을 참조하세요.

SetSink()

매개 변수: LogSink

MaxDocumentLength

유형: uint
기본값: 1000

드라이버가 내보내는 각 로그 메시지의 최대 길이(바이트)입니다. 메시지가 이 값보다 크면 드라이버는 메시지를 자르고 부분 로그 메시지에 줄임표를 추가합니다.

SetMaxDocumentLength()

매개 변수: uint

특정 파일에 로그 쓰기

기본적으로 표준 로거는 콘솔(stderr)에 메시지를 기록합니다. MONGODB_LOG_PATH 환경 변수를 stdout 또는 파일 경로로 설정하여 로깅 대상을 지정할 수 있습니다.

드라이버가 기록하는 구성 요소를 지정하려면 LogComponent 유형을 설정합니다. 다음 표에서는 LogComponent 에 대한 기본 제공 사양을 설명합니다.

설정
설명
열거형 값

LogComponentAll

모든 구성 요소에 대한 로깅 활성화

0

LogComponentCommand

명령 모니터 로깅 활성화

1

LogComponentTopology

토폴로지 로깅 활성화

2

LogComponentServerSelection

서버 선택 로깅 활성화

3

LogComponentConnection

연결 서비스 로깅 활성화

4

설정 이름이나 설정의 열거형 값을 사용하여 로그 구성 요소를 지정할 수 있습니다. 다음 코드는 명령 모니터링을 활성화하는 동일한 방법을 보여줍니다.

// 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() 메서드를 호출하여 로거를 ClientLogSink로 설정합니다.

이 예제에서는 사용자 지정 로거를 정의하고 구현하는 방법을 보여줍니다.

1
type CustomLogger struct {
io.Writer
mu sync.Mutex
}

참고

앞의 코드 예시에서는 CustomLogger 구조체에서 Mutex 유형을 사용하여 원자성 쓰기를 보장하고 경쟁 상태를 방지합니다. Mutex 를 설정하면 여러 goroutine에서 동시에 사용할 수 있는 로거가 안전해집니다.

2
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)
}
3

이 예시에서 로거는 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)
4

다음 코드는 로그 메시지를 생성하는 삽입 작업을 수행합니다.

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 을 애플리케이션에 통합하는 방법을 보여줍니다.

1

터미널에서 다음 go get 명령을 실행하여 이 예제에 필요한 logrus 패키지를 다운로드합니다.

go get github.com/bombsimon/logrusr/v4
go get github.com/sirupsen/logrus
2

다음 코드는 이러한 사양으로 logrus 로거를 생성합니다.

  • 로거는 콘솔에 메시지를 기록합니다.

  • 로거는 DebugLevel 수준에서 메시지를 기록합니다.

  • 로거는 JSONFormatter 포맷터를 사용하여 메시지 형식을 지정합니다.

myLogger := &logrus.Logger{
Out: os.Stderr,
Level: logrus.DebugLevel,
Formatter: &logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
PrettyPrint: true,
},
}
3

다음 코드 예시에서는 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)
4

다음 코드는 로그 메시지를 생성하는 몇 가지 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 문서를 참조하세요.