简述

QsLog是一个轻量级的开源qt日志,可以输出qt自己的类型,有输出级别控制,并且可以运行时调整级别。

另外也是线程安全的,支持多线程。使用起来也很方便。

使用介绍

引入日志模块

如果要加入到你现有的qt项目里,只需在代码的项目文件(pro)里加入如下代码几个引入日志模块:

#引入日志模块,路径要修改为实际的路径
include(./QsLog/QsLog.pri)

代码

包含头文件,声明命名空间

#include "../QsLog/QsLog.h"
using namespace QsLogging;

日志初始化代码:

#define LOG_FILE_PATH "log/"  //日志路径

void initLog()
{
// 初始化日志机制
Logger& logger = Logger::instance();
logger.setLoggingLevel(QsLogging::TraceLevel); //指定日志级别

// 添加文件为目的地
const QString sLogPath(LOG_FILE_PATH+QString("app.log"));
DestinationPtr fileDestination(DestinationFactory::MakeFileDestination(
sLogPath, EnableLogRotation, MaxSizeBytes(10*1024), MaxOldLogCount(3)));
logger.addDestination(fileDestination);

DestinationPtr debugDestination(DestinationFactory::MakeDebugOutputDestination());
logger.addDestination(debugDestination);

// 打印日志
QLOG_FATAL() << "app start."<<sLogPath;
}

//在主程序启动时,初始化;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
initLog();

Widget w;



w.show();

return a.exec();
}

测试代码:

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);

QTimer *pTimer = new QTimer;
pTimer->setInterval(500);
connect(pTimer, &QTimer::timeout, this, [this](){

QLOG_FATAL() << "fatal msg.";
QLOG_ERROR() << "error msg.";
QLOG_WARN() << "warn msg.";
QLOG_INFO() << "info msg.";
QLOG_DEBUG() << "debug msg.";
QLOG_TRACE() << "trace msg.";


});
pTimer->start();
}

Widget::~Widget()
{
delete ui;
}

日志输出

日志输出到了指定的目录下面,会循环覆盖:

Qt日志工具--QsLog_Qt

2000-01-01 10:14:14.641 [INFO ]: operator() [ 19 ]: info  msg. 
2000-01-01 10:14:14.641 [DEBUG]: operator() [ 20 ]: debug msg.
2000-01-01 10:14:14.641 [TRACE]: operator() [ 21 ]: trace msg.
2000-01-01 10:14:15.132 [FATAL]: operator() [ 16 ]: fatal msg.
2000-01-01 10:14:15.132 [ERROR]: operator() [ 17 ]: error msg.
2000-01-01 10:14:15.132 [WARN ]: operator() [ 18 ]: warn msg.
2000-01-01 10:14:15.132 [INFO ]: operator() [ 19 ]: info msg.
2000-01-01 10:14:15.132 [DEBUG]: operator() [ 20 ]: debug msg.
2000-01-01 10:14:15.132 [TRACE]: operator() [ 21 ]: trace msg.

完整代码


Qt日志工具--QsLog_日志输出_02