当前位置: 首页 > article >正文

C++ 【异步日志模块和std::cout << 一样使用习惯替代性好】 使用示例,后续加上远程日志

简单 易用

使用示例

    CLogSystem::Instance().SetLogLevel( E_LOG_LEVEL::LOG_LEVEL_INFO | E_LOG_LEVEL::LOG_LEVEL_DEBUG | E_LOG_LEVEL::LOG_LEVEL_DUMP );
    CLogSystem::Instance().SetFileInfo(true, "./log.txt");

    LogDebug() << 12;
    LogInfo() << "hello, world!";
    std::string str = { 1, 2, 3, 4, 12 };
    QByteArray data;

    QDataStream out(&data, QIODevice::WriteOnly);
    out.setByteOrder(QDataStream::BigEndian);

    uint16_t u16MsgId = 0x55AA;
    uint8_t u8Length = 0x01;
    uint8_t u8Result = 0x01;

    out << u16MsgId << u8Length << u8Result;

    LogDump() << data.data();

在这里插入图片描述

公共头定义

/*
**  File name:   LogCommon.h
**  Author:      
**  Date:        2024-11-4
**  Brief:       日志系统公共头文件
**  Copyright (C) 1392019713@qq.com All rights reserved.
*/


#pragma once

#include <string>
#include <sstream>

enum E_LOG_LEVEL
{
	LOG_LEVEL_DEBUG = 1,  // 调试信息
	LOG_LEVEL_INFO = 2,   // 一般信息
	LOG_LEVEL_WARN = 4,   // 警告信息
	LOG_LEVEL_ERROR = 16,  // 错误信息
	LOG_LEVEL_DUMP = 32,   // 16进制数据
};

static const char* GetLogLevelString(int nLevel)
{
	switch (nLevel)
	{
	case LOG_LEVEL_DEBUG:
		return "DEBUG";
	case LOG_LEVEL_INFO:
		return "INFO";
	case LOG_LEVEL_WARN:
		return "WARN";
	case LOG_LEVEL_ERROR:
		return "ERROR";
	case LOG_LEVEL_DUMP:
		return "DUMP";
	default:
		return "NONE";
	}
}

**日志流类**

/*
**  File name:   LogStream.h
**  Author:      
**  Date:        2024-11-4
**  Brief:       日志流类
**  Copyright (C) 1392019713@qq.com All rights reserved.
*/

#pragma once

#include <stdint.h>
#include "LogCommon.h"
#include "LogSystem.h"
#include "LogWriter.h"
#include <string>
#include <chrono>

class CByteArray;

class CLogLocator
{
public:
	CLogLocator(const char* szFile, uint32_t nLine);

	~CLogLocator();

public:
	const char* m_szFile;
	uint32_t m_nLine;
};

class CLogStream
{
public:
	/*
	* @brief 构造函数
	* @param eLevel 日志级别
	* @param szMsg 日志内容
	* @param szFile 日志文件名
	* @param szFunc 日志函数名
	* @param nLine 日志行号
	* @Note 日志格式为 [2024-01-01 12:34:56.789] [DEBUG] [file:func:line] [pid] msg
	*/
	CLogStream(E_LOG_LEVEL eLevel, const CLogLocator& rLogLocator);

	CLogStream& operator <<(bool bArg);

	CLogStream& operator <<(char cArg);

	CLogStream& operator <<(int16_t n16Arg);

	CLogStream& operator <<(uint16_t u16Arg);

	CLogStream& operator <<(int32_t n32Arg);

	CLogStream& operator <<(uint32_t u32Arg);

	CLogStream& operator <<(int64_t n64Arg);

	CLogStream& operator <<(uint64_t u64Arg);

	CLogStream& operator <<(double dArg);

	CLogStream& operator <<(const char* szArg);

	CLogStream& operator <<(const std::string& strArg);

	~CLogStream();

private:
	std::string String2Hex(const std::string& str);

private:
	std::string m_strMsg;
	std::string m_strLogHead;
	E_LOG_LEVEL m_eLevel;
};

实现

#include "../Include/LogStream.h"

CLogLocator::CLogLocator(const char* szFile, uint32_t nLine)
{
    m_szFile = szFile;
    m_nLine = nLine;
}

CLogLocator::~CLogLocator()
{
}

