在上篇Window平台编译log4cpp使用方法记录 (一)中完成对下载的源码编译工作,接下来在工程中去应用该功能。
1.新建VS工程
将上篇文章生成的dll和lib文件拷贝到该工程目录里,并在工程项目属性中包含源代码下的include文件夹。
包含头文件:
链接库文件(如果未拷贝到当前工程目录,则需添加库文件目录):
2 演示
#include <stdio.h>
#include "log4cpp/Portability.hh"
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#ifdef LOG4CPP_HAVE_SYSLOG
#include "log4cpp/SyslogAppender.hh"
#endif
#include "log4cpp/Layout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"
#include "log4cpp/PropertyConfigurator.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/RollingFileAppender.hh"
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main(int argc, char* argv[])
{
log4cpp::OstreamAppender* osAppender = new log4cpp::OstreamAppender("osAppender", &cout);
log4cpp::PatternLayout* pLayOut = new log4cpp::PatternLayout();
pLayOut->setConversionPattern("%d : %p %c %x: %m%n");
osAppender->setLayout(pLayOut);
log4cpp::Category& root = log4cpp::Category::getRoot();
log4cpp::Category& infoCategory = root.getInstance("infoCategory");
infoCategory.addAppender(osAppender);
infoCategory.setPriority(log4cpp::Priority::INFO);
infoCategory.info("system isrunning");
infoCategory.warn("system has awarning");
infoCategory.error("system hasa error, can't find a file");
infoCategory.fatal("system hasa fatal error,must be shutdown");
infoCategory.info("systemshutdown,you can find some information in systemlog");
log4cpp::Category::shutdown();
return 0;
}
运行结果如下:
3 错误报警。
如果编译过程中出现 无法解析的外部符号 __imp__closesocket@4 之类的错误,则需再链接库文件时再引入ws2_32.lib,或者在头文件中加入该行: #pragma comment(lib, “ws2_32.lib”)