programing

MongoDB가 모든 쿼리를 로깅합니다.

fastcode 2023. 3. 11. 09:32
반응형

MongoDB가 모든 쿼리를 로깅합니다.

질문은 간단하지만 기본이다...mongodb에서 "tail" 가능한 로그 파일에 모든 쿼리를 기록하려면 어떻게 해야 합니까?

시도했습니다.

  • 프로파일링 수준 설정
  • 느린 ms 매개 변수 설정 시작
  • mongod with -vv 옵션

/var/log/mongodb/mongodb.log에 현재 활성 연결 수만 계속 표시됩니다.

모든 쿼리를 기록할 수 있습니다.

$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use myDb
switched to db myDb
> db.getProfilingLevel()
0
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 1, "ok" : 1 }
> db.getProfilingLevel()
2
> db.system.profile.find().pretty()

출처 : http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/

db.setProfilingLevel(2)'이렇게 하다'

결국 이렇게 망치질을 시작해서 이 문제를 해결하게 되었습니다(망치질을 하고 못생겼죠.개발 환경용으로 동작합니다).

mongod --profile=1 --slowms=1 &

프로파일링을 활성화하고 "저속 쿼리" 임계값을 1ms로 설정하여 모든 쿼리가 "저속 쿼리"로 파일에 기록됩니다.

/var/log/mongodb/mongodb.log

이제 다음 명령을 사용하여 연속 로그 출력을 가져옵니다.

tail -f /var/log/mongodb/mongodb.log

로그의 예:

Mon Mar  4 15:02:55 [conn1] query dendro.quads query: { graph: "u:http://example.org/people" } ntoreturn:0 ntoskip:0 nscanned:6 keyUpdates:0 locks(micros) r:73163 nreturned:6 reslen:9884 88ms

★★★★★★★★★★★★★★★★★...
3의 3의 경우

$ mongo
MongoDB shell version: 3.0.2
connecting to: test
> use myDb
switched to db
> db.setLogLevel(1)

http://docs.mongodb.org/manual/reference/method/db.setLogLevel/

MongoDB 벌목하다system.profile수집.로그는 다음 위치에서 볼 수 있습니다.

db.system.profile.find()

로그 레벨(소스)에는, 다음의 3개의 로그 레벨은 다음과 같습니다.

  • 레벨 0 - 프로파일러가 꺼져 있어 데이터를 수집하지 않습니다.mongod는 항상 slowOp보다 긴 조작을 씁니다.로그에 대한 ThresholdMs 임계값.이것이 디폴트 프로파일러 레벨입니다.
  • 레벨 1-느린 동작에 대해서만 프로파일링 데이터를 수집한다.디폴트로는 저속 동작은 100밀리초 미만입니다.slowOp을 사용하여 "저속" 작업의 임계값을 수정할 수 있습니다.ThresholdMs 런타임옵션 또는 setParameter 명령어.자세한 내용은 "Specify the Threshold for Slow Operations" 섹션을 참조하십시오.
  • 레벨 2-모든 데이터베이스 작업에 대한 프로파일링 데이터를 수집합니다.

데이터베이스가 실행 중인 프로파일링 단계를 보려면

db.getProfilingLevel()

그리고 상태를 확인합니다.

db.getProfilingStatus()

프로파일링 상태를 변경하려면명령어를 사용합니다.

db.setProfilingLevel(level, milliseconds)

서 ★★★★★level과 '프로파일링 레벨'을 .millisecondsms로 하다 , 「」를 사용합니다.

db.setProfilingLevel(0)

시스템 프로파일 컬렉션에서 타임스탬프 내림차순으로 1초 이상 걸린 모든 쿼리를 검색하는 쿼리는 다음과 같습니다.

db.system.profile.find( { millis : { $gt:1000 } } ).sort( { ts : -1 } )

프로파일러 액티비티를 활성화하고 로그를 "tail" 가능한 방법으로 표시하기 위한 명령줄 도구를 만들었습니다. --> "mongotail":

