# Java

{% hint style="warning" %}
본 가이드는 기존의 JAVA 애플리케이션이 칵테일 클라우드의 <mark style="color:red;">**빌드 작업을 거친 애플리케이션**</mark>을 위한 가이드입니다.
{% endhint %}

## 1.  Log Appender 설정

로그 어펜더(Log Appender)는 로깅 프레임워크나 라이브러리에서 제공하는 인터페이스로, 로그 메시지를 수집하고 처리하는 기능을 제공합니다. OpenTelemetry는 로그 브리지 API를 통해 로그 어펜더와 상호 작용하여 로그 메시지를 수집하고 OpenTelemetry의 추적 데이터와 연결합니다. 따라서 로그 어펜더는 OpenTelemetry에서 로그 데이터를 수집하여 통합하는 데 사용될 수 있습니다.

대표적인 Logger인 `logback`과 `log4j`를 통해 수집하는 방법을 소개합니다.

### 1)  logback

#### 1-1) dependency 추가

{% tabs %}
{% tab title="Maven" %}

```
<dependency>
    <groupId>io.opentelemetry.instrumentation</groupId>
    <artifactId>opentelemetry-logback-appender-1.0</artifactId>
    <version>2.0.0-alpha</version>
    <scope>runtime</scope>
</dependency>

```

{% endtab %}

{% tab title="Gradle" %}

```
runtimeOnly group: 'io.opentelemetry.instrumentation', name: 'opentelemetry-logback-appender-1.0', version: '2.0.0-alpha'
```

{% endtab %}
{% endtabs %}

#### 1-2) logback.xml 설정

```java

    ...

    <appender name="OpenTelemetry"
              class="io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender">
    </appender>

    ...
 
    <logger name="OTLP" additivity="false">
        <appender-ref ref="OpenTelemetry"/>
        <level value="INFO"/>
    </logger>


```

### 2) log4J

#### 2-1) dependency 추가

{% tabs %}
{% tab title="Maven" %}

```
<dependency>
    <groupId>io.opentelemetry.instrumentation</groupId>
    <artifactId>opentelemetry-log4j-appender-2.17</artifactId>
    <version>OPENTELEMETRY_VERSION</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>
```

{% endtab %}

{% tab title="Gradle" %}

```gradle
runtimeOnly("io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17:OPENTELEMETRY_VERSION")
```

{% endtab %}
{% endtabs %}

#### 2-2) log4j.xml 설정

```java
<Configuration status="WARN" packages="io.opentelemetry.instrumentation.log4j.appender.v2_17">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout
          pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} trace_id: %X{trace_id} span_id: %X{span_id} trace_flags: %X{trace_flags} - %msg%n"/>
    </Console>
    <OpenTelemetry name="OpenTelemetryAppender"/>
  </Appenders>
  <Loggers>
    <Root>
      <AppenderRef ref="OpenTelemetryAppender" level="All"/>
      <AppenderRef ref="Console" level="All"/>
    </Root>
  </Loggers>
</Configuration>
```

### 3) Logger 설정

```java
private static final Logger logger = LoggerFactory.getLogger("OTLP");
// OTLP라는 로거로 로깅함. 이는 변경이 가능하며
// 위 문서의 'ALL'로 설정하게 되면 console과 opentelemetry로 로깅할 수 있다.
```

## 2. SDK를 통한 이미지 생성

### 1) 빌드/파이프라인 - 빌드에서 로그를 수집할 자바 애플리케이션의  빌드 상세

### 2) "이미지 빌드작업"을 클릭하여 수정

<figure><img src="/files/aPT2Ap6xtihvpHPxsG9H" alt=""><figcaption></figcaption></figure>

### 3) 환경변수 설정과  Opentelemetry-java-instrumentation의 sdk 다운로드

<figure><img src="/files/6ePr7p6suCyyHuWjnXZA" alt=""><figcaption></figcaption></figure>

```docker
...

# Log를 Export할 필수설정
ENV OTEL_EXPORTER_OTLP_ENDPOINT=$OTEL_EXPORTER_OTLP_ENDPOINT
ENV OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=$OTEL_EXPORTER_OTLP_LOGS_ENDPOINT
ENV OTEL_EXPORTER_OTLP_LOGS_HEADERS=$OTEL_EXPORTER_OTLP_LOGS_HEADERS
ENV OTEL_LOGS_EXPORTER=$OTEL_LOGS_EXPORTER
ENV OTEL_SERVICE_NAME=$OTEL_SERVICE_NAME

# metric과 trace를 수집하지 않기 위한 none 처리
ENV OTEL_METRICS_EXPORTER=none
ENV OTEL_TRACES_EXPORTER=none


# sdk를 다운받아옵니다
RUN wget -q https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v2.0.0/opentelemetry-javaagent.jar
ENTRYPOINT ["java", "-javaagent:opentelemetry-javaagent.jar", "-jar", "app.jar"]

...
```

## 3. 컨테이너 설정

### 1) 로깅 - 애플리케이션 관리 에서 생성한 애플리케이션의 토큰 복사

<figure><img src="/files/k7c8vurg8tvl83iAPw2N" alt=""><figcaption></figcaption></figure>

### 2) 컨테이너 상세 - 설정 - 환경변수 탭에서 다음과 같이 환경변수를 설정

<figure><img src="/files/Sbf9rktYA8MZ1hJMGpMK" alt=""><figcaption></figcaption></figure>

```yaml
apiVersion: apps/v1
kind: Deployment
...
spec:
...
  template:
    spec:
      containers:
      - env:

	- name: OTEL_EXPORTER_OTLP_ENDPOINT
          value: http://cocktail-telemetry-collector.cocktail-addon:4318

        - name: OTEL_EXPORTER_OTLP_LOGS_ENDPOINT
          value: http://cocktail-telemetry-collector.cocktail-addon:4318/v1/logs

	# opelemetry protocal을 사용하는 설정
        - name: OTEL_LOGS_EXPORTER
          value: otlp
        
	# Application 이름
	- name: OTEL_SERVICE_NAME
          value: {애플리케이션 이름}
        
        # 인증을 위한 설정
        - name: OTEL_EXPORTER_OTLP_LOGS_HEADERS
          value: app_token={애플리케이션 토큰},app_name={애플리케이션 이름}        
        
        image: {java-application image}
        imagePullPolicy: Always
        ...
```

**`log-agent 서비스 주소`** : 인프라 - 클러스터 - 애드온 - 'log-agent' 클릭 후 서비스 이름 확인

( http 포트 = 4318 , grpc 포트 = 4317)

<figure><img src="/files/T9cbRUATVsnhGEcG8QXV" alt=""><figcaption></figcaption></figure>

## 4. 애플리케이션 로그 확인

### 1) 로깅 - 애플리케이션 로그 - 애플리케이션 목록에서 설정한 애플리케이션 검색

<figure><img src="/files/dac6FVRdtfEYoihSRoch" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cocktailcloud.gitbook.io/cocktail-cloud-online/log-service/application-log/app-logging/sdk/java.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
