c++编译使用log4cplus

news2024/9/28 15:27:25

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、log4cplus是什么?
  • 二、使用步骤
    • 1.下载源代码
    • 2.开始配置
      • 1.配置介绍
      • 2.开始编译
    • 3.cmake引用
    • 4.示例
  • 总结


前言

C++很强大,但是仍然有很多不尽如人意的地方,比如打印日志方面就没有java的log4j那种信手拈来,自然而然地东西。目前官方没有推出这个东西,只能借助第三方开源项目实现,或者干脆自己实现。但是,今天我们说一说一个很强大地日志库log4cplus在c++项目中地使用。


一、log4cplus是什么?

看名字就明白了,为c++开发地日志库。接下来引用开发者的话:

log4cplus is a simple to use C++ logging API providing thread–safe, flexible, and arbitrarily granular control over log management and configuration. It is modeled after the Java log4j API.

二、使用步骤

1.下载源代码

这个地方需要注意地是现在master是3.x版本了,这个版本基于C++ 20以后,使用C++ 11会直接编译报错。如果你是C++ 11的话请在分支里找到2.x的版本(包括2.0.x和2.1.x)。

由于这两个版本编译上没有显著区别,今天就以2.0.x版本为基础讲一下log4cplus的编译使用。

log4cplus下载地址

git clone https://gitee.com/anold/log4cplus.git -b 2.0.x

这里克隆完了还不能拿来直接用,还需要同步下引用的子项目。直接克隆的代码很小,包括子项目之后的大概是不到60MB,请留一下项目大小。

在这里插入图片描述
进入到项目目录后执行以下命令:

git submodule update --init --recursive

一定要确认所有操作成功了才行,否则编译时一定失败。

2.开始配置

1.配置介绍

log4cplus配置项众多,可以根据需要来配置。

请注意,不同的版本分支配置项可能不一样,请注意区分。这个东西在配置文件里可以看到,这里不细说了。

Configure script options
--enable-debugging
This option is disabled by default. This option mainly affects GCC builds but it also has some limited effect on non-GCC builds. It turns on debugging information generation, undefines NDEBUG symbol and adds -fstack-check (GCC).

--enable-warnings
This option is enabled by default. It adds platform / compiler dependent warning options to compiler command line.

--enable-so-version
This option is enabled by default. It enables SO version decoration on resulting library file, e.g., the .2.0.0 in liblog4cplus-1.2.so.2.0.0.

--enable-release-version
This option is enabled by default. It enables release version decoration on the resulting library file, e.g., the -1.2 in liblog4cplus-1.2.so.2.0.0.

--enable-symbols-visibility-options
This option is enabled by default. It enables use of compiler and platform specific option for symbols visibility. See also the Visibility page on GCC Wiki.

--enable-profiling
This option is disabled by default. This option adds profiling information generation compiler option -pg to GCC and Sun CC / Solaris Studio builds.

--enable-threads
This option is enabled by default. It turns on detection of necessary compiler and linker flags that enable POSIX threading support.

While this detection usually works well, some platforms still need help with configuration by supplying additional flags to the configure script. One of the know deficiencies is Solaris Studio on Linux. See one of the later note for details.

--with-wchar_t-support
This option is enabled by default. When enabled, additional binaries will be built, marked with U suffix in file name and compiled with -DUNICODE=1 flag. In effect, these binaries assume that log4cplus::tchar is wchar_t.

--with-working-locale
This is one of three locale and wchar_t↔char conversion related options. It is disabled by default.

It is know to work well with GCC on Linux. Other platforms generally have lesser locale support in their implementations of the C++ standard library. It is known not to work well on any BSDs.

See also docs/unicode.txt.

--with-working-c-locale
This is second of wchar_t↔char conversion related options. It is disabled by default.

It is known to work well on most Unix--like platforms, including recent Cygwin.

--with-iconv
This is third of wchar_t↔char conversion related options. It is disabled by default.

The conversion using iconv() function always uses "UTF-8" and "WCHAR_T" as source/target encoding. It is known to work well on platforms with GNU iconv. Different implementations of iconv() might not support "WCHAR_T" encoding selector.

Either system provided iconv() or library provided libiconv() are detected and accepted. Also both SUSv3 and GNU iconv() function signatures are accepted.