$ mongotail MYDATABASE
2020-02-24 19:17:01.194 QUERY  [Company] : {"_id": ObjectId("548b164144ae122dc430376b")}. 1 returned.
2020-02-24 19:17:01.195 QUERY  [User] : {"_id": ObjectId("549048806b5d3db78cf6f654")}. 1 returned.
2020-02-24 19:17:01.196 UPDATE [Activation] : {"_id": "AB524"}, {"_id": "AB524", "code": "f2cbad0c"}. 1 updated.
2020-02-24 19:17:10.729 COUNT  [User] : {"active": {"$exists": true}, "firstName": {"$regex": "mac"}}
...

, 더 」와 )tail)는, 「실시간」에 있어서의 변경을 확인합니다.-f 수 있습니다.grep을 사용하다

다음 URL에서 매뉴얼 및 설치 절차를 참조하십시오.https://github.com/mrsarm/mongotail

(Docker에서도 실행할 수 있습니다.특히 Windows https://hub.docker.com/r/mrsarm/mongotail) 에서 실행하는 경우는,

쿼리를 mongodb 로그 파일에 기록하려면 로그 수준과 프로파일링을 모두 설정해야 합니다.다음은 예를 제시하겠습니다.

db.setLogLevel(1)
db.setProfilingLevel(2)

(https://docs.mongodb.com/manual/reference/method/db.setLogLevel) 참조).

프로파일링만 설정하면 쿼리가 파일에 기록되지 않으므로 다음에서만 얻을 수 있습니다.

db.system.profile.find().pretty()

이 「」를 사용해 되면,db.setProfilingLevel(2)

다음 명령어는 마지막으로 실행된 쿼리를 인쇄합니다.
제한(5)을 변경하여 더 적은/더 많은 쿼리를 표시할 수도 있습니다.
- 및 쿼리를 $nin - - - $ $ $ $ $ $ $ $ 。
또한투영 {'1}을(를) 하십시오.

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
} 
).limit(5).sort( { ts : -1 } ).pretty()

쿼리 투영만 있는 로그

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
},
{'query':1}
).limit(5).sort( { ts : -1 } ).pretty()

프로파일러 데이터는 파일이 아닌 DB의 컬렉션에 기록됩니다.http://docs.mongodb.org/manual/tutorial/manage-the-database-profiler/ 를 참조해 주세요.

10gen의 MMS 서비스를 이용하여 UI에서 필터링 및 정렬할 수 있는 개발 프로파일러 데이터를 제공하는 것을 추천합니다.

우아하지는 않지만 oplog는 이 목적으로 부분적으로 사용될 수 있다고 생각합니다.읽기는 기록되지만 읽기는 기록되지 않습니다.

내 말이 맞다면 복제품을 활성화해야 해이 질문에 대한 답변은 다음과 같습니다.MongoDB 컬렉션의 변경 내용을 청취하는 방법

프로파일링 수준을 2로 설정하는 것도 모든 쿼리를 기록하는 옵션입니다.

db.setProfilingLevel(2,-1)

성공했습니다! 모든 쿼리 정보를 mongod 로그 파일에 기록했습니다.

나는 mongosniff를 볼 것을 추천한다.이 툴은 원하는 모든 것을 할 수 있습니다.특히 대규모 mongo 시스템에서 발생하는 문제, 쿼리의 라우팅 방법 및 발신원지를 진단하는 데 도움이 됩니다.이는 모든 mongo 관련 통신에 대해 네트워크인터페이스를 듣는 것으로 동작하기 때문입니다.

http://docs.mongodb.org/v2.2/reference/mongosniff/

나는 시스템을 출력할 대본을 썼다.프로파일 로그인은 쿼리가 들어오면 실시간으로 이루어집니다.다른 응답에 설명된 대로 먼저 로깅을 활성화해야 합니다.Windows Subsystem for Linux를 사용하고 있는데 아직 꼬리가 작동하지 않기 때문에 이것이 필요했습니다.

https://github.com/dtruel/mongo-live-logger

db.adminCommand( { getLog: "*" } )

그리고나서

db.adminCommand( { getLog : "global" } )

이는 오래 전에 요청되었지만 여전히 도움이 될 수 있습니다.

