C/C++记录执行程序日志的使用

       作为一枚程序员好几年了,一直都没有自己的博客,感觉蛮遗憾的。很多知识点,都是当时使用才去了解,查资料,这样很不方便,也容易忘记。下了好大决心,才想着写一些自己的博客,来记录平时的一些容易忘的知识点,经验,和一些走过的坑,以后可以查阅,警醒。

Easyloggingpp的使用

       对于有开发经验的程序员来说,记录程序执行日志是一件必不可少的事情。通过查看和分析日志信息,不仅可以有效地帮助我们调试程序,而且当程序正式发布运行之后,更是可以帮助我们快速、准确地定位问题。以前由于经常使用QT,所以使用都是QT自带的日志系统。这几天偶然发现了一个开源日志库Easylogging++,使用之后,感觉非常简单,而又轻量,还能兼顾性能,实是一种开发编码的利器。

        Easylogging++项目在GitHub的开源地址:https://github.com/easylogging/easyloggingpp

        GitHub上给出了一个简单示例代码:

#include "easylogging++.h"

INITIALIZE_EASYLOGGINGPP

int main(int argv, char* argc[]) {
   LOG(INFO) << "My first info log using default logger";
   return 0;
}

       这几行代码的作用:

  • 包含easylogging++.h头文件
  • 使用宏 INITIALIZE_EASYLOGGINGPP 初始化
  • 使用宏 LOG(INFO) 开始日志记录

        还可以通过自定义来设置日志的格式:

#include "easylogging++.h"

INITIALIZE_EASYLOGGINGPP

int main(int argc, char** argv)
{
    el::Configurations conf("my_log.conf");
    el::Loggers::reconfigureAllLoggers(conf);

    LOG(TRACE)   << "***** trace log  *****";
    LOG(DEBUG)   << "***** debug log  *****";
    LOG(ERROR)   << "***** error log  *****";
    LOG(WARNING) << "***** warning log  *****";
    LOG(INFO)    << "***** info log  *****";

    system("pause");
    return 0;
}

        其中配置文件 my_log.conf 的内容如下:

* GLOBAL:
    ENABLED                 =   true
    TO_FILE                 =   true
    TO_STANDARD_OUTPUT      =   true
    FORMAT                  =   "[%level | %datetime] | %msg"
    FILENAME                =   "log\\log_%datetime{%Y%M%d}.log"
    MILLISECONDS_WIDTH      =   3
    PERFORMANCE_TRACKING    =   false
    MAX_LOG_FILE_SIZE       =   1048576
    LOG_FLUSH_THRESHOLD     =   0
    
* TRACE:
    FILENAME                =   "log\\trace_log_%datetime{%Y%M%d}.log"
    
* DEBUG:
    FILENAME                =   "log\\debug_log_%datetime{%Y%M%d}.log"
    
* FATAL:
    ENABLED                 =   false
    
* ERROR:
    FILENAME                =   "log\\error_log_%datetime{%Y%M%d}.log"
    
* WARNING:
    FILENAME                =   "log\\warning_log_%datetime{%Y%M%d}.log"
    
* INFO:
    FILENAME                =   "log\\info_log_%datetime{%Y%M%d}.log"
    
* VERBOSE:
    ENABLED                 =   false

      效果:

C/C++记录执行程序日志的使用_第1张图片

QtMessageHandler的使用

        一般情况下,在调试程序的时候,我们会输出一些调试信息,便于程序跟踪。

        例如:

int main(int argc, char **argv) 
{ 
    QApplication app(argc, argv); // 打印信息 
    qDebug("This is a debug message."); 
    qWarning("This is a warning message."); 
    qCritical("This is a critical message."); 
    qFatal("This is a fatal message."); ... 
    return app.exec(); 
}

        不过,这只能发送到控制台,或者调试器。。要写入日志文件的话,就需要我们自定义了。

       例如:

//设置本地日志目录,以及日志名称
QString LogHandler::getLogFilePath(QtMsgType type)
{
	QString fileName = ""; 
	switch (type)
	{
	case QtDebugMsg:
		fileName = QString("debug.log");
		break;
	case QtInfoMsg:
		fileName = QString("info.log");
		break;
	case WyDetailMsg:
		fileName = QString("detail.log");
		break;
	default:
		fileName = QString("error.log");
		break;
	}

	QString strFilePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
	strFilePath += "/logfile/";
	QDir dir;
	if (!dir.exists(strFilePath))
		dir.mkdir(strFilePath);

	strFilePath += QDateTime::currentDateTime().toString("MMdd_");
	strFilePath += fileName;

	return strFilePath;
}

//自定义消息处理程序
void    LogHandler::messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
	static QMutex mutex;//设置锁,多线程使用
	mutex.lock();
	QString strFilePath = getLogFilePath(type);

	QString strType = "";
	switch (type)
	{
	case QtInfoMsg:
		strType = QString("Info:");
		break;
	case QtDebugMsg:
		strType = QString("Debug:");
		break;
	case QtWarningMsg:
		strType = QString("Warning:");
		break;
	case QtCriticalMsg:
		strType = QString("Critical:");
		break;
	case QtFatalMsg:
		strType = QString("Fatal:");
		break;
	default:
		strType = QString("Debug:");
		break;
	}
	QString date_time	 = QDateTime::currentDateTime().toString("MM-dd hh:mm:ss.") + QTime::currentTime().toString("zzz");
	QString current_date = QString("[%1]: ").arg(date_time);
	QString message		 = QString("%1 %2 %3").arg(current_date).arg(strType).arg(msg);

        //写入日志文件
	QFile file(strFilePath);
	if(file.open(QIODevice::WriteOnly | QIODevice::Append))
	{
		QTextStream text_stream(&file);
		if(msg.isEmpty())
			text_stream << "\r\n";
		else
			text_stream << message << "\r\n";
		file.flush();
		file.close();
	}

	mutex.unlock();
}

      接着需要在main函数中安装日志log处理函数:

qInstallMessageHandler(messageHandler);

       效果:

C/C++记录执行程序日志的使用_第2张图片

结语:

         在目前开源的C++日志库中,并没有一个在使用份额上占绝对优势的,像log4cplus和glog,这两个库都比较成熟了,而且网上教程也很多。不过我都没怎么使用过这俩个库,就不多做介绍了。第一次写博客,也参考了一些其他文章,就先这样了,有人看的话,多多担待。

你可能感兴趣的:(工具)