--with-qt
This option is disabled by default. It enables compilation of a separate shared library (liblog4cplusqt4debugappender) that implements Qt4DebugAppender. It requires Qt4 and pkg-config to be installed.

--enable-tests
This option is enabled by default. It enables compilation of test executables.

--enable-unit-tests
This option is disabled by default. It enables compilation of unit tests along their units. These unit tests then can be executed through unit_tests test executable that is built during compilation.

主要包括调试,so版本号支持,宽字符支持和本地化等。如果看不懂英文就维持原样。

2.开始编译

编译方法原作者已经给出了,这里着重说一下LInux上的编译。

这里还是建议安装到/usr/local;一方面,因为/usr本身包含很多操作系统预装的应用,相比来说/usr/local基本上空空如也,管理起来方便。另一方面,也是为了以后使用pkgconfig查找方便,这个后面再说。

./configure --prefix=/usr/local --enable-so-version=yes --enable-release-version=yes \
--enable-threads=yes

配置好之后使用下面的命令:

make -j6 && sudo make install

安装好之后会在/usr/local下面找到,重点是/usr/local/lib/pkgconfig/log4cplus.pc,一会配置要用到这个文件。

3.cmake引用

这里选用的是cmake,不为了别的就是因为简单。这里需要先通过cmake找到pkgconf这个包管理器,再通过pkgconf进一步定位log4cplus这个最终需要的包。
请看配置:

cmake_minimum_required(VERSION 3.10)
project(log_4_cplus)

set(CMAKE_CXX_STANDARD 11)
find_package(PkgConfig REQUIRED)
if (PKG_CONFIG_FOUND)
	message(STATUS "PkgConfig Found")
	pkg_search_module(
			log4cplus
			REQUIRED
			log4cplus
			IMPORTED_TARGET
	)
	if (TARGET PkgConfig::log4cplus)
		message(STATUS "log4cplus Found")
		add_executable(log_4_cplus main.cpp)
		target_link_libraries(log_4_cplus PkgConfig::log4cplus)
	endif ()
endif ()

重点就是find_package(PkgConfig REQUIRED)pkg_search_module,前者找到Linux上面安装的pkgconf,后者通过pkgconf找到它管理的module,也就是log4cplus。

这个时候你就可以使用log4cplus了。下面列出几个简单的例子,其它的用法可以看下开发者的tests或wiki。

4.示例

简单实用1:

#include <iostream>
#include <iomanip>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/initializer.h>

using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;

void printTest(log4cplus::Logger const &logger) {
    LOG4CPLUS_INFO(logger,
                   LOG4CPLUS_TEXT("This is")
                           << LOG4CPLUS_TEXT(" a reall")
                           << LOG4CPLUS_TEXT("y long message.") << std::endl
                           << LOG4CPLUS_TEXT("Just testing it out") << std::endl
                           << LOG4CPLUS_TEXT("What do you think?"));
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a bool: ") << true);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a char: ")
            << LOG4CPLUS_TEXT('x'));
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a short: ")
            << static_cast<short>(-100));
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a unsigned short: ")
            << static_cast<unsigned short>(100));
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a int: ") << 1000);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a unsigned int: ") << 1000U);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a long(hex): ")
            << std::hex << 100000000L);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a unsigned long: ")
            << static_cast<unsigned long>(100000000U));
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a float: ") << 1.2345f);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a double: ")
            << std::setprecision(15)
            << 1.2345234234);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("This is a long double: ")
            << std::setprecision(15)
            << 123452342342.342L);
}

int main(){
    log4cplus::Initializer initializer;
    log4cplus::BasicConfigurator config;
    config.configure(logger);
    log4cplus::Logger logger = log4cplus::Logger::getInstance(
            LOG4CPLUS_TEXT("main"));
	printTest();
	return 0;
}

简单实用2:

#include <iostream>
#include <iomanip>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/initializer.h>

using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;

