Poco::Logger 日志库使用示例(中)

引言

在上篇中已经介绍了Loger的使用的大体的步骤,下面将引入实际的例子在来理解


Logger例子

   /* 1.获取 root logger */
   auto &logger = Poco::Logger::root();

   /* 2.设置管道 */

   /* 2.1 创建控制台管道 */
   Poco::AutoPtr<Poco::ConsoleChannel> console_channel(new Poco::ConsoleChannel);

   /* 2.2 创建文件管道 */
   AutoPtr<FileChannel> file_channel(new FileChannel);
    file_channel->setProperty("rotation" ,"10M");   //日志文件的旋转模式
    file_channel->setProperty("archive" ,"timestamp");  //日志文件的归档模式
    file_channel->setProperty("path",switchFileName("Nut"));


   /* 2.3 创建 Formatter */
   // 关于格式化控制符的说明可以参见 PatternFormatter.h 中的描述
   Poco::AutoPtr<Poco::PatternFormatter> patternFormatter(
       new Poco::PatternFormatter("[%Y-%m-%d  %H:%M:%s] [%U(%u)] %p: %t"));

   patternFormatter->setProperty("times", "local");  // 格式化中的时间显示为本地时间

    /* 2.4 创建 SplitterChannel */
   AutoPtr<SplitterChannel> splitter_Channel(new SplitterChannel);
   splitter_Channel->addChannel(file_channel);
   splitter_Channel->addChannel(console_channel);

   /* 2.5 创建 Formatting Channel */
   Poco::AutoPtr<Poco::FormattingChannel> formattingChannel(
       new Poco::FormattingChannel(patternFormatter, splitter_Channel));

   /* 2.6 将 Formatting Channel 设置给 logger */
   Poco::Logger::root().setChannel(formattingChannel);


   /* 3.打印日志 */
   poco_error(logger, "This is an error message");

控制台输出

[2018-04-28 22:24:] [MyLogger.cpp(130)] Error: This is an error message

Log文件输出

这里写图片描述


Poco::logger 架构简析

理解logger 库的最核心一点就是看懂logger库的层次结构,这种设计方式很好的实现解耦,并且层次结构分明,非常值得学习

步骤一 生成消息

这里写图片描述

步骤二 写入logger

这里写图片描述

步骤三 导入channel

这里写图片描述

步骤四 写文件

这里写图片描述



上面只是通过简单的例子来了解和如何去使用Logger
我将在下篇中,将对Poco::logger 进行封装,讲述在集成框架中如何来使用日志。
敬请期待…

扫描二维码关注公众号,回复: 1441647 查看本文章

猜你喜欢

转载自blog.csdn.net/osean_li/article/details/80140020