spdlog – 꿈꾸는 개발자 https://studioys.me #개발 #일상생활 #생각 Sat, 04 Jan 2025 11:34:14 +0000 ko-KR hourly 1 https://wordpress.org/?v=6.8 https://studioys.me/wp-content/webpc-passthru.php?src=https://studioys.me/wp-content/uploads/2024/09/cropped-그림1-32x32.png&nocache=1 spdlog – 꿈꾸는 개발자 https://studioys.me 32 32 [spdlog] spdlog 사용 방법 https://studioys.me/how-to-use-spdlog-library/ https://studioys.me/how-to-use-spdlog-library/#respond Mon, 30 Sep 2024 04:07:16 +0000 https://studioys.me/?p=901 더 보기[spdlog] spdlog 사용 방법]]>

이번 포스트는 spdlog 라이브러리를 사용할 수 있는 환경을 기반으로 합니다.
[spdlog] spdlog 소스 빌드 및 참조

spdlog 라이브러리를 사용하면 다양한 형태로 로그를 남길 수 있습니다.

이번 포스팅에서는 spdlog 사용 방법 및 예시에 대해서 알아보도록 하겠습니다.

spdlog 사용 방법

Formatting

spdlog에서 Formatting은 open source formatting library인 fmt를 사용하고 있습니다.

콘솔 화면에 간단하게 로그를 남겨 보겠습니다.

#include "spdlog/spdlog.h"
  
int main()
{
    spdlog::info("Welcome to spdlog!");
    spdlog::info("Args : {}", 42);
    spdlog::info("Between {1} and {0}", "Z", 0);
    spdlog::info("Notation Formatting int: {0:d}, hex: {0:x}, oct: {0:o}, bin: {0:b}", 42);
    spdlog::info("Padding 1 : {:8d}", 5);
    spdlog::info("Padding 2 : {:08x}", 5);
    spdlog::info("{:<30}", "left aligned");
    spdlog::info("{:>30}", "right aligned");
    spdlog::info("Floating 1 : {:08.1f}", 1.23456);
    spdlog::info("Floating 2 : {:08.2f}", 1.23456);
    spdlog::info("Floating 3 : {:8.1f}", 1.23456);
    spdlog::info("Floating 4 : {:8.2f}", 1.23456);
    
    spdlog::set_pattern("%^%l: %v%$");
 
    return 0;
}
실행 결과
[2024-09-30 12:22:58.974] [info] Welcome to spdlog!
[2024-09-30 12:22:58.975] [info] Args : 42
[2024-09-30 12:22:58.975] [info] Between 0 and Z
[2024-09-30 12:22:58.975] [info] Notation Formatting int: 42, hex: 2a, oct: 52, bin: 101010
[2024-09-30 12:22:58.976] [info] Padding 1 :        5
[2024-09-30 12:22:58.976] [info] Padding 2 : 00000005
[2024-09-30 12:22:58.976] [info] left aligned
[2024-09-30 12:22:58.977] [info]                  right aligned
[2024-09-30 12:22:58.977] [info] Floating 1 : 000001.2
[2024-09-30 12:22:58.977] [info] Floating 2 : 00001.23
[2024-09-30 12:22:58.978] [info] Floating 3 :      1.2
[2024-09-30 12:22:58.978] [info] Floating 4 :     1.23

소스와 같이 아주 간단하게 로그를 남길 수 있습니다.

5번째 라인처럼 문자열을 남길 수 있고, 

6번째 ~ 7번째 라인처럼 {}, {0}, {1} 등을 통해서 값이나 변수를 출력할 수 있고,

8번째 ~ 16번째 라인처럼 다양한 formatting을 지원하고 있습니다.

출력 패턴 변경

spdlog::set_pattern 함수를 사용하여 출력 패턴을 변경할 수 있습니다. 보다 자세한 내용은 Custom Formatting 문서를 참고하시길 바랍니다.

spdlog::set_pattern(pattern_string)

// Level: 로그 형태로 출력
spdlog::set_pattern("%^%l: %v%$");

// *** [12:53:29 +09:00] [thread 17340] 로그 ** 형태로 출력
spdlog::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");

로그 레벨

spdlog는 다음과 같이 로그 레벨을 지원하며, 오른쪽으로 갈 수록 순위가 높습니다.

Trace – Debug – Info – Warning – Error – Critical

로그 레벨은 각각 다음 함수와 매칭됩니다.

함수매크로 함수
Tracespdlog::traceSPDLOG_TRACES
Debugspdlog::debugSPDLOG_DEBUG
Infospdlog::infoPDLOG_INFO
Warningspdlog::warnSPDLOG_WARN
Errorspdlog::errorSPDLOG_ERROR
Criticalspdlog::criticalSPDLOG_CRITICAL

