[Basic]make_unique+파일에 로그기록/log to file

👉🏻 아래 코드는 mini_mediasever_1의 일부로직을 사용합니다.
The code below uses some of the logic from mini_mediasever_1.

👉🏻make_unique를 사용해서 파일에 로그를 기록하는 코드입니다.
This is code that logs to a file using make_unique.

✔️make_unique 는new + unique_ptr 생성자를 합친 것.
make_unique is a combination of the new + unique_ptr constructors.

✔️ unique_ptr :
한 곳만 할당가능한 포인터,소유권 이동만가능
A pointer that can be assigned to only one location, ownership can only be transferred.

✔️ make_unique 는 스마트 포인터로 자동 메모리 해제
make_unique automatically frees memory using smart pointers.

✔️ make_unique를 사용하면 Logger클래스가 소멸될 때 파일도 자동으로 닫힙니다.
If you use make_unique, the file is automatically closed when the Logger class is destroyed.

✔️ 방송중 방송이 끊긴후 파일도 닫게 해서 플레이어에서 열리지 않는 문제를 방지하기 위함입니다.
This is to prevent the file from opening in the player by closing it after the broadcast is cut off.

#include <iostream>
#include <memory>
#include <fstream>
#include <string>

class Logger {
    std::ofstream file_; //private
public:
    Logger(const std::string& filename) {
        file_.open(filename);
        file_ << "=== 로그 시작 / Log Start ===\n";
        std::cout << filename << " 파일 열림 / File Open\n";
    }

    void log(const std::string& msg) {
        file_ << msg << "\n";
        std::cout << "로그 기록 / log record: " << msg << "\n";
    }

    ~Logger() {
        file_ << "=== 로그 종료 / log exit ===\n";
        file_.close();
        std::cout << "파일 닫힘 / file close\n";
    }
};

int main() {
    {
        // 여기서 파일 열림 /  Open file here
        auto logger = std::make_unique<Logger>("app.log");
        logger->log("프로그램 시작 / Start program");
        logger->log("작업 중.../ Working...");
    } // 여기 나가면 자동으로 파일 닫힘 / The file closes automatically when you leave here

    std::cout << "main 끝/end\n";
    return 0;
}

👉🏻 컴파일 / Compiling

g++ main.cpp -o main

👉🏻실행 / Run

./main

👉🏻 결과 / result

MacBookAir make_unique % ls
main.cpp

MacBookAir make_unique % g++ main.cpp -o main

MacBookAir make_unique % ls
main		main.cpp

MacBookAir make_unique % ./main
app.log 파일 열림 / File Open
로그 기록 / log record: 프로그램 시작 / Start program
로그 기록 / log record: 작업 중.../ Working...
파일 닫힘 / file close
main 끝/end

MacBookAir make_unique % ls
app.log		main		main.cpp

MacBookAir make_unique % cat app.log
=== 로그 시작 / Log Start ===
프로그램 시작 / Start program
작업 중.../ Working...
=== 로그 종료 / log exit ===

MacBookAir make_unique % 

Leave a Reply