전체 코드는 다음과 같습니다.

    코드 12-7 Elasticsearch를 연동한 로그 관리 마이크로서비스 전체 코드

    예제 파일 : microservice_logs_elasticsearch.js

    'use strict';
    
    const cluster = require('cluster'); // cluster 모듈 로드
    const fs = require('fs');           // fs 모듈 로드
    const elasticsearch = new require('elasticsearch').Client({  // elasticsearch 인스턴스 생성
        host: '127.0.0.1:9200',
        log: 'trace'
    });
    
    class logs extends require('./server.js') {
        constructor() {
            super("logs"
                , process.argv[2] ? Number(process.argv[2]) : 9040
                , ["POST/logs"]);
    
            // writestream 생성
            this.writestream = fs.createWriteStream('./log.txt', { flags: 'a' });
    
            this.connectToDistributor("127.0.0.1", 9000, (data) => {
                console.log("Distributor Notification", data);
            });
        }
    
        onRead(socket, data) {
            const sz = new Date().toLocaleString() + '\t' + socket.remoteAddress + '\t' +
                       socket.remotePort + '\t' + JSON.stringify(data) + '\n';
            console.log(sz);
            this.writestream.write(sz);                 // 로그 파일 저장
            data.timestamp = new Date().toISOString();  // timestamp 설정
            data.params = JSON.parse(data.params);      // JSON 포맷 변환
            elasticsearch.index({
                index: 'microservice',                  // index
                type: 'logs',                           // type
                body: data
            });
        }
    }
    
    if (cluster.isMaster) { // 자식 프로세스 실행
        cluster.fork();
    
        // Exit 이벤트가 발생하면 새로운 자식 프로세스 실행
        cluster.on('exit', (worker, code, signal) => {
            console.log(`worker ${worker.process.pid} died`);
            cluster.fork();
        });
    } else {
        new logs();
    }

    웹 브라우저에서 상품 조회 API http://127.0.0.1:8000/goods를 호출해 로그가 정상적으로 저장되는지 확인합니다. 이제 Elasticsearch에 로그가 저장되었습니다. elasticsearch > logs 폴더를 보면 생성된 로그가 들어 있습니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.