MongoDB 프로파일러는 상한 수집 시스템에 모든 쿼리를 기록합니다.프로파일링 합니다.'데이터베이스 프로파일러' 참조

  1. mongod 인스턴스 시작--profile=2모든 쿼리를 로깅할 수 있는 옵션 또는 mongod 인스턴스가 이미 실행 중인 경우 mongoshell에서 실행db.setProfilingLevel(2)데이터베이스를 선택한 후.(검증할 수 있는 것은,db.getProfilingLevel()이 값은 반환됩니다.2)
  2. 그 후 mongodb의 tailable cursor를 사용하여 이 시스템을 tail 하는 스크립트를 작성했습니다.프로파일 컬렉션을 작성하고 엔트리를 파일에 씁니다.로그를 보려면 다음 작업을 수행하기만 하면 됩니다.tail -f ../logs/mongologs.txt이 스크립트는 백그라운드에서 시작할 수 있으며 모든 작업을 파일에 기록합니다.

시스템에 맞게 조정 가능한 커서의 코드입니다.프로파일 컬렉션은 nodejs입니다.MyDb의 모든 컬렉션에서 발생하는 쿼리와 함께 모든 작업을 기록합니다.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require('fs');
const file = '../logs/mongologs'
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'MyDb';
//Mongodb connection

MongoClient.connect(url, function (err, client) {
   assert.equal(null, err);
   const db = client.db(dbName);
   listen(db, {})
});

function listen(db, conditions) {
var filter = { ns: { $ne: 'MyDb.system.profile' } }; //filter for query
//e.g. if we need to log only insert queries, use {op:'insert'}
//e.g. if we need to log operation on only 'MyCollection' collection, use {ns: 'MyDb.MyCollection'}
//we can give a lot of filters, print and check the 'document' variable below

// set MongoDB cursor options
var cursorOptions = {
    tailable: true,
    awaitdata: true,
    numberOfRetries: -1
};

// create stream and listen
var stream = db.collection('system.profile').find(filter, cursorOptions).stream();

// call the callback
stream.on('data', function (document) {
    //this will run on every operation/query done on our database
    //print 'document' to check the keys based on which we can filter
    //delete data which we dont need in our log file

    delete document.execStats;
    delete document.keysExamined;
    //-----
    //-----

    //append the log generated in our log file which can be tailed from command line
    fs.appendFile(file, JSON.stringify(document) + '\n', function (err) {
        if (err) (console.log('err'))
    })

});

}

pymongo를 사용하여 python에서 맞춤 가능한 커서는 MyCollection을 필터링하고 삽입 작업만 수행하는 다음 코드를 참조하십시오.

import pymongo
import time
client = pymongo.MongoClient()
oplog = client.MyDb.system.profile
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()

ts = first['ts']
while True:
    cursor = oplog.find({'ts': {'$gt': ts}, 'ns': 'MyDb.MyCollection', 'op': 'insert'},
                        cursor_type=pymongo.CursorType.TAILABLE_AWAIT)
    while cursor.alive:
        for doc in cursor:
            ts = doc['ts']
            print(doc)
            print('\n')
        time.sleep(1)

참고: 맞춤 가능한 커서는 캡이 있는 컬렉션에서만 작동합니다.컬렉션에 대한 작업을 직접 기록하는 데 사용할 수 없습니다. 대신 필터를 사용합니다.'ns': 'MyDb.MyCollection'

주의: 위의 nodejs와 python 코드가 일부에게는 도움이 되지 않을 수 있다는 것을 알고 있습니다.나는 방금 참고할 수 있는 코드를 제공했습니다.

언어/드라이버 선택 Mongodb 드라이버에서 맞춤 가능한 커서의 매뉴얼을 찾으려면 이 링크를 사용합니다.

로그로타이트 후에 추가한 또 하나의 기능.

이 패키지를 사용해 모든 쿼리를 tailing 합니다(Oplog 조작 없음).https://www.npmjs.com/package/mongo-tail-queries

(면책자:이 패키지는 이 필요에 맞게 작성했습니다.)

언급URL : https://stackoverflow.com/questions/15204341/mongodb-logging-all-queries

반응형