POCO C++库学习和分析 -- 日志 (二)
2. Poco日志的实现
2.1 日志模块应该实现的业务
在讨论日志的实现之前,先来聊一下日志模块应该实现那些业务。日志的业务说简单可以很简单,就是输出记录。说复杂也复杂,来看它的复杂性:首先,日志的输出对象是不同的,有控制台输出,本地文件输出,网络文件输出,输出到系统日志等。假如是网络日志,日志库中其实还会包含网络模块,真是越来越复杂了。
第二,日志输出的格式和内容。不同用户关心的内容和喜欢的输出格式是不同的,要满足所有人的需求,就必须能够提供全面的信息,并提供选项供用户选择。
第三,日志的级别。程序的日志一定是需要动态可调的。程序日志过多,消耗资源;日志过少,无法提供足够的信息,用来定位和解决问题。
第四,日志的存储策略。日志是具有实效性的,日志保存的时间越久,信息熵越低;日志存储也是需要成本的,大量的日志会挤占硬盘空间,所以需要对日志的存储进行管理。超过一定时间的日志可以考虑删除。在磁盘资源紧张的情况下,必须考虑控制日志的大小。
第五,日志是用来查询和排除问题的。为了能够快速的定位问题,最好能够把日志按照模块输出,这就要求日志库设计的时候考虑日志模块的分类。
第六,这一点和日志的业务无关,和库的实现相关。跨平台的话,必须考虑操作系统底层API的不同。
对于日志模块的业务就讨论到这里,还是回到Poco的日志模块上。首先来看一张Poco 日志模块的类图:

2.2. Message类
下面是Message类的头文件。其定义如下:class Foundation_API Message
{
public:
enum Priority
{
PRIO_FATAL = 1, /// A fatal error. The application will most likely terminate. This is the highest priority.
PRIO_CRITICAL, /// A critical error. The application might not be able to continue running successfully.
PRIO_ERROR, /// An error. An operation did not complete successfully, but the application as a whole is not affected.
PRIO_WARNING, /// A warning. An operation completed with an unexpected result.
PRIO_NOTICE, /// A notice, which is an information with just a higher priority.
PRIO_INFORMATION, /// An informational message, usually denoting the successful completion of an operation.
PRIO_DEBUG, /// A debugging message.
PRIO_TRACE /// A tracing message. This is the lowest priority.
};
Message();
Message(const std::string& source, const std::string& text, Priority prio);
Message(const std::string& source, const std::string& text, Priority prio, const char* file, int line);
Message(const Message& msg);
Message(const Message& msg, const std::string& text);
~Message();
Message& operator = (const Message& msg);
void swap(Message& msg);
void setSource(const std::string& src);
const std::string& getSource() const;
void setText(const std::string& text);
const std::string& getText() const;
void setPriority(Priority prio);
Priority getPriority() const;
void setTime(const Timestamp& time);
const Timestamp& getTime() const;
void setThread(const std::string& thread);
const std::string& getThread() const;
void setTid(long pid);
long getTid() const;
void setPid(long pid);
long getPid() const;
void setSourceFile(const char* file);
const char* getSourceFile() const;
void setSourceLine(int line);
int getSourceLine() const;
const std::string& operator [] (const std::string& param) const;
s