spdlog::set_level 함수를 통해서 로그 레벨을 설정할 수 있으며, 설정한 로그 레벨을 포함하여 순위가 높은 로그 레벨만 출력합니다.

만약 다음과 같이 설정한다면 Error 보다 순위가 높은 ErrorCritical 만 출력합니다.

spdlog::set_level(spdlog::level::err);

간단하게 로그 레벨 로그를 남겨보겠습니다.

#include "spdlog/spdlog.h"
 
int main()
{
    spdlog::set_level(spdlog::level::err);
    spdlog::trace("Trace Level");
    spdlog::debug("Debug Level");
    spdlog::info("Info Level");
    spdlog::warn("Warn Level");
    spdlog::error("Error Level");
    spdlog::critical("Critical Level");
 
    return 0;
}
실행 결과

[2024-09-30 12:28:32.952] [error] Error Level
[2024-09-30 12:28:32.953] [critical] Critical Level

spdlog::set_level 함수를 사용하여 로그 레벨을 Err로 변경하자 Error ~ Critical 까지 출력되는 것을 확인할 수 있습니다.

만약, 로그를 남기고 싶지 않으면 다음과 같이 설정하면 됩니다.

spdlog::set_level(spdlog::level::off);

보통 spdlog::set_level 함수를 사용하여 Release 빌드일 경우에는 Info ~ Critical 까지, Debug 빌드일 경우에는 Trace ~ Critical까지 출력하도록 설정합니다.

매크로 방식으로 로그 남기기

함수를 사용 방식 대신에 매크로 방식으로 로그를 남길 수 있습니다.

#include "spdlog/spdlog.h"
 
#pragma comment(lib, "libspdlog_MD_2019_x86D_v1.10.0.lib")
 
int main()
{
    SPDLOG_TRACE("Trace Level");
    SPDLOG_DEBUG("Debug Level");
    SPDLOG_INFO("Info Level");
    SPDLOG_WARN("Warn Level");
    SPDLOG_ERROR("Error Level");
    SPDLOG_CRITICAL("Critical Level");
 
    return 0;
}

파일 로그 남기기

지금까지 화면에 로그를 남겼는데 파일로 로그를 남겨보겠습니다.

파일 로그도 아주 간단합니다. 헤더 파일을 추가하고, 파일 로거를 생성하고 기본 로거를 파일 로거로 지정하면 됩니다.

#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"

int main()
{
    auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic.txt");
    
    spdlog::set_default_logger(logger);
    spdlog::info("Basic File Logger");
    
    return 0;
}

최대 크기 지정

로그가 최대 크기가 넘어가면 다른 파일로 로그를 남기도록 설정할 수 있습니다.

#include "spdlog/spdlog.h"
#include "spdlog/sinks/rotating_file_sink.h"
 
int main()
{
    auto max_size = 5 * 1024 * 1024;
    auto max_files = 3;
    
    // 5MB 넘어갈 경우 파일을 생성. 3개 파일을 반복하여 사용
    auto logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", max_size, max_files);

    spdlog::set_default_logger(logger);
    spdlog::info("Rotating File Logger");
 
    return 0;
}

일자별 파일 로그 남기기 

일자별로 로그를 남기도록 설정할 수 있습니다.

#include "spdlog/spdlog.h"
#include "spdlog/sinks/daily_file_sink.h"
 
int main()
{
    auto hour = 2;
    auto min = 30;
    
    // daily_YYYY-MM-DD.txt 파일 생성 ( 새벽 2시 30분에 )
    auto logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", hour, min);
 
    spdlog::set_default_logger(logger);
    spdlog::info("Daily File Logger");
 
    return 0;
}

flush

파일 로그 생성 시 로그가 실시간으로 기록되지 않을 수 있습니다. flush가 되지 않아서 발생하는 것으로 flush 주기 및 레벨을 설정할 수 있습니다.

spdlog::flush_every(std::chrono::seconds(3));  // 3초마다 갱신
spdlog::flush_on(spdlog::level::trace);        // trace 이상 항상 갱신

Backtrace 지원

Backtrace를 지원합니다. spdlog::enable_backtrace 함수에서 지정한 크기 만큼 메모리 상으로 로그를 가지고 있다가 spdlog::dump_backtrace() 사용 시 출력합니다.

spdlog::enable_backtrace(10);

for(int i = 0; i < 100; i++)
{
  spdlog::debug("Backtrace message {}", i); // not logged yet..
}

