MongoDB Shell 스크립트에서 사용자지정 로그 항목을 쓰기 (write)수 있습니다. 사용자 지정 로그 항목은 디버깅, 오류 처리에 도움이 되며 스크립트 특정 기능을 수행할 때 경고 .
이 작업에 대하여
MongoDB Shell 사용자 지정 로그 항목에 대해 다음 메서드를 지원합니다.
log.debug()
log.error()
log.fatal()
log.info()
log.warn()
단계
1
사용자 지정 로그 항목을 작성하는 스크립트 만들기
다음 스크립트 movies
컬렉션 에 문서를 삽입하고 사용자 지정 info
로그 항목을 작성합니다. 스크립트 오류가 발생하면 대신 사용자 지정 error
로그 항목을 씁니다.
// connect-and-insert-with-log-entry.js try { db = connect( 'mongodb://localhost/myDatabase' ); db.movies.insertMany( [ { title: 'Titanic', year: 1997, genres: [ 'Drama', 'Romance' ] }, { title: 'Spirited Away', year: 2001, genres: [ 'Animation', 'Adventure', 'Family' ] }, { title: 'Casablanca', genres: [ 'Drama', 'Romance', 'War' ] } ] ) log.info('InsertData: Inserted 3 movies'); } catch (error) { log.error('Insert failed', { error: error.message }); }
스크립트 connect-and-insert-with-log-entry.js
(으)로 저장합니다.
2
스크립트 실행
connect-and-insert-with-log-entry.js
스크립트 실행 하려면 mongosh
를 사용하여 배포서버 에 연결하고 MongoDB Shell 내에서 다음 명령을 실행 .
load("connect-and-insert-with-log-entry.js")
또는 mongosh
를 시작할 때 --file
옵션을 사용하여 프로그래밍 방식으로 스크립트 실행 수 있습니다.
mongosh --file connect-and-insert-with-log-entry.js
결과
사용자 지정 로그 항목이 세션의 로그에 나타납니다.
{"t":{"$date":"2025-02-25T18:04:01.690Z"},"s":"I","c":"MONGOSH-SCRIPTS","id":1000000054,"ctx":"custom-log","msg":"InsertData: Inserted 3 movies"}
로그 세션 및 로그 메시지를 조회 방법에 대한 자세한 내용은 셸 로그 보기를 참조하세요.
스크립트 문서를 삽입했는지 확인하려면 movies
컬렉션 쿼리 .
use myDatabase db.movies.find()
출력:
[ { _id: ObjectId('67bde8c2a527c6b1341979f2'), title: 'Titanic', year: 1997, genres: [ 'Drama', 'Romance' ] }, { _id: ObjectId('67bde8c2a527c6b1341979f3'), title: 'Spirited Away', year: 2001, genres: [ 'Animation', 'Adventure', 'Family' ] }, { _id: ObjectId('67bde8c2a527c6b1341979f4'), title: 'Casablanca', genres: [ 'Drama', 'Romance', 'War' ] } ]