//带时间格式的日志
void time_format_test() {
    log4cplus::tchar const fmtstr[] =
            LOG4CPLUS_TEXT("%s, %Q%%q%q %%Q %%q=%%%q%%;%%q, %%Q=%Q");
    std::cout << "Entering main()..." << std::endl;
    log4cplus::Initializer initializer;
    try {
        Time time;
        log4cplus::tstring str;

        time = now();
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << LOG4CPLUS_TEXT ("now: ") << str << std::endl;

        time = time_from_parts(0, 7);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 17);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 123);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 1234);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 12345);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 123456);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;

        time = time_from_parts(0, 0);
        str = getFormattedTime(fmtstr, time);
        log4cplus::tcout << str << std::endl;
    }
    catch (std::exception const &e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Exception..." << std::endl;
    }

    std::cout << "Exiting main()..." << std::endl;
}

int main(){
	time_format_test();
	return 0;
}


总结

1、蛮简单的,倒是log4cplus的使用有很多需要研究的地方

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1130256.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

postgresql|数据库|序列Sequence的创建和管理

前言&#xff1a; Sequence也是postgresql数据库里的一种对象&#xff0c;其属性如同索引一样&#xff0c;但通常Sequence是配合主键来工作的&#xff0c;这一点不同于MySQL&#xff0c;MySQL的主键自增仅仅是主键的属性做一个更改&#xff0c;而postgresql的主键自增是需要序…

windows协议详解之-RPC/SMB/LDAP/LSA/SAM域控协议关系

如果你在windows域控环境中&#xff0c;例如企业的网络中开启wireshark抓包&#xff0c;你一定会遇到一大堆各种各样的协议。不同于互联网服务&#xff08;大多基于HTTP&#xff09;&#xff0c;为了实现域控中各种各样的服务&#xff0c;windows的域控环境中采用了非常多的协议…

【Pytorch】Pytorch学习笔记02 - 单变量时间序列 LSTM

目录 说明简单神经网络LSTM原理Pytorch LSTM生成数据初始化前向传播方法训练模型自动化模型构建 总结参考文献 说明 这篇文章主要介绍如何使用PyTorch的API构建一个单变量时间序列 LSTM。文章首先介绍了LSTM&#xff0c;解释了它们在时间序列数据中的简单性和有效性。然后&…

Unity - 导出的FBX模型,无法将 vector4 保存在 uv 中(使用 Unity Mesh 保存即可)

文章目录 目的问题解决方案验证保存为 Unity Mesh 结果 - OK保存为 *.obj 文件结果 - not OK&#xff0c;但是可以 DIY importer注意References 目的 备忘&#xff0c;便于日后自己索引 问题 为了学习了解大厂项目的效果&#xff1a; 上周为了将 王者荣耀的 杨玉环 的某个皮肤…

GEE图表——利用NOAA气象数据绘制气温预测图

简介 气象预测是通过气象数据和模型对未来某一时间和地点的天气情况进行预测。 具体步骤如下&#xff1a; 1. 数据采集&#xff1a;从气象观测站、卫星等获取气象数据&#xff0c;包括气压、水汽、风速、温度、降雨、云量等。 2. 数据清洗&#xff1a;对采集到的数据进行质…

模拟计算器编程教程,中文编程开发语言工具编程实例

模拟计算器编程教程&#xff0c;中文编程开发语言工具编程实例 中文编程系统化教程&#xff0c;不需英语基础。学习链接 ​​​​​​https://edu.csdn.net/course/detail/39036 课程安排&#xff1a;初级1 1 初级概述 2 熟悉构件取值赋值 3 折叠式菜单滑动面板编程 4 自定…

前端(二十三)——轮询和长轮询

&#x1f62b;博主&#xff1a;小猫娃来啦 &#x1f62b;文章核心&#xff1a;实现客户端与服务器实时通信的技术手段 文章目录 前言轮询技术轮询的概念轮询的实现原理轮询的优缺点轮询的使用场景 长轮询技术长轮询的概念长轮询的实现原理长轮询的优缺点长轮询的使用场景 轮询与…

2 第一个Go程序

概述 在上一节的内容中&#xff0c;我们介绍了Go的前世今生&#xff0c;包括&#xff1a;Go的诞生、发展历程、特性和应用领域。从本节开始&#xff0c;我们将正式学习Go语言。Go语言是一种编译型语言&#xff0c;也就是说&#xff0c;Go语言在运行之前需要先进行编译&#xff…

JVM | 命令行诊断与调优 jhsdb jmap jstat jps

