자바스크립트를 이용한 GraphQL Subscriptions를 위한 로그 수집 방법

GraphQL은 최신 웹 애플리케이션에서 데이터를 효율적으로 관리하기 위한 강력한 쿼리 언어입니다. GraphQL Subscriptions는 실시간 데이터 업데이트를 지원하며, 이를 통해 서버 측에서 클라이언트에게 데이터 변경을 푸시하고, 웹 소켓을 통해 양방향 통신을 제공할 수 있습니다.

이번 기사에서는 자바스크립트를 사용하여 GraphQL Subscriptions를 구현하고 실시간 로그를 수집하는 방법에 대해 알아보겠습니다.

1. GraphQL Subscriptions 구현하기

GraphQL Subscriptions를 구현하기 위해서는 GraphQL 서버와 클라이언트를 설정해야 합니다. 가장 널리 사용되는 GraphQL 서버 프레임워크 중 하나인 Apollo Server를 사용하도록 하겠습니다.

서버 사이드 설정

const { ApolloServer, gql } = require('apollo-server');
const { PubSub } = require('graphql-subscriptions');

const pubsub = new PubSub();

const typeDefs = gql`
  type Query {
    hello: String
  }

  type Subscription {
    logAdded: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello World!'
  },

  Subscription: {
    logAdded: {
      subscribe: () => pubsub.asyncIterator(['LOG_ADDED'])
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

위 코드는 단순한 GraphQL 서버를 설정하는 예시입니다. logAdded라는 이름의 Subscription을 정의하고, 클라이언트가 해당 Subscription에 구독하면 실시간으로 로그를 전송할 수 있게 됩니다.

클라이언트 사이드 설정

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';

const client = new ApolloClient({
  link: new WebSocketLink({
    uri: 'ws://localhost:4000/graphql',
    options: {
      reconnect: true
    }
  }),
  cache: new InMemoryCache()
});

const subscription = gql`
  subscription {
    logAdded
  }
`;

client.subscribe({ query: subscription }).subscribe({
  next(data) {
    console.log(data);
  }
});

위 코드는 클라이언트가 GraphQL Subscriptions에 구독하는 예시입니다. 클라이언트는 WebSocketLink를 사용하여 서버와 웹 소켓 연결을 생성하고, subscribe 함수를 사용하여 logAdded Subscription에 구독합니다. 실시간으로 수신되는 로그는 next 함수를 통해 출력됩니다.

2. 로그 수집하기

GraphQL Subscriptions를 사용하여 실시간으로 로그를 수신하는 경우, 이를 로그 파일이나 데이터베이스에 저장하기 위한 추가 작업이 필요합니다. 여기서는 간단히 로그를 콘솔에 출력하는 방법을 알아보도록 하겠습니다.

const { ApolloServer, gql } = require('apollo-server');
const { PubSub } = require('graphql-subscriptions');

const pubsub = new PubSub();

const typeDefs = gql`
  type Query {
    hello: String
  }

  type Subscription {
    logAdded: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello World!'
  },

  Subscription: {
    logAdded: {
      subscribe: () => pubsub.asyncIterator(['LOG_ADDED'])
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    {
      async serverWillStart() {
        console.log('Server is starting');
      },
      async requestDidStart() {
        console.log('A request is starting');
        return {
          async executionDidStart(requestContext) {
            return {
              async didEncounterErrors(requestContext) {
                console.error('An error occurred');
                console.error(requestContext.errors);
              }
            };
          }
        };
      }
    }
  ]
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

위 코드에서는 plugins 배열에 로그 수집을 위한 함수를 등록했습니다. serverWillStart 함수는 서버가 시작될 때 호출되며, requestDidStart 함수는 각 요청이 시작될 때 호출됩니다.

실행 중에 오류가 발생하면 didEncounterErrors 함수가 호출되며, 해당 함수에서 오류를 로그에 기록하는 작업을 수행할 수 있습니다.

결론

GraphQL Subscriptions는 웹 애플리케이션에서 실시간 데이터 업데이트를 가능하게 합니다. 이를 활용하여 로그와 같은 실시간 데이터를 수집하고 처리하는 방법에 대해 알아보았습니다.

서버와 클라이언트 설정을 통해 GraphQL Subscriptions를 구현하고, 로그 수집을 위한 코드를 추가해야 합니다. 이를 통해 웹 애플리케이션에서 발생하는 중요한 데이터를 실시간으로 모니터링하고 분석할 수 있습니다.

#GraphQL #로그수집