로거 만들기

Walter Mitty·2025년 4월 7일
0

개인공부

목록 보기
48/51

스레드를 누가 실행하고, 얼마나 실행되었는지 편하게 보기 위해 로거를 만들어 보려고 한다.
(실무에서는 보통 로거라는 라이브러리를 씁니당.)

package util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public abstract class MyLogger { // 추상클래스로 만들어서 직접 생성할 수 없도록 함.

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");

    public static void log(Object obj) {
        String time = LocalDateTime.now().format(formatter);
        System.out.printf("%s [%9s] %s\n", time, Thread.currentThread().getName(), obj);
    }
}
  • %s : printf 에서 %s는 문자열을 뜻한다.
    • 그리고 인자를 순서대로 사용하는데, 여기서는 현재시간, 스레드 이름, 출력할 객체 순서
    • 마지막으로 출력할 객체는 문자열이 아니라 Object 타입인데, %s를 사용하면 toString()을 사용해서 문자열료 변환 후 출력한다.
      (이렇게 하면 문자열 뿐만 아니라 객체도 출력할 수 있다.)
  • [%9s] : 무조건 9칸 유지. 9칸이 차지 않으면 왼쪽에 그 만큼 비워둔다.

간단한 Main 클래스에서 main 메서드를 만들어 출력하면,

package util;

public abstract class MyLoggerMain {

    public static void main(String[] args) {
        MyLogger.log("hello Thread");
        MyLogger.log(123);
    }
}
15:34:48.304 [     main] hello Thread
15:34:48.305 [     main] 123

사용 방법

package thread.start;

import static util.MyLogger.log;

public class ManyThreadMainV1 {
    public static void main(String[] args) {
        log("main() start");

        HelloRunnable runnable = new HelloRunnable();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        Thread thread3 = new Thread(runnable);
        thread3.start();

        log("main() end");
    }
}

출력 👇

15:43:15.608 [     main] main() start
15:43:15.610 [     main] main() end
Thread-1: run()
Thread-0: run()
Thread-2: run()

설명

  • main 스레드가 Thread-0, Thread-1, Thread-2 스레드에 일 시킴
  • 스레드 3개를 생성할 때 모두 같은 HelloRunnable 인스턴스(x001)를 스레드의 실행 작업으로 전달
  • Thread-0, Thread-1, Thread-2 는 모두 HelloRunnable 인스턴스에 있는 run() 메서드를 실행

0개의 댓글