目录 jmap 查看堆使用情况 查看类列表&#xff0c;包含实例数、占用内存大小 生成jvm的堆转储快照dump文件 jstat 查看gc的信息&#xff0c;查看gc的次数&#xff0c;及时间 查看VM内存中三代&#xff08;young/old/perm&#xff09;对象的使用和占用大小 查看元数据空…

Qt生成PDF报告

文章目录 一、示意图二、实现部分代码总结 一、示意图 二、实现部分代码 //! 生成测试报告 void MainWindow::createPdf(QString filename, _pdf_msg_& msg, const QMap<QString, int>& ok, const QMap<QString, int>& err) {//QDir dir;if(!dir.exis…

mac安装jdk

1、下载jdk&#xff08;我的电脑要下载arm版&#xff0c;截图不对&#xff09; Java Downloads | Oraclehttps://www.oracle.com/java/technologies/downloads/#jdk17-mac 2、双击安装

【微信小程序】实现投票功能

一、后端 1、xmlsql <select id"voteList" resultMap"BaseResultMap" >select<include refid"Base_Column_List" />from t_oa_meeting_infowhere 11<if test"state!null">and state#{state}</if><if test&…

互联网Java工程师面试题·Spring篇·第四弹

目录 6、AOP 6.1、什么是 AOP&#xff1f; 6.2、什么是 Aspect&#xff1f; 6.3、什么是切点&#xff08;JoinPoint&#xff09; 6.4、什么是通知&#xff08;Advice&#xff09;&#xff1f; 6.5、有哪些类型的通知&#xff08;Advice&#xff09;&#xff1f; 6.6、指出…

06 MIT线性代数-列空间和零空间 Column space Nullspace

1. Vector space Vector space requirements vw and c v are in the space, all combs c v d w are in the space 但是“子空间”和“子集”的概念有区别&#xff0c;所有元素都在原空间之内就可称之为子集&#xff0c;但是要满足对线性运算封闭的子集才能成为子空间 中 2 …

嵌入式实时操作系统的设计与开发(消息)

消息 从概念上讲&#xff0c;消息机制和邮箱机制很类似&#xff0c;区别在于邮箱一般只能容纳一条消息&#xff0c;而消息则会包含一系列的消息。 系统定义了一个全局变量g_msgctr_header&#xff0c;通过它可以查找到任一已创建的消息容器。 每一个消息容器都可以根据其参数…

CentOS 7 安装Java环境

本文采用源码安装 1. 下载安装包 下载地址&#xff1a;jdk官网下载地址 下载linux64位tgz压缩包、官网下载需要登录oracle账号、可临时注册一个、几分钟搞定、或者查下其他方式获取安装包皆可。 2. 上传至centos7服务器 3. 安装 # tar zxvf jdk-8u381-linux-x64.tar.gz4.…

UE5 Blueprint发送http请求

一、下载插件HttpBlueprint、Json Blueprint Utilities两个插件是互相依赖的&#xff0c;启用&#xff0c;重启项目 目前两个是Beta的状态&#xff0c;如果你使用的平台支持就可以使用&#xff0c;我们的项目因为需要取Header的值&#xff0c;所有没法使用这两个插件&#xff0…

【AI视野·今日Robot 机器人论文速览 第五十九期】Fri, 20 Oct 2023

AI视野今日CS.Robotics 机器人学论文速览 Fri, 20 Oct 2023 Totally 29 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Robotics Papers CCIL: Continuity-based Data Augmentation for Corrective Imitation Learning Authors Liyiming Ke, Yunchu Zhang, Abhay D…

vue3检测是手机还是pc端,监测视图窗口变化

1.超小屏幕&#xff08;手机&#xff09; 768px以下 2.小屏设备&#xff08;平板&#xff09; 768px-992px 3.中等屏幕&#xff08;旧式电脑&#xff09; 992px-1200px 4.大屏设备&#xff08;现代电脑&#xff09; 1200px以上 <script setup name"welcome"> i…

BurpSuite安装

下载 BurpSuite 下载 Java17 下载后确定版本 java -version获取启动器 密钥生成器 破解 将下载的 BurpSuite、启动器、密钥生成器&#xff0c;放入同一个目录 打开 CMD 进入该目录 启动密钥生成器 java -jar burp-keygen-scz.jar开启新的CMD&#xff0c;进入该目录 启动…