Ghi log file trong C++

Dùng fopen (thư viện C) thay vì ofstream. Trong Linux, hàm fopen được dùng để mở một file và trả về một con trỏ kiểu FILE*

fopen: mở file với tên và chế độ (ví dụ "r" để đọc, "w" để ghi, "a" để ghi nối thêm).

test.cpp
#include <cstdio>
#include <string>
#include <unistd.h>
#include <chrono>  // lấy thời gian chính xác đến micro‑giây hoặc nanosecond
#include <iomanip>
#include <sstream>

enum class LogLevel { INFO, WARN, ERROR, DEBUG };

void mylog(FILE* logfile, const std::string &message, LogLevel level = LogLevel::INFO) {
    if (logfile == NULL) return;

    // Lấy thời gian hiện tại với kiểu rõ ràng
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    std::time_t in_time_t = std::chrono::system_clock::to_time_t(now);

    // Lấy phần microseconds
    std::chrono::microseconds micros =
        std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()) % 1000000;

    // Format thời gian
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&in_time_t), "%d/%m/%Y %H:%M:%S")
        << "." << std::setw(6) << std::setfill('0') << micros.count();

    // PID
    pid_t pid = getpid();

    // Chuyển level thành string
    std::string levelStr;
    switch (level) {
        case LogLevel::WARN:  levelStr = "WARN";  break;
        case LogLevel::ERROR: levelStr = "ERROR"; break;
        case LogLevel::DEBUG: levelStr = "DEBUG"; break;
        case LogLevel::INFO:  levelStr = "INFO";  break;
        default:              levelStr = "UNDEF"; break;
    }

    // Ghi log
    fprintf(logfile, "[%s] [%d] [%-5s] %s\n",
            oss.str().c_str(), pid, levelStr.c_str(), message.c_str());
}

int main() {
    FILE *logfile = fopen("test.log", "a");
    if (logfile == NULL) {
        perror("Không thể mở file log");
        return 1;
    }

    mylog(logfile, "Ứng dụng bắt đầu chạy.");                       // mặc định INFO
    mylog(logfile, "Bộ nhớ gần đầy.", LogLevel::WARN);              // rõ ràng hơn
    mylog(logfile, "Không thể kết nối tới server.", LogLevel::ERROR);
    mylog(logfile, "Giá trị biến x = 42.", LogLevel::DEBUG);

    fclose(logfile);
    printf("Log đã được ghi vào test.log\n");
    return 0;
}
[root@GIGABYTEU4 test]# g++ test.cpp -o test
[root@GIGABYTEU4 test]# ./test
Log đã được ghi vào test.log
[root@GIGABYTEU4 test]# cat test.log
[06/09/2026 15:26:12.123456] [703] [INFO ] Ứng dụng bắt đầu chạy.
[06/09/2026 15:26:12.123460] [703] [WARN ] Bộ nhớ gần đầy.
[06/09/2026 15:26:12.123465] [703] [ERROR] Không thể kết nối tới server.
[06/09/2026 15:26:12.123470] [703] [DEBUG] Giá trị biến x = 42.
[root@GIGABYTEU4 test]#

Leave a Comment