//
CLogStream::CLogStream(E_LOG_LEVEL eLevel, const CLogLocator& rLogLocator)
{
    auto now = std::chrono::system_clock::now();
    std::time_t   now_time_t = std::chrono::system_clock::to_time_t(now);
    std::tm now_tm{};
    localtime_s(&now_tm, &now_time_t);
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
    char szTime[27] = { 0 };
    strftime(szTime, sizeof(szTime), "[%Y-%m-%d %H:%M:%S", &now_tm);
    snprintf(szTime + strlen(szTime), sizeof(szTime) - strlen(szTime), ".%03ld]", static_cast<long>(milliseconds.count()));

    m_strLogHead = szTime + std::string(" [") + std::string(GetLogLevelString(eLevel)) + "]";

    if (CLogSystem::Instance().IsHasFileInfo())
    {
        m_strLogHead += " [" + std::string(rLogLocator.m_szFile) +  ":" + std::to_string(rLogLocator.m_nLine) + "]";
    }

    if (CLogSystem::Instance().IsHasPid())
    {
        auto tid = std::this_thread::get_id();
        std::stringstream s;
        s << tid;
        m_strLogHead += " [" + s.str() + "]";
    }

    m_eLevel = eLevel;
}

CLogStream::~CLogStream()
{
    CByteArray byteArray;
    if (m_eLevel == E_LOG_LEVEL::LOG_LEVEL_DUMP)
    {
        std::string strLog = String2Hex(m_strMsg);
        byteArray.m_strMsg = m_strLogHead + " " + strLog + "\n";
        std::cout << strLog << '\n';
    }
    else 
    {
        byteArray.m_strMsg = m_strLogHead  + " " + m_strMsg + "\n";
        std::cout << m_strMsg << '\n';
    }
    CLogWriter::Instance().WriteLog(byteArray);
}

std::string CLogStream::String2Hex(const std::string& str)
{
    std::string strResult;
    for (size_t i = 0; i < str.size(); i++)
    {
        char szValue[4];
        memset(szValue, 0, sizeof(szValue));
        snprintf(szValue, sizeof(szValue), "%02X ", (uint8_t)str[i]);
        strResult += szValue;
    }
    return strResult;
}

CLogStream& CLogStream::operator<<(bool bArg)
{
    if (bArg)
    {
        m_strMsg += " true";
    }
    else
    {
        m_strMsg += " false";
    }
    return *this;
}

CLogStream& CLogStream::operator<<(char cArg)
{
    m_strMsg += cArg;
    return *this;
}

CLogStream& CLogStream::operator<<(int16_t n16Arg)
{
    m_strMsg += std::to_string(n16Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(uint16_t u16Arg)
{
    m_strMsg += std::to_string(u16Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(int32_t n32Arg)
{
    m_strMsg += std::to_string(n32Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(uint32_t u32Arg)
{
    m_strMsg += std::to_string(u32Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(int64_t n64Arg)
{
    m_strMsg += std::to_string(n64Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(uint64_t u64Arg)
{
    m_strMsg += std::to_string(u64Arg);
    return *this;
}

CLogStream& CLogStream::operator<<(double dArg)
{
    m_strMsg += std::to_string(dArg);
    return *this;
}

CLogStream& CLogStream::operator<<(const char* szArg)
{
    m_strMsg += szArg;
    return *this;
}

CLogStream& CLogStream::operator<<(const std::string& strArg)
{
    m_strMsg += strArg;
    return *this;
}


具体实现链接 git https://gitee.com/wyj4869/LogSystem.git


http://www.kler.cn/a/414804.html

相关文章:

  • 双十一线上服务调用链路追踪SkyWalking实战分析
  • el-tree的使用及控制全选、反选、获取选中
  • Airsim安装问题:This project was made with a different version of the Unreal Engine.
  • 【好玩的经典游戏】Docker环境下部署贪吃蛇网页小游戏(二)
  • 极狐GitLab 17.6 正式发布几十项与 DevSecOps 相关的功能【四】
  • PyTorch:神经网络的基本骨架 nn.Module的使用
  • ABAP 快速入门之 Hello World 和 ALV 列表
  • 深度学习基本单元结构与输入输出维度解析
  • C语言根据字符串变量获取/设置结构体成员值
  • c++基础开发环境vscode+mingw-w64
  • 【Oracle11g SQL详解】WHERE 子句的条件筛选及常用操作符
  • Seata使用ZooKeeper作为注册中心
  • 【面向对象的程序设计——集合框架】主要接口
  • java charAt()返回数值型 详解
  • python之Flask入门—路由参数
  • 从数据孤岛到数据协同:企业如何构建安全的数据共享生态?
  • php 导出excel 带图片
  • 基于Matlab的图像去噪算法仿真
  • 用 llama.cpp 体验 Meta 的 Llama AI 模型
  • 软件工程头歌实训作业:Junit实训入门篇
  • 一个高效的Java对象映射库Orika
  • SpringBoot 接口加密SM2非对称加密算法 国密算法 公钥加密 私钥解密
  • 使用Alpine镜像作为基础镜像的Dockerfile配置
  • 154. tweenjs相机运动动画
  • sqlmap使用过程中的每个步骤及其相关命令
  • 3D格式转换工具HOOPS Exchange如何保证不同CAD数据准确性和一致性?