Poco Application 框架学习(3)配置文件,日志

来源:互联网 发布:dev c 怎么写c语言 编辑:程序博客网 时间:2024/06/05 23:43

配置文件及日志:
配置文件:
配置文件初始化:
一般应用程序都会有配置文件,Application 框架也不例外。通过一下接口来读取配置文件信息。当前 Poco支持的格式有 .ini .xml .json .properties 等格式。需要注意的是 Poco Application 是根据扩展名来是别配置文件的,所以配置文件的扩展名不可以乱起。
配置文件使用第一步就是加载配置文件,使用以下函数。建议在 Application 框架的 init() 函数调用。
Util::Application::loadConfiguration(“yuhaiyang.json”, PRIO_APPLICATION );
第一个是参数是配置文件的路径及文件名。
第二个参数是等级。当前可用的等级有

enum ConfigPriority{       PRIO_APPLICATION = -100,    PRIO_DEFAULT     = 0,    PRIO_SYSTEM      = 100};

如果程序有两个配置文件a,b,a等级为PRIO_APPLICATION, 包含了同一个选项port=100,b等级为,PRIO_DEFAULT ,
包含了一个选项port=200 ,那么程序里以PRIO_APPLICATION 配置文件的为准 port 在程序里值就是 100。

获取配置文件里的值,这里使用 json 格式的配置文件配置文件内容为

{    "dbPool":    {        "comment":"这里是数据库链接池的信息",        "host":"192.168.1.120",        "port":"3306",        "user":"rd",        "password":"rd"    },    "RadiusServer" :    {        "comment":"这里包含的是RadiusServer的信息",        "name" : "RadiusServer",        "port" : "8086"    }}

配置文件的使用:
获取方法为以下几种。想获取什么类型就调用什么类型的 getXXX 方法即可。

std::string dbHost = config().getString( "dbPool.host" );    uint16_t dbPort = config().getUInt( "dbPool.port" );    uint16_t rPort = config().getUInt("RadiusServer.port");

日志:
日志初始化:
Application框架也是包含日志的。我们在使用的时候要通过以下函数对日志进行初始化。(还是最好放到 init() 方法调用)

logger().setChannel(Channel* pChannel);

在这之前我们要初始化一个 Channel。

//日志部分。

Poco::AutoPtr<Poco::Channel> channel;    {        AutoPtr<FileChannel> fileChannel(new FileChannel);        fileChannel->setProperty("path", "./test");     //指定日志路径及文件名        fileChannel->setProperty("archive", "timestamp");   //日志文件加时间戳        Poco::AutoPtr<Poco::PatternFormatter> patternFormatter(new Poco::PatternFormatter());        patternFormatter->setProperty("pattern","%Y %m %d %H:%M:%S %s(%l): %t");    //每条日志时间        channel = new Poco::FormattingChannel( patternFormatter,fileChannel );//初始化 Channel    }

然后

logger().setChannel( channel );//把 Application 的 Channel 设置为我们指定的输出

日志使用

logger().information(" this is debug information");logger().information("initialize application successful!"); //日志功能logger().warning("memory error ")logger().fatal("application occur fatal error ,exit")

支持的日志等级

    /// Valid values are:        ///   - none (turns off logging)        ///   - fatal        ///   - critical        ///   - error        ///   - warning        ///   - notice        ///   - information        ///   - debug        ///   - trace

注意:
Application 是单实例类也就是程序只能创建一次。应用程序确实只需要创建一次此对象就够了。单实例还有个好处就是我们可以在任何时候(当然是日志和配置文件初始化之后),任何位置,来获取 Application 的实例来使用配置文件以和日志。可以通过如下方式来使用。

Util::Application::instance().logger().information( "initialize application successful!" ); /* 日志功能 */std::string dbHost = Util::Application::instance().config().getString( "dbPool.host" );

Poco Application 框架基本功能介绍完毕。我们今后写程序就可以使用这个框架,快速的开发应用软件了。

0 0
原创粉丝点击