当前位置: 首页 > 工具软件 > Poco > 使用案例 >

C++ 使用Poco库实现日志操作

阴永福
2023-12-01

C++ 使用Poco库实现日志操作

flyfish

日志输出到文件

#include <Poco/PatternFormatter.h>
#include <Poco/FormattingChannel.h>
#include <Poco/FileChannel.h>
#include <Poco/AutoPtr.h>
#include <Poco/Logger.h>
#include <Poco/ConsoleChannel.h>

#define logger_handle   (Poco::Logger::get("logger"))
namespace MyLogger
{

	void init()
	{
	    Poco::AutoPtr<Poco::PatternFormatter> pattern_formatter (new Poco::PatternFormatter("%L%Y-%m-%d %H:%M:%S  code:%u-%U :%q :%t"));
	    //%L将时间转换为本地时间
	
	    //写入文件
	    Poco::AutoPtr<Poco::FileChannel> file_channel(new Poco::FileChannel());
	    file_channel->setProperty("rotation" ,"20M");
	    file_channel->setProperty("archive" ,"timestamp");
	    file_channel->setProperty("path" ,"test.log");
	
	    Poco::AutoPtr<Poco::FormattingChannel> formatter_channle1(new Poco::FormattingChannel(pattern_formatter , file_channel));
	
	    Poco::Logger::root().setChannel(formatter_channle1);
	
	}


}

void test()
{
    logger_handle.setLevel(Poco::Message::PRIO_TRACE);
    poco_information(logger_handle , "hello world");
    poco_warning(logger_handle, "This is a warning");
    poco_information_f(logger_handle, "An informational message with args: %d, %d", 1, 2);

    logger_handle.trace("hello world");
    logger_handle.debug("hello world");
    logger_handle.error("hello world");
    logger_handle.fatal("hello world");
    logger_handle.warning("hello world");
    logger_handle.critical("hello world");
}

int main()
{
    MyLogger::init();
    test();
}

结果
生成文件test.log,文件内容

2021-01-01 10:17:12  code:81-/media/test/main.cpp :I :hello world
2021-01-01 10:17:12  code:82-/media/test/main.cpp :W :This is a warning
2021-01-01 10:17:12  code:83-/media/test/main.cpp :I :An informational message with args: 1, 2
2021-01-01 10:17:12  code:0- :T :hello world
2021-01-01 10:17:12  code:0- :D :hello world
2021-01-01 10:17:12  code:0- :E :hello world
2021-01-01 10:17:12  code:0- :F :hello world
2021-01-01 10:17:12  code:0- :W :hello world
2021-01-01 10:17:12  code:0- :C :hello world

Poco::PatternFormatter格式化输出

///   * %s - message source
///   * %t - message text
///   * %l - message priority level (1 .. 7)
///   * %p - message priority (Fatal, Critical, Error, Warning, Notice, Information, Debug, Trace)
///   * %q - abbreviated message priority (F, C, E, W, N, I, D, T)
///   * %P - message process identifier
///   * %T - message thread name
///   * %I - message thread identifier (numeric)
///   * %N - node or host name
///   * %U - message source file path (empty string if not set)
///	  * %O - message source file filename (empty string if not set)
///   * %u - message source line number (0 if not set)
///   * %w - message date/time abbreviated weekday (Mon, Tue, ...)
///   * %W - message date/time full weekday (Monday, Tuesday, ...)
///   * %b - message date/time abbreviated month (Jan, Feb, ...)
///   * %B - message date/time full month (January, February, ...)
///   * %d - message date/time zero-padded day of month (01 .. 31)
///   * %e - message date/time day of month (1 .. 31)
///   * %f - message date/time space-padded day of month ( 1 .. 31)
///   * %m - message date/time zero-padded month (01 .. 12)
///   * %n - message date/time month (1 .. 12)
///   * %o - message date/time space-padded month ( 1 .. 12)
///   * %y - message date/time year without century (70)
///   * %Y - message date/time year with century (1970)
///   * %H - message date/time hour (00 .. 23)
///   * %h - message date/time hour (00 .. 12)
///   * %a - message date/time am/pm
///   * %A - message date/time AM/PM
///   * %M - message date/time minute (00 .. 59)
///   * %S - message date/time second (00 .. 59)
///   * %i - message date/time millisecond (000 .. 999)
///   * %c - message date/time centisecond (0 .. 9)
///   * %F - message date/time fractional seconds/microseconds (000000 - 999999)
///   * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
///   * %Z - time zone differential in RFC format (GMT or +NNNN)
///   * %L - convert time to local time (must be specified before any date/time specifier; does not itself output anything)
///   * %E - epoch time (UTC, seconds since midnight, January 1, 1970)
///   * %v[width] - the message source (%s) but text length is padded/cropped to 'width'
///   * %[name] - the value of the message parameter with the given name
///   * %% - percent sign

