Docs Menu
Docs Home
/ / /
Go 드라이버
/

로깅

이 페이지의 내용

  • 개요
  • 로깅 활성화
  • 로거 구성
  • 로그 구성 요소 및 심각도 수준
  • 예제
  • 사용자 지정 로거 사용
  • 예제
  • 타사 로거 통합
  • 예제
  • 추가 정보
  • API 문서

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

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

로깅 심각도 수준에 대해 자세히 알아보려면 메시지 로깅에 대한 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(context.TODO(), clientOptions)

LoggerOptions 객체를 만들려면 options.Logger() 메서드를 호출합니다. 다음 표에서는 LoggerOptions 유형의 속성을 설정하여 로거를 구성하는 방법을 설명합니다. 첫 번째 열은 LoggerOptions 속성을 나열하고, 두 번째 열은 속성을 설명하며, 세 번째 열은 각 속성에 해당하는 setter 메서드 및 매개 변수를 나열합니다.

속성
설명
세터 메서드
ComponentLevels

Type: map[LogComponent]LogLevel
A mapping of components to log severity levels. The driver uses the LogLevel for each LogComponent to determine if the log message is generated.

To learn more about the LogComponent and LogLevel types, see the Log Components and Severity Levels section of this guide.
SetComponentLevel()

Parameters: LogComponent, LogLevel
Sink

Type: LogSink
The logging interface that the driver uses to log messages. The LogSink type is an interface that you can implement to provide a custom sink or integrate a third-party logger for the driver's logs. If you don't set this property, the driver uses the standard logging library.

To learn more, see the Use a Custom Logger and Integrate Third-Party Loggers sections of this guide.
SetSink()

Parameter: LogSink
MaxDocumentLength

Type: uint
Default: 1000
The maximum length in bytes of each log message that the driver emits. If the message is larger than this value, the driver truncates it and appends ellipses to the partial log message.
SetMaxDocumentLength()

Parameter: 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"})

표준 로깅 라이브러리가 요구 사항을 충족하지 않는 경우 사용자 지정 로거를 구현할 수 있습니다. 로깅 구성을 사용자 지정하면 로그 메시지의 내용, 형식 및 빈도를 더 효과적으로 제어할 수 있습니다.

사용자 지정 로거를 사용하려면 로거 구조체를 정의하고 구조체에 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, _ ...interface{}) {
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, _ ...interface{}) {
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"})

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 := []interface{}{
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)
}

로깅 패키지

타사 로깅 패키지에 대한 자세한 내용은 해당 GitHub 리포지토리에서 확인할 수 있습니다.

이러한 로거를 통합하는 전체 코드 예제를 보려면 Go 드라이버 Github 리포지토리의 로깅 테스트를 참조하세요.

클라이언트 옵션 설정에 대한 자세한 내용은 연결 가이드를 참조하세요.

모니터링

로깅 외에도 애플리케이션에서 서버 선택 및 토폴로지 모니터링을 활성화할 수 있습니다. 자세한 내용은 모니터링 기본 사항 가이드를 참조하세요.

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

트랜잭션