spdlog::dump_backtrace();
실행 결과
[2024-09-30 12:57:14.187] [info] ****************** Backtrace Start ******************
[2024-09-30 12:57:14.187] [debug] Backtrace message 90
[2024-09-30 12:57:14.187] [debug] Backtrace message 91
[2024-09-30 12:57:14.187] [debug] Backtrace message 92
[2024-09-30 12:57:14.187] [debug] Backtrace message 93
[2024-09-30 12:57:14.187] [debug] Backtrace message 94
[2024-09-30 12:57:14.187] [debug] Backtrace message 95
[2024-09-30 12:57:14.187] [debug] Backtrace message 96
[2024-09-30 12:57:14.187] [debug] Backtrace message 97
[2024-09-30 12:57:14.187] [debug] Backtrace message 98
[2024-09-30 12:57:14.187] [debug] Backtrace message 99
[2024-09-30 12:57:14.191] [info] ****************** Backtrace End ********************

마치며

spdlog 사용 방법에 대해서 알아보았습니다. spdlog를 사용하면 원하는 형태로 쉽게 로그를 남길 수 있습니다. 레지스트리나 설정 파일을 사용하여 로그 레벨을 조정하도록 설정하면 원하는 시점에 로그를 확인할 수 있습니다.

간단하게 사용할 수 있으므로 로그를 남긴다면 spdlog 로그를 사용해보세요. 🙏

참고 자료 및 사이트

]]>
https://studioys.me/how-to-use-spdlog-library/feed/ 0
[spdlog] 소스 빌드 및 참조 https://studioys.me/how-to-build-and-use-the-spdlog-source/ https://studioys.me/how-to-build-and-use-the-spdlog-source/#respond Fri, 27 Sep 2024 04:31:59 +0000 https://studioys.me/?p=704 더 보기[spdlog] 소스 빌드 및 참조]]> spglog는 C++용 고속 로깅 라이브러리로 헤더 파일만 추가하여 사용할 수 있도록 설계되어 라이브러리 컴파일 없이 헤더 파일을 추가하여 사용할 수 있습니다.

이번 포스팅에서는 Visual Studio 환경에서 spdlog 소스를 다운로드 받아 헤더 버전 또는 빌드 후 라이브러리 버전으로 사용하는 방법에 대해서 알아보도록 하겠습니다.

필수 소프트웨어 설치

spdlog는 헤더 전용 라이브러리로 반드시 빌드해서 사용해야 하는 건 아니지만, 공식 페이지에서는 프로젝트 컴파일 시간을 단축하기 위해 빌드 후 사용하는 것을 권장하고 있습니다.

Visual Studio 환경에서 spdlog 라이브러리를 사용하거나 빌드하기 위해서는 다음 도구들이 설치되어 있어야 합니다.

  • CMake : CMake를 통해서 MSVC 프로젝트를 생성하여 빌드할 수 있습니다.
  • Visual Studio (MSVC 컴파일러 포함) : spdlog 사용 및 빌드 시 필요합니다. C++ 11을 지원하는 MSVC 버전 필요

MSVC 버전 별로 지원하는 C++ 버전은 아래 사이트에서 확인할 수 있습니다.
Visual Studio 버전의 Microsoft C/C++ 언어 규칙

소스 다운로드

spdlog GitHub에서 소스 코드를 다운로드 받을 수 있습니다. 저장소를 복제하거나, 압축 파일을 다운로드 후 사용합니다.

저는 저장소를 복사해서 사용하겠습니다.

git clone https://github.com/gabime/spdlog.git

헤더 전용 버전으로 사용하기

spdlog 소스 폴더 안에 있는 include 폴더를 프로젝트 폴더에 추가합니다. ( 직접 링크를 걸거나 프로젝트 폴더 내 복사 )

spdlog include 폴더 이미지
spdlog 소스폴더 하위에 include 폴더

정적 라이브러리로 사용하기

spdlog 프로젝트를 정적 라이브러리로 빌드하여 사용해보겠습니다.

CMake를 통해 Visual Studio 솔루션 생성

CMake를 사용하여 Visusl Studio 솔루션을 생성해야 합니다. spdlog 소스 폴더로 이동 후 빌드 폴더를 생성합니다.

저는 x86 및 x64 빌드 프로젝트를 생성해보겠습니다.

# spdlog 소스 폴더로 이동
cd spdlog

# x86용 build 폴더 생성
mkdir build

# x64용 build 폴더 생성
mkdir build64

명령 프롬프트에 아래 명령을 실행하여 Visual Studio 솔루션 파일을 생성합니다.

# CMake를 사용하여 빌드 프로젝트 생성하기
cmake CMakeLists.txt -B [빌드 프로젝트 경로] -G [Generator] -A [Architecture]
 