Poco::FileChannel可以设置的属性

path
rotation
archive
times
compress
purgeAge
purgeCount
flush
rotateOnOpen

日志输出到控制台

上面的void init()函数改为

namespace MyLogger
{

	void init()
	{
	    Poco::AutoPtr<Poco::PatternFormatter> pattern_formatter (new Poco::PatternFormatter("%L%Y-%m-%d %H:%M:%S  code:%u-%U :%q :%t"));
	    //%L将时间转换为本地时间
	
	 Poco::AutoPtr<Poco::ConsoleChannel> console_channel(new Poco::ConsoleChannel());
	 Poco::AutoPtr<Poco::FormattingChannel> formatter_channle2(new Poco::FormattingChannel(pattern_formatter , console_channel));
	 Poco::Logger::root().setChannel(formatter_channle2);
	
	}


}

日志同时输出到文件和控制台

#include <Poco/PatternFormatter.h>
#include <Poco/FormattingChannel.h>
#include <Poco/FileChannel.h>
#include <Poco/AutoPtr.h>
#include <Poco/Logger.h>
#include <Poco/ConsoleChannel.h>
#include <Poco/SplitterChannel.h>

#define logger_handle   (Poco::Logger::get("logger"))
namespace MyLogger
{
    void init()
    {
        Poco::AutoPtr<Poco::PatternFormatter> pattern_formatter (new Poco::PatternFormatter("%L%Y-%m-%d %H:%M:%S  code:%u-%U :%q :%t"));
        //%L将时间转换为本地时间

        //写入文件
        Poco::AutoPtr<Poco::FileChannel> file_channel(new Poco::FileChannel());
        file_channel->setProperty("rotation" ,"20M");
        file_channel->setProperty("archive" ,"timestamp");
        file_channel->setProperty("path" ,"test.log");


        Poco::AutoPtr<Poco::ConsoleChannel> console_channel(new Poco::ConsoleChannel());

        Poco::AutoPtr<Poco::SplitterChannel> splitter_Channel(new Poco::SplitterChannel);
        splitter_Channel->addChannel(file_channel);
        splitter_Channel->addChannel(console_channel);

        Poco::AutoPtr<Poco::FormattingChannel> formattingChannel(new Poco::FormattingChannel(pattern_formatter, splitter_Channel));

        Poco::Logger::root().setChannel(formattingChannel);

    }

}

示例:将异常输出到日志

#include <Poco/PatternFormatter.h>
#include <Poco/FormattingChannel.h>
#include <Poco/FileChannel.h>
#include <Poco/AutoPtr.h>
#include <Poco/Logger.h>
#include <Poco/ConsoleChannel.h>
#include <Poco/SplitterChannel.h>
#include <Poco/Exception.h>
#include <string>
#include <iostream>
#include <sstream>

//...
struct ooops :  Poco::Exception
{
    const char* what() const noexcept {return "haha!";}
};

int main () {
    MyLogger::init();

    ooops e;

    try
    {
        throw e;
    }
    catch (Poco::Exception &ex)
    {
        int n=9;
        double d=10.8;
        std::ostringstream msg;
        msg << "My Poco::Exception: int:" <<n<<":double:"<<d<<":"<<ex.what();
        logger_handle.error(msg.str());

    }
    return 0;
}
 类似资料: