plog

plog

轻量级且功能强大的C++日志库

plog是一个简洁高效的C++日志库,仅有约1000行代码。它支持跨平台使用,提供多种格式化器和输出器选项。plog特点包括线程安全、类型安全、Unicode支持等,且易于扩展。该库无需C++11,使用便捷,适合各类C++项目使用。

PlogC++日志库跨平台多线程Github开源项目

Plog - portable, simple and extensible C++ logging library

Pretty powerful logging library in about 1000 lines of code CI Build status CircleCI Build Status

image

Introduction

Hello log!

Plog is a C++ logging library that is designed to be as simple, small and flexible as possible. It is created as an alternative to existing large libraries and provides some unique features as CSV log format and wide string support.

Here is a minimal hello log sample:

#include <plog/Log.h> // Step1: include the headers #include "plog/Initializers/RollingFileInitializer.h" int main() { plog::init(plog::debug, "Hello.txt"); // Step2: initialize the logger // Step3: write log messages using a special macro // There are several log macros, use the macro you liked the most PLOGD << "Hello log!"; // short macro PLOG_DEBUG << "Hello log!"; // long macro PLOG(plog::debug) << "Hello log!"; // function-style macro // Also you can use LOG_XXX macro but it may clash with other logging libraries LOGD << "Hello log!"; // short macro LOG_DEBUG << "Hello log!"; // long macro LOG(plog::debug) << "Hello log!"; // function-style macro return 0; }

And its output:

2015-05-18 23:12:43.921 DEBUG [21428] [main@13] Hello log!
2015-05-18 23:12:43.968 DEBUG [21428] [main@14] Hello log!
2015-05-18 23:12:43.968 DEBUG [21428] [main@15] Hello log!

Features

Usage

To start using plog you need to make 3 simple steps.

Step 1: Adding includes

At first your project needs to know about plog. For that you have to:

  1. Add plog/include to the project include paths
  2. Add #include <plog/Log.h> into your cpp/h files (if you have precompiled headers it is a good place to add this include there)

Step 2: Initialization

The next step is to initialize the Logger. This is done by the following plog::init function:

Logger& init(Severity maxSeverity, const char/wchar_t* fileName, size_t maxFileSize = 0, int maxFiles = 0);

maxSeverity is the logger severity upper limit. All log messages have its own severity and if it is higher than the limit those messages are dropped. Plog defines the following severity levels:

enum Severity { none = 0, fatal = 1, error = 2, warning = 3, info = 4, debug = 5, verbose = 6 };

Note Messages with severity level none will always be printed.

The log format is determined automatically by fileName file extension:

The rolling behavior is controlled by maxFileSize and maxFiles parameters:

  • maxFileSize - the maximum log file size in bytes
  • maxFiles - a number of log files to keep

If one of them is zero then log rolling is disabled.

Sample:

plog::init(plog::warning, "c:\\logs\\log.csv", 1000000, 5);

Here the logger is initialized to write all messages with up to warning severity to a file in csv format. Maximum log file size is set to 1'000'000 bytes and 5 log files are kept.

Note See Custom initialization for advanced usage.

Step 3: Logging

Logging is performed with the help of special macros. A log message is constructed using stream output operators <<. Thus it is type-safe and extendable in contrast to a format string output.

Basic logging macros

This is the most used type of logging macros. They do unconditional logging.

Long macros:

PLOG_VERBOSE << "verbose"; PLOG_DEBUG << "debug"; PLOG_INFO << "info"; PLOG_WARNING << "warning"; PLOG_ERROR << "error"; PLOG_FATAL << "fatal"; PLOG_NONE << "none";

Short macros:

PLOGV << "verbose"; PLOGD << "debug"; PLOGI << "info"; PLOGW << "warning"; PLOGE << "error"; PLOGF << "fatal"; PLOGN << "none";

Function-style macros:

PLOG(severity) << "msg";

Conditional logging macros

These macros are used to do conditional logging. They accept a condition as a parameter and perform logging if the condition is true.

Long macros:

PLOG_VERBOSE_IF(cond) << "verbose"; PLOG_DEBUG_IF(cond) << "debug"; PLOG_INFO_IF(cond) << "info"; PLOG_WARNING_IF(cond) << "warning"; PLOG_ERROR_IF(cond) << "error"; PLOG_FATAL_IF(cond) << "fatal"; PLOG_NONE_IF(cond) << "none";

Short macros:

PLOGV_IF(cond) << "verbose"; PLOGD_IF(cond) << "debug"; PLOGI_IF(cond) << "info"; PLOGW_IF(cond) << "warning"; PLOGE_IF(cond) << "error"; PLOGF_IF(cond) << "fatal"; PLOGN_IF(cond) << "none";

Function-style macros:

PLOG_IF(severity, cond) << "msg";

Logger severity checker

In some cases there is a need to perform a group of actions depending on the current logger severity level. There is a special macro for that. It helps to minimize performance penalty when the logger is inactive.

IF_PLOG(severity)

Sample:

IF_PLOG(plog::debug) // we want to execute the following statements only at debug severity (and higher) { for (int i = 0; i < vec.size(); ++i) { PLOGD << "vec[" << i << "]: " << vec[i]; } }

Advanced usage

Changing severity at runtime

It is possible to set the maximum severity not only at the logger initialization time but at any time later. There are special accessor methods:

Severity Logger::getMaxSeverity() const; Logger::setMaxSeverity(Severity severity);

To get the logger use plog::get function:

Logger* get();

Sample:

plog::get()->setMaxSeverity(plog::debug);

Custom initialization

Non-typical log cases require the use of custom initialization. It is done by the following plog::init function:

Logger& init(Severity maxSeverity = none, IAppender* appender = NULL);

You have to construct an Appender parameterized with a Formatter and pass it to the plog::init function.

Note The appender lifetime should be static!

Sample:

static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender; plog::init(plog::debug, &consoleAppender);

Multiple appenders

It is possible to have multiple Appenders within a single Logger. In such case log message will be written to all of them. Use the following method to accomplish that:

Logger& Logger::addAppender(IAppender* appender);

Sample:

static plog::RollingFileAppender<plog::CsvFormatter> fileAppender("MultiAppender.csv", 8000, 3); // Create the 1st appender. static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender; // Create the 2nd appender. plog::init(plog::debug, &fileAppender).addAppender(&consoleAppender); // Initialize the logger with the both appenders.

Here the logger is initialized in the way when log messages are written to both a file and a console.

Refer to MultiAppender for a complete sample.

Multiple loggers

Multiple Loggers can be used simultaneously each with their own separate configuration. The Loggers differ by their instanceId (that is implemented as a template parameter). The default instanceId is zero. Initialization is done by the appropriate template plog::init functions:

Logger<instanceId>& init<instanceId>(...);

To get a logger use plog::get function (returns NULL if the logger is not initialized):

Logger<instanceId>* get<instanceId>();

All logging macros have their special versions that accept an instanceId parameter. These kind of macros have an underscore at the end:

PLOGD_(instanceId) << "debug"; PLOGD_IF_(instanceId, condition) << "conditional debug"; IF_PLOG_(instanceId, severity)

Sample:

enum // Define log instanceIds. Default is 0 and is omitted from this enum. { SecondLog = 1 }; int main() { plog::init(plog::debug, "MultiInstance-default.txt"); // Initialize the default logger instance. plog::init<SecondLog>(plog::debug, "MultiInstance-second.txt"); // Initialize the 2nd logger instance. // Write some messages to the default log. PLOGD << "Hello default log!"; // Write some messages to the 2nd log. PLOGD_(SecondLog) << "Hello second log!"; return 0; }

Refer to MultiInstance for a complete sample.

Share log instances across modules (exe, dll, so, dylib)

For applications that consist of several binary modules, plog instances can be local (each module has its own instance) or shared (all modules use the same instance). In case of shared you have to initialize plog only in one module, other modules will reuse that instance.

Sharing behavior is controlled by the following macros and is OS-dependent:

MacroOSBehavior
PLOG_GLOBALLinux/UnixShared
PLOG_LOCALLinux/UnixLocal
PLOG_EXPORTLinux/Unixn/a
PLOG_IMPORTLinux/Unixn/a
<default>Linux/UnixAccording to compiler settings
PLOG_GLOBALWindowsn/a
PLOG_LOCALWindowsLocal
PLOG_EXPORTWindowsShared (exports)
PLOG_IMPORTWindowsShared (imports)
<default>WindowsLocal

For sharing on Windows one module should use PLOG_EXPORT and others should use PLOG_IMPORT. Also be careful on Linux/Unix: if you don't specify sharing behavior it will be determined by compiler settings (-fvisibility).

Refer to Shared for a complete sample.

Chained loggers

A Logger can work as an Appender for another Logger. So you can chain several loggers together. This is useful for streaming log messages from a shared library to the main application binary.

Important: don't forget to specify PLOG_LOCAL sharing mode on Linux/Unix systems for this sample.

Sample:

// shared library // Function that initializes the logger in the shared library. extern "C" void EXPORT initialize(plog::Severity severity, plog::IAppender* appender) { plog::init(severity, appender); // Initialize the shared library logger. } // Function that produces a log message. extern "C" void EXPORT foo() { PLOGI << "Hello from shared lib!"; }
// main app // Functions imported from the shared library. extern "C" void initialize(plog::Severity severity, plog::IAppender* appender); extern "C" void foo(); int main() { plog::init(plog::debug, "ChainedApp.txt"); // Initialize the main logger. PLOGD << "Hello from app!"; // Write a log message. initialize(plog::debug, plog::get()); // Initialize the logger in the shared library. Note

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

下拉加载更多