# Visual Studio 2022 - x86
cmake CMakeLists.txt -B build -G "Visual Studio 17 2022" -A Win32
 
# Visual Studio 2022 - x64
cmake CMakeLists.txt -B build64 -G "Visual Studio 17 2022" -A x64

만약 MSVC 버전을 사용한다면 [Generator] 부분을 해당 버전에 맞게 변경합니다.

# MSVC Generators 예시

Visual Studio 17 2022 = Generates Visual Studio 2022 project files.
                        Use -A option to specify architecture.
Visual Studio 16 2019 = Generates Visual Studio 2019 project files.
                        Use -A option to specify architecture.
Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                               Optional [arch] can be "Win64" or "ARM".
Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                               Optional [arch] can be "Win64" or "ARM".
Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                               Optional [arch] can be "Win64" or "ARM".
Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                               Optional [arch] can be "Win64" or "ARM".
Visual Studio 10 2010 [arch] = Deprecated. Generates Visual Studio 2010 project files.
                               Optional [arch] can be "Win64" or "IA64".
Visual Studio 9 2008 [arch] = Generates Visual Studio 2008 project files.
                              Optional [arch] can be "Win64" or "IA64".

CMake가 성공적으로 실행되면, buildbuild64 폴더 안에 spdlog.sln과 같이 Visual Studio 솔루션 파일이 생성됩니다.

build 및 build 폴더 생성
build 및 build64 폴더 생성

프로젝트 빌드 ( 정적 라이브러리 생성 )

정적 라이브러리를 만들어 보겠습니다. 저는 아래와 같이 MSVC 플랫폼 및 구성에 맞게 총 8개의 정적 라이브러리를 만들어서 사용하고 있습니다.

구분x86x64
MT – Debuglibspdlog_MT_2022_x86D_v1.14.1.liblibspdlog_MT_2022_x64D_v1.14.1.lib
MT – Releaselibspdlog_MT_2022_x86_v1.14.1.liblibspdlog_MT_2022_x64_v1.14.1.lib
MD – Debuglibspdlog_MD_2022_x86D_v1.14.1.liblibspdlog_MD_2022_x64D_v1.14.1.lib
MD – Relaselibspdlog_MD_2022_x86_v1.14.1.liblibspdlog_MD_2022_x64_v1.14.1.lib

Visual Studio 2022에서 플랫폼에 맞게 build 또는 build64 폴더에 있는 솔루션 파일을 열고, 구성에 맞게 프로젝트를 빌드합니다.

출력 폴더에 정적 라이브러리가 생성된 것을 확인할 수 있습니다.

정적 라이브러리 생성

spdlog 라이브러리 참조

이제 console 프로젝트를 생성 후 spdlog 헤더 파일과 생성한 라이브러리를 사용하여 파일 로그를 남겨보겠습니다.

console 프로젝트 생성

간단하게 콘솔 애플리케이션을 만들어 spdlog를 테스트 해보겠습니다.

spdlog 헤더 파일 및 라이브러리 복사

spdlog 소스 폴더에 있는 include 폴더정적 라이브러리를 프로젝트에 맞게 솔루션 내 적절한 위치에 복사합니다.

저는 다음과 같이 솔루션 파일이 있는 위치에 include 폴더lib 폴더를 생성하였습니다.

include 및 lib 폴더 생성
헤더 파일 및 정적 라이브러리 복사

console 프로젝트에 참조 폴더 추가

프로젝트 속성 페이지에서 추가 포함 디렉터리에 spdlog 헤더 파일을 복사한 폴더 경로를 입력합니다.

프로젝트 속성 페이지에서 추가 라이브러리 디렉토리를 경로를 입력하고, 추가 종속성에 라이브러리를 추가합니다.

spdlog 추가 라이브러리 디렉토리 입력
spdlog 추가 족송성 입력

테스트

이제 다음과 같이 main 함수 작성 후 실행 시 콘솔에서 로그가 정상적으로 보인다면 헤더와 라이브러리를 정상적으로 참조한 것입니다.

#include <iostream>
#include "spdlog/spdlog.h"
  
int main()
{
    spdlog::info("Hello World!\n");
 
    return 0;
}
[2022-07-16 16:09:24.870] [info] Hello World!
실행 결과

마치며

spdlog 소스 빌드 방법에 대해서 알아보았습니다. 이제 spdlog 사용 방법에 대해서 알아보도록 하겠습니다.

참조 자료 및 관련 사이트

# 관련 포스트

]]>
https://studioys.me/how-to-build-and-use-the-spdlog-source/feed/ 0