ukui-interface/ 0000775 0001750 0001750 00000000000 15167726076 012434 5 ustar feng feng ukui-interface/src/ 0000775 0001750 0001750 00000000000 15167726076 013223 5 ustar feng feng ukui-interface/src/Makefile.am 0000664 0001750 0001750 00000000044 15167726076 015255 0 ustar feng feng NULL =
SUBDIRS = common \
$(NULL)
ukui-interface/src/common/ 0000775 0001750 0001750 00000000000 15167726076 014513 5 ustar feng feng ukui-interface/src/common/Makefile.am 0000664 0001750 0001750 00000002462 15167726076 016553 0 ustar feng feng #Generata binary file
lib_LTLIBRARIES = libukui-com4c.la libukui-com4cxx.la
#gcc -wall: displays all the errors and warning information when compiling
#gcc -g: add the debugging code when compiling
COMM_CFS = -Wall -g
#Add the dependent source file for libukui-com4c.la
libukui_com4c_la_SOURCES = kylin-com4c.c \
kylin-ini.c \
$(NULL)
#Additional C compiler flags
libukui_com4c_la_CFLAGS= $(COMM_CFS) \
-liniparser \
$(NULL)
#Additional link objects
libukui_com4c_la_LDFLAGS= \
$(NULL)
#Add the dependent source file for libukui-com4cxx.la
libukui_com4cxx_la_SOURCES = kylin-com4cxx.cpp \
kylin-ini.c \
$(NULL)
#Additional CXX compiler flags
libukui_com4cxx_la_CXXFLAGS= $(COMM_CFS) \
-liniparser \
$(NULL)
#Additional C compiler flags
libukui_com4cxx_la_CFLAGS= $(COMM_CFS) \
$(NULL)
#Additional link objects
libukui_com4cxx_la_LDFLAGS= \
$(NULL)
#The header files that need to be installed
include_HEADERS= \
kylin-com4c.h \
kylin-com4cxx.h \
$(NULL)
#Additional C compiler flags
libukui_gsettings_la_CFLAGS= $(COMM_CFS) \
$(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \
$(NULL)
#Additional link objects
libukui_gsettings_la_LDFLAGS= \
$(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \
$(NULL)
ukui-interface/src/common/kylin-com4c.h 0000664 0001750 0001750 00000005640 15167726076 017022 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#ifdef __cplusplus
extern "C" {
#endif
/**
* @fn kdk_get_lsbrelease
* @brief 根据lsbrelease信息的键获取值
* @param[in] key lsbrelease信息的键
* @param[out] value lsbrelease信息的值
* @param[in] value_max_len 值缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_lsbrelease(const char *key, char *value, int value_max_len);
/**
* @fn kdk_get_osrelease
* @brief 根据osrelease信息的键获取值
* @param[in] key osrelease信息的键
* @param[out] value osrelease信息的值
* @param[in] value_max_len 值缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_osrelease(const char *key, char *value, int value_max_len);
/**
* @fn kdk_get_kyinfo
* @brief 根据kyinfo的键获取值
* @param[in] session kyinfo的session值
* @param[in] key kyinfo的键
* @param[out] value kyinfo的值
* @param[in] value_max_len 值缓存区的大小
* @retval int >= 0 成功 否则失败
*/
int kdk_get_kyinfo(const char *session, const char *key, char *value, int value_max_len);
/**
* @fn kdk_get_prjcodename
* @brief 根据PROJECT_CODENAME字段的值
* @param[out] value PROJECT_CODENAME字段的值
* @param[in] value_max_len 值缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_prjcodename(char *value, int value_max_len);
/**
* @fn kdk_get_cpumodelname
* @brief 获取CPU型号
* @param[out] modelName CPU型号信息
* @param[in] max_len CPU型号缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_cpumodelname(char *modelName, int max_len);
/**
* @fn kdk_get_spechdplatform
* @brief 获取特定硬件平台信息
* @param[out] platformName 特定硬件平台信息
* @param[in] max_len 特定硬件平台缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_spechdplatform(char *platformName, int max_len);
/**
* @fn kdk_get_virtenv
* @brief 获取虚拟化环境
* @param[out] virtenv 虚拟化环境标志
* @param[in] max_len 虚拟化环境标志缓存区的大小
* @retval int > 0 成功 否则失败
*/
int kdk_get_virtenv(char *virtenv, int max_len);
#ifdef __cplusplus
}
#endif
#endif // __KYLINCOMM4C_H__
ukui-interface/src/common/kylin-ini.c 0000664 0001750 0001750 00000004625 15167726076 016571 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#include
#include
//去除尾部空白字符 包括\t \n \r
/*
标准的空白字符包括:
' ' (0x20) space (SPC) 空格符
'\t' (0x09) horizontal tab (TAB) 水平制表符
'\n' (0x0a) newline (LF) 换行符
'\v' (0x0b) vertical tab (VT) 垂直制表符
'\f' (0x0c) feed (FF) 换页符
'\r' (0x0d) carriage return (CR) 回车符
//windows \r\n linux \n mac \r
*/
char *strstripr(char *str, int containQuot)
{
if(str == NULL || *str == '\0') {
return str;
}
int len = s_strcount(str);
char *p = str + len - 1;
if (containQuot) {
while(p >= str && (isspace(*p) || *p == '\"')) {
*p = '\0'; --p;
}
} else {
while(p >= str && isspace(*p)) {
*p = '\0'; --p;
}
}
return str;
}
//去除首部空格
char *strstripl(char *str, int containQuot)
{
if(str == NULL || *str == '\0') {
return str;
}
int len = 0;
char *p = str;
if (containQuot) {
while(*p != '\0' && (isspace(*p) || *p == '\"')) {
++p; ++len;
}
} else {
while(*p != '\0' && isspace(*p)) {
++p; ++len;
}
}
size_t left_len = s_strcount(str) - len + 1;
memmove(str, p, left_len);
return str;
}
//去除首尾空格
char *strstrip(char *str, int containQuot)
{
str = strstripr(str, containQuot);
str = strstripl(str, containQuot);
return str;
}
// 安全计算字符串长度
size_t s_strcount(const char *str)
{
char dest[256] = {0};
strncpy(dest, str, sizeof(dest));
dest[sizeof(dest) - 1] = 0;
return strlen(dest);
}
ukui-interface/src/common/kylin-com4cxx.h 0000664 0001750 0001750 00000004704 15167726076 017402 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @fn KDKGetLsbRelease
* @brief 根据lsbrelease信息的键获取值
* @param[in] key lsbrelease信息的键
* @param[out] value lsbrelease信息的值
* @param[in] value_max_len 值缓存区的大小
* @retval string lsbrelease信息的值,empty 失败,否则成功
*/
string KDKGetLSBRelease(const string key);
/**
* @fn KDKGetOSRelease
* @brief 根据osrelease信息的键获取值
* @param[in] key osrelease信息的键
* @retval string osrelease信息的值,empty 失败,否则成功
*/
string KDKGetOSRelease(const string key);
/**
* @fn KDKGetKYInfo
* @brief 根据kyinfo的键获取值
* @param[in] session kyinfo的session值
* @param[in] key kyinfo的键
* @retval string kyinfo信息的键值,empty 失败,否则成功
*/
string KDKGetKYInfo(const string session, const string key);
/**
* @fn KDKGetPrjCodeName
* @brief 根据PROJECT_CODENAME字段的值
* @param None 无参
* @retval string PROJECT_CODENAME字段的值,empty 失败,否则成功
*/
string KDKGetPrjCodeName();
/**
* @fn KDKGetCpuModelName
* @brief 获取CPU型号
* @param None 无参
* @retval string CPU型号信息,empty 失败,否则成功
*/
string KDKGetCpuModelName();
/**
* @fn KDKGetSpecHDPlatform
* @brief 获取特定硬件平台信息
* @param None 无参
* @retval string 特定硬件平台信息,empty 失败,否则成功
*/
string KDKGetSpecHDPlatform();
/**
* @fn KDKGetVirtEnv
* @brief 获取虚拟化环境
* @param None 无参
* @retval string 虚拟化环境标志信息,empty 失败,否则成功
*/
string KDKGetVirtEnv();
#ifdef __cplusplus
}
#endif
#endif // __KYLINCOMM4C_H__
ukui-interface/src/common/kylin-ini.h 0000664 0001750 0001750 00000002221 15167726076 016564 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#ifdef __cplusplus
extern "C" {
#endif
// 去除尾部空格
char *strstripr(char *str, int containQuot);
// 去除头部空格
char *strstripl(char *str, int containQuot);
// 去除前后空格
char *strstrip(char *str, int containQuot);
// 安全计算字符串长度
size_t s_strcount(const char *str);
#ifdef __cplusplus
}
#endif
#endif //__KYLININI_H__
ukui-interface/src/common/kylin-com4c.c 0000664 0001750 0001750 00000016347 15167726076 017023 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#include
#include
#include
#include "kylin-ini.h"
#define LSB_RELEASE_FILE "/etc/lsb-release" /* lsb-release文件路径 */
#define OS_RELEASE_FILE "/etc/os-release" /* os-release文件路径 */
#define KYINFO_FILE "/etc/.kyinfo" /* kyinfo文件路径 */
#define CPUINFO_FILE "/proc/cpuinfo" /* cpuinfo文件路径 */
#define RELEASEFILE_LINE_MAX 256 /* 最大解析行行数 */
#define RELEASEFILE_LINE_MAX_LEN 256 /* 最大解析行长度 */
#define RELEASEFILE_KEY_MAX_LEN 128 /* 最大key长度 */
#define RELEASEFILE_VALUE_MAX_LEN 256 /* 最大value长度 预留'\0', '='*/
#define RELEASEFILE_SPLIT_EQUAL '=' /* key和value的分隔符 */
#define RELEASEFILE_SPLIT_COLON ':' /* key和value的分隔符 */
#define PROJECT_CODENAME "PROJECT_CODENAME"
#define CPUINFO_MODELNAME "model name"
// 根据key获取value,成功返回 >0 否则 返回 <= 0
static int file_get_keyvalue(const char *path, const char *key, char *value, int value_max_len, const char chSplit)
{
if (path == NULL || key == NULL || value == NULL || value_max_len <= 0) {
return -1;
}
int ret = 0;
int cnt = 0;
int key_len = 0;
int line_len = 0;
int value_len = 0;
FILE *fp = NULL;
char line_buf[RELEASEFILE_LINE_MAX_LEN] = {0};
/* 合法性判断 */
if (NULL == path || NULL == key || NULL == value || 0 >= value_max_len) {
return -1;
}
key_len = s_strcount(key);
if (0 >= key_len || RELEASEFILE_KEY_MAX_LEN < key_len) {
return -2;
}
/* 打开文件 */
fp = fopen(path, "r");
if (NULL == fp) {
return -4;
}
/* 遍历行,匹配Key */
while(NULL != fgets(line_buf, RELEASEFILE_LINE_MAX_LEN-1, fp)) {
line_len = s_strcount(line_buf);
if (line_len > key_len) {
/* 找到key */
//找到非空格的首字符
char *pStart = line_buf;
int nSplitIndex = 0;
while(pStart != (line_buf+line_len) && isspace(*pStart)) {
++pStart; ++nSplitIndex;
}
if (0 == strncmp(pStart, key, key_len)) {
pStart = pStart + key_len;
nSplitIndex = nSplitIndex + key_len;
//跳过空格字符
while(pStart != (line_buf+line_len) && isspace(*pStart)) {
++pStart; ++nSplitIndex;
}
if (pStart != (line_buf+line_len) && *pStart == chSplit) {
ret = 1;
key_len = nSplitIndex;
break;
}
}
}
memset(line_buf, 0, sizeof(line_buf));
/* 最大查找行限制 */
cnt++;
if (RELEASEFILE_LINE_MAX < cnt) {
break;
}
}
/* 关闭文件 */
fclose(fp);
fp = NULL;
/* 找到key,返回value */
memset(value, 0, value_max_len);
if (1 == ret) {
value_len = line_len - key_len - 1;
if (0 < value_len) {
if (value_len >= value_max_len) {
value_len = value_max_len - 1;
}
/* 拷贝value */
char *src_buffer = NULL;
if (key_len + 1 < RELEASEFILE_LINE_MAX_LEN) {
src_buffer = &line_buf[key_len + 1];
} else {
src_buffer = "\0";
}
snprintf(value, value_max_len, "%s", src_buffer);
/* 去掉结尾的换行符 */
strstrip(value, 1);
}
}
return ret;
}
/**
* @fn kdk_get_xdgsessiontype
* @brief 获取区分x11与wayland的环境变量值
* @retval char* !NULL 成功 否则失败
*/
char* kdk_get_xdgsessiontype()
{
return getenv("XDG_SESSION_TYPE");
}
int kdk_get_lsbrelease(const char *key, char *value, int value_max_len)
{
int nRet = -1;
if (NULL == key || NULL == value || 0 >= value_max_len)
return nRet;
dictionary *iniHandle = iniparser_load(LSB_RELEASE_FILE);
if (iniHandle) {
char sessionKey[256] = {0};
snprintf(sessionKey, 256, ":%s", key);
const char *tempValue = iniparser_getstring(iniHandle, sessionKey, "");
snprintf(value, value_max_len, "%s", tempValue);
iniparser_freedict(iniHandle);
iniHandle = NULL;
nRet = s_strcount(value);
}
return nRet;
}
int kdk_get_osrelease(const char *key, char *value, int value_max_len)
{
int nRet = -1;
if (NULL == key || NULL == value || 0 >= value_max_len)
return nRet;
dictionary *iniHandle = iniparser_load(OS_RELEASE_FILE);
if (iniHandle) {
char sessionKey[256] = {0};
snprintf(sessionKey, 256, ":%s", key);
const char *tempValue = iniparser_getstring(iniHandle, sessionKey, "");
snprintf(value, value_max_len, "%s", tempValue);
iniparser_freedict(iniHandle);
iniHandle = NULL;
nRet = s_strcount(value);
}
return nRet;
}
int kdk_get_prjcodename(char *value, int value_max_len)
{
int nResult = kdk_get_lsbrelease(PROJECT_CODENAME, value, value_max_len);
if (nResult <= 0) {
nResult = kdk_get_osrelease(PROJECT_CODENAME, value, value_max_len);
}
return nResult;
}
int kdk_get_kyinfo(const char *session, const char *key, char *value, int value_max_len)
{
int nRet = -1;
if (NULL == session || NULL == key || NULL == value || 0 >= value_max_len)
return nRet;
dictionary *iniHandle = iniparser_load(KYINFO_FILE);
if (iniHandle) {
char sessionKey[256] = {0};
snprintf(sessionKey, 256, "%s:%s", session, key);
const char *tempValue = iniparser_getstring(iniHandle, sessionKey, "");
snprintf(value, value_max_len, "%s", tempValue);
iniparser_freedict(iniHandle);
iniHandle = NULL;
nRet = s_strcount(value);
}
return nRet;
}
int kdk_get_cpumodelname(char *modelName, int max_len)
{
return file_get_keyvalue(CPUINFO_FILE, CPUINFO_MODELNAME, modelName, max_len, RELEASEFILE_SPLIT_COLON);
}
int kdk_get_spechdplatform(char *platformName, int max_len)
{
if (platformName == NULL || max_len <= 0)
return -1;
char strDefault[128] = "default";
int validLen = s_strcount(strDefault);
validLen = validLen > max_len ? max_len : validLen;
snprintf(platformName, max_len, "%s", strDefault);
return validLen;
}
int kdk_get_virtenv(char *virtenv, int max_len)
{
if (virtenv == NULL || max_len <= 0)
return -1;
int validLen = 0;
char *cmdStr = "systemd-detect-virt"; // 准备运行的命令
FILE *pipeLine = popen(cmdStr,"r"); // 建立流管道
if (!pipeLine) { // 检测流管道
return -2;
}
if (fgets(virtenv, max_len, pipeLine) != NULL) { // 获取输出
validLen = s_strcount(virtenv);
} else {
char strDefault[128] = "none";
validLen = s_strcount(strDefault);
validLen = validLen > max_len ? max_len : validLen;
snprintf(virtenv, max_len, "%s", strDefault);
}
pclose(pipeLine);
return validLen;
}
ukui-interface/src/common/kylin-com4cxx.cpp 0000664 0001750 0001750 00000015173 15167726076 017737 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#include
#include
#include
#include
#include "kylin-ini.h"
#define LSB_RELEASE_FILE "/etc/lsb-release" /* lsb-release文件路径 */
#define OS_RELEASE_FILE "/etc/os-release" /* os-release文件路径 */
#define KYINFO_FILE "/etc/.kyinfo" /* kyinfo文件路径 */
#define CPUINFO_FILE "/proc/cpuinfo" /* cpuinfo文件路径 */
#define RELEASEFILE_LINE_MAX 256 /* 最大解析行行数 */
#define RELEASEFILE_LINE_MAX_LEN 256 /* 最大解析行长度 */
#define RELEASEFILE_KEY_MAX_LEN 128 /* 最大key长度 */
#define RELEASEFILE_VALUE_MAX_LEN 256 /* 最大value长度 预留'\0', '='*/
#define RELEASEFILE_SPLIT_EQUAL '=' /* key和value的分隔符 */
#define RELEASEFILE_SPLIT_COLON ':' /* key和value的分隔符 */
#define PROJECT_CODENAME "PROJECT_CODENAME"
#define CPUINFO_MODELNAME "model name"
// 根据key获取value,成功返回 >0 否则 返回 <= 0
static int file_get_keyvalue(const char *path, const char *key, char *value, int value_max_len, const char chSplit)
{
if (path == NULL || key == NULL || value == NULL || value_max_len <= 0) {
return -1;
}
int ret = 0;
int cnt = 0;
int key_len = 0;
int line_len = 0;
int value_len = 0;
FILE *fp = NULL;
char line_buf[RELEASEFILE_LINE_MAX_LEN] = {0};
/* 合法性判断 */
if (NULL == path || NULL == key || NULL == value || 0 >= value_max_len) {
return -1;
}
key_len = s_strcount(key);
if (0 >= key_len || RELEASEFILE_KEY_MAX_LEN < key_len) {
return -2;
}
/* 打开文件 */
fp = fopen(path, "r");
if (NULL == fp) {
return -4;
}
/* 遍历行,匹配Key */
while(NULL != fgets(line_buf, RELEASEFILE_LINE_MAX_LEN-1, fp)) {
line_len = s_strcount(line_buf);
if (line_len > key_len) {
/* 找到key */
//找到非空格的首字符
char *pStart = line_buf;
int nSplitIndex = 0;
while(pStart != (line_buf+line_len) && isspace(*pStart)) {
++pStart; ++nSplitIndex;
}
if (0 == strncmp(pStart, key, key_len)) {
pStart = pStart + key_len;
nSplitIndex = nSplitIndex + key_len;
//跳过空格字符
while(pStart != (line_buf+line_len) && isspace(*pStart)) {
++pStart; ++nSplitIndex;
}
if (pStart != (line_buf+line_len) && *pStart == chSplit) {
ret = 1;
key_len = nSplitIndex;
break;
}
}
}
memset(line_buf, 0, sizeof(line_buf));
/* 最大查找行限制 */
cnt++;
if (RELEASEFILE_LINE_MAX < cnt) {
break;
}
}
/* 关闭文件 */
fclose(fp);
fp = NULL;
/* 找到key,返回value */
if (1 == ret) {
value_len = line_len - key_len - 1;
if (0 < value_len) {
if (value_len >= value_max_len) {
value_len = value_max_len-1;
}
/* 拷贝value */
char src_buffer[256] = {0};
if (key_len + 1 < RELEASEFILE_LINE_MAX_LEN) {
strncpy(src_buffer, &line_buf[key_len + 1], sizeof(src_buffer));
src_buffer[sizeof(src_buffer) - 1] = 0;
} else {
src_buffer[0] = '\0';
}
snprintf(value, value_max_len, "%s", src_buffer);
value[value_len] = '\0';
/* 去掉结尾的换行符 */
strstrip(value, 1);
} else {
value[0] = '\0';
}
}
return ret;
}
/**
* @fn KDKGetXdgSessionType
* @brief 获取区分x11与wayland的环境变量值
* @param None 无参
* @retval string xdg会话类型字符串,empty 失败,否则成功
*/
string KDKGetXdgSessionType()
{
char *strSessionType = getenv("XDG_SESSION_TYPE");
if (!strSessionType) {
return "";
}
return string(strSessionType);
}
string KDKGetLSBRelease(const string key)
{
if (key.empty()) {
return "";
}
dictionary *iniHandle = iniparser_load(LSB_RELEASE_FILE);
if (iniHandle) {
string sessionKey = ":"+key;
string strValue = "";
strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), "");
iniparser_freedict(iniHandle);
iniHandle = NULL;
return string(strValue);
}
return "";
}
string KDKGetOSRelease(const string key)
{
if (key.empty()) {
return "";
}
dictionary *iniHandle = iniparser_load(OS_RELEASE_FILE);
if (iniHandle) {
string sessionKey = ":"+key;
string strValue = "";
strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), "");
iniparser_freedict(iniHandle);
iniHandle = NULL;
return string(strValue);
}
return "";
}
string KDKGetPrjCodeName()
{
string strValue = KDKGetLSBRelease(PROJECT_CODENAME);
if (strValue.empty()) {
strValue = KDKGetOSRelease(PROJECT_CODENAME);
}
return string(strValue);
}
string KDKGetKYInfo(const string session, const string key)
{
if (session.empty() || key.empty()) {
return "";
}
dictionary *iniHandle = iniparser_load(KYINFO_FILE);
if (iniHandle) {
string sessionKey = session+":"+key;
string strValue = "";
strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), "");
iniparser_freedict(iniHandle);
iniHandle = NULL;
return string(strValue);
}
return "";
}
string KDKGetCpuModelName()
{
char strValue[256] = {0};
int nRet = file_get_keyvalue(CPUINFO_FILE, CPUINFO_MODELNAME, strValue, 256, RELEASEFILE_SPLIT_COLON);
if (nRet > 0) {
return string(strValue);
} else {
return "";
}
}
string KDKGetSpecHDPlatform()
{
string strDefaultValue = "default";
return string(strDefaultValue);
}
string KDKGetVirtEnv()
{
char virtEnv[256] = {0};
string strVirtEnv = "";
char cmdStr[] = "systemd-detect-virt"; // 准备运行的命令
FILE *pipeLine = popen(cmdStr,"r"); // 建立流管道
if (!pipeLine) { // 检测流管道
return strVirtEnv;
}
if (fgets(virtEnv, 256, pipeLine) != NULL) { // 获取输出
strVirtEnv = virtEnv;
} else {
strVirtEnv = "none";
}
pclose(pipeLine);
return string(strVirtEnv);
}
ukui-interface/src/log4qt/ 0000775 0001750 0001750 00000000000 15167726076 014435 5 ustar feng feng ukui-interface/src/log4qt/Doxyfile 0000664 0001750 0001750 00000021166 15167726064 016146 0 ustar feng feng # Doxyfile 1.5.3
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = Log4Qt
PROJECT_NUMBER =
OUTPUT_DIRECTORY = doc
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF =
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = NO
FULL_PATH_NAMES = YES
STRIP_FROM_PATH =
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
DETAILS_AT_TOP = NO
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 4
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = NO
OPTIMIZE_OUTPUT_JAVA = NO
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
DISTRIBUTE_GROUP_DOC = NO
SUBGROUPING = YES
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = YES
EXTRACT_PRIVATE = NO
EXTRACT_STATIC = NO
EXTRACT_LOCAL_CLASSES = NO
EXTRACT_LOCAL_METHODS = NO
EXTRACT_ANON_NSPACES = NO
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
HIDE_IN_BODY_DOCS = NO
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = NO
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_BY_SCOPE_NAME = NO
GENERATE_TODOLIST = YES
GENERATE_TESTLIST = YES
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_DIRECTORIES = NO
FILE_VERSION_FILTER =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text "
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
INPUT =
INPUT_ENCODING = UTF-8
FILE_PATTERNS =
RECURSIVE = YES
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS = *_p.h \
*.cpp
EXCLUDE_SYMBOLS =
EXAMPLE_PATH =
EXAMPLE_PATTERNS =
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
#---------------------------------------------------------------------------
# configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = YES
REFERENCES_RELATION = YES
REFERENCES_LINK_SOURCE = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_ALIGN_MEMBERS = YES
GENERATE_HTMLHELP = NO
HTML_DYNAMIC_SECTIONS = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
BINARY_TOC = NO
TOC_EXPAND = NO
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 4
GENERATE_TREEVIEW = NO
TREEVIEW_WIDTH = 250
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4wide
EXTRA_PACKAGES =
LATEX_HEADER =
PDF_HYPERLINKS = NO
USE_PDFLATEX = NO
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = YES
EXPAND_ONLY_PREDEF = YES
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED = Q_CORE_EXPORT=\ \
"Q_DECLARE_FLAGS(Flags, Enum)=typedef QFlags Flags; " \
Q_WS_WIN=1 \
Q_WS_MAC=1 \
Q_WS_X11=1
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
PERL_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = YES
MSCGEN_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
DOT_PATH =
DOTFILE_DIRS =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
#---------------------------------------------------------------------------
# Configuration::additions related to the search engine
#---------------------------------------------------------------------------
SEARCHENGINE = NO
ukui-interface/src/log4qt/ukui-log4qt.cpp 0000664 0001750 0001750 00000003467 15167726076 017340 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#if QT_VERSION < 0x060000
#include
#else
#include
#endif
#include "ukui-logconfigurator.h"
// 初始化ukui-log4qt库,传入application名称
int initUkuiLog4qt(QString strAppName)
{
if (strAppName.isEmpty()) {
return -1;
}
// 检查纠正名称格式 小写+'-'+数字
strAppName = strAppName.toLower();
#if QT_VERSION < 0x060000
// 非数字和小写字母以'-'代替
strAppName.replace(QRegExp("[^a-z0-9]+"), "-");
// 多个'-'以一个'-'代替
strAppName.replace(QRegExp("[-]+"), "-");
// 去掉头部的非字母串和尾部的'-''
strAppName.replace(QRegExp("(^[^a-z]+|-$)"), "");
#else
// 非数字和小写字母以'-'代替
strAppName.replace(QRegularExpression("[^a-z0-9]+"), "-");
// 多个'-'以一个'-'代替
strAppName.replace(QRegularExpression("[-]+"), "-");
// 去掉头部的非字母串和尾部的'-''
strAppName.replace(QRegularExpression("(^[^a-z]+|-$)"), "");
#endif
// 初始化log4qt配置
return UkuiLog4qtConfig::instance().init(strAppName);
}
ukui-interface/src/log4qt/ukui-logrolling.h 0000664 0001750 0001750 00000006036 15167726076 017736 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#include
#include
#include
/**
* @brief UKUI日志文件滚动清理线程类
*/
class UkuiLog4qtRolling : public QThread
{
public:
/**
* @brief 构造函数
* @param strBaseFilePath 基础日志文件路径
* @param parent 父对象指针
*/
UkuiLog4qtRolling(QString strBaseFilePath, QObject *parent = nullptr);
/**
* @brief 析构函数
*/
virtual ~UkuiLog4qtRolling();
/**
* @brief 停止线程
*/
void stop();
/**
* @brief 设置文件检查限制条件
* @param fileInfoList 要检查的文件信息列表
* @param uMaxFileCount 最大允许的文件数量(0表示不限制)
* @param uMaxFileSize 最大允许的文件总大小(0表示不限制)
*/
void setFileCheckLimit(const QFileInfoList &fileInfoList, unsigned uMaxFileCount = 0, quint64 uMaxFileSize = 0);
/**
* @brief 检查文件数量
* @param fileInfoList 要检查的文件信息列表
*/
void checkLogFilesCount(const QFileInfoList &fileInfoList);
/**
* @brief 检查文件大小
* @param fileInfoList 要检查的文件信息列表
*/
void checkLogFilesSize(const QFileInfoList &fileInfoList);
public Q_SLOTS:
/**
* @brief 滚动处理槽函数
*/
void onRollingProc();
protected:
/**
* @brief 线程运行函数
*/
void run();
private:
/**
* @brief 线程退出标志
*/
QAtomicInt m_isExit = 1;
/**
* @brief 当前基础文件路径
*/
QString m_strBaseFilePath;
/**
* @brief 最大文件数限制
*
* 允许保留的最大日志文件数量。
* 0表示不限制文件数量。
*/
unsigned m_uMaxFileCount = 0;
/**
* @brief 最大文件大小限制
*
* 允许保留的最大日志文件总大小(字节)。
* 0表示不限制文件大小。
*/
quint64 m_uMaxFileSize = 0;
/**
* @brief 文件信息列表
*/
QFileInfoList m_listFileInfo;
/**
* @brief 互斥锁
*/
QMutex m_mutex;
/**
* @brief 条件变量
*/
QWaitCondition m_condition;
};
#endif // __UKUILOG4QT_ROLLING_H__
ukui-interface/src/log4qt/doc/ 0000775 0001750 0001750 00000000000 15167726064 015177 5 ustar feng feng ukui-interface/src/log4qt/doc/default.css 0000664 0001750 0001750 00000001320 15167726064 017331 0 ustar feng feng BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV {
font-family: Geneva, Arial, Helvetica, sans-serif;
}
BODY,TD {
font-size: 90%;
}
H1 {
text-align: center;
font-size: 160%;
}
H2 {
font-size: 120%;
}
H3 {
font-size: 100%;
}
H2 {
background-color: #e8eef2;
color: #1a419d;
font-weight: bold;
padding-right : 10px;
padding-top : 2px;
padding-left : 10px;
padding-bottom : 2px;
margin-left : 0px;
margin-right : 0px;
margin-top : 2px;
margin-bottom : 2px;
border: 1px solid #cccccc;
}
A {
text-decoration: none;
font-weight: bold;
color: #1A419D;
}
A:visited {
text-decoration: none;
font-weight: bold;
color: #1A419D
}
A:hover {
text-decoration: none;
background-color: #ddddff;
}
ukui-interface/src/log4qt/doc/index.html 0000664 0001750 0001750 00000012720 15167726064 017176 0 ustar feng feng
Log4Qt
Log4Qt
Introduction
Log4Qt is a C++ port of the Apache Software Foundation Log4j package using the
Trolltech Qt Framework. It is intended to be used by open source and commercial
Qt projects.
Documentation
The documentation describes classes and methods that have been added or changed
compared to Log4j. The documentation was generated from the source code using
Doxygen. It can be accessed here.
How to use
To use Log4Qt within your software project include the Log4Qt source into your project
Add the log4qt source to the Qt project file by adding the following line include(<unpackdir>/src/log4qt/log4qt.pri)
Include the Logger class, a layout and an appender class to configure Log4Qt to generate output. The example uses the ConsoleAppender with a TTCCLayout include "log4qt/consoleappender.h" include "log4qt/logger.h" include "log4qt/ttcclayout.h"
Configure a logger to generate output. The example uses the root logger // Create a layout Log4Qt::LogManager::rootLogger(); TTCCLayout *p_layout = new TTCCLayout(); p_layout->setName(QLatin1String("My Layout")); p_layout->activateOptions(); // Create an appender ConsoleAppender *p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET); p_appender->setName(QLatin1String("My Appender")); p_appender->activateOptions(); // Set appender on root logger Log4Qt::Logger::rootLogger()->setAppender(p_appender);
Request a logger by either calling Log4Qt::Logger::logger or using LOG4QT_DECLARE_QCLASS_LOGGER // Request a logger and output "Hello World!" Log4Qt::Logger::logger(QLatin1String("My Logger"))->info("Hello World!");
Releases
0.3 - 01 March 2009
Bug fixes, compatibility with VS 2008 and Qt 4.5 RC1
Fixed a problem where the pParent parameter of the constructor was not passed on to the QObject constructor (logobject.h)
Fixed a problem were OptionConverter::toBoolean would not return the default value, if the conversion fails (optionconverter.cpp)
Fixed a compile error on VS 2008 by using Q_UNUSED(&rEvent) instead of Q_UNUSED(rEvent) (varia/denyallfilter.h.h)
Fixed VS 2008 unreferenced formal parameter warning by using Q_UNUSED (logmanager.cpp, mdc.cpp, ndc.cpp, propertyconfigurator.cpp, helpers/initialisationhelper.cpp, helpers/patternformatter.cpp)
0.2 - 30 January 2009
Bug fixes and compatibility with Qt 4.4
Added a compile time version check for the Qt version (log4qt.h)
Replaced usage of q_atomic_increment and q_atomic_decrement with QAtomicInt for compilation with Qt 4.4 (helpers/logobject.h)
Replaced usage of q_atomic_test_and_set_ptr with QAtomicPointer for compilation with Qt 4.4 (logger.h, helpers/classlogger.cpp, helpers/classlogger.h, helpers/initialisationhelper.h)
Fixed a problem with Qt 4.4 where QReadWriteLock is by default non-recursive (hierarchy.cpp, logger.cpp)
Resolved compilation problem with Microsoft Visual Studio 2005 (logmanager.cpp, helpers/datetime.cpp)
0.1 - 29 December 2007
Initial Version
Known Problems
The Eclipse CDT console does not display the log output of a correctly
when using a ConsoleAppender with a TTCCLayout and relative time format.
The millisecond count is stripped from the output.
ukui-interface/src/log4qt/org.ukui.log4qt-test.gschema.xml 0000664 0001750 0001750 00000003240 15167726064 022512 0 ustar feng feng "true"hook qt messagesControl if hook qt messages"DEBUG,console,daily"config rootLogger's level and appendersconfig rootLogger's level and appenders:"level,appender"".yyyy-MM-dd"daily log file patternset daily log file pattern format:one day"%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)[%t]|%-5p| - %m%n"set log message's formatset log message's format3600set check log files delay timeset check log files delay time3set log files countset log files count,unit s512set log files total sizeset log files total size, unit M
ukui-interface/src/log4qt/ukui-log4qt.pri 0000664 0001750 0001750 00000002276 15167726076 017345 0 ustar feng feng DEFINES += LIBUKUILOG4QT_LIBRARY UKUILOG4QT_EXTRA_ENABLE
# Qt6 requires C++17 or higher
greaterThan(QT_MAJOR_VERSION, 5) {
CONFIG += link_pkg_config c++17
PKGCONFIG += gsettings-qt6
} else {
config += link_pkg_config c++14
PKGCONFIG += gsettings-qt
}
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
#log4qt
include($$PWD/log4qt/log4qt.pri)
SOURCES += \
$$PWD/ukui-logconfigurator.cpp \
$$PWD/ukui-logrolling.cpp \
$$PWD/ukui-log4qt.cpp
HEADERS += \
$$PWD/ukui-logmacros.h \
$$PWD/ukui-logconfigurator.h \
$$PWD/ukui-logrolling.h \
$$PWD/ukui-log4qt.h
DISTFILES += \
$$PWD/log4qt.conf
ukui-interface/src/log4qt/log4qt.conf 0000664 0001750 0001750 00000007357 15167726064 016527 0 ustar feng feng #设置储存log文件的根目录
logpath=.
#全局设置
#是否重置所有配置,恢复全局设置默认值
log4j.reset=true
#设置Log4Qt记录器输入级别
log4j.Debug=INFO
#日志记录器存储库的阈值
log4j.threshold=NULL
#设置是否监听QDebug输出的字符串
log4j.handleQtMessages=true
#设置根Logger的输出log等级为INFO
#设置Log输出的几种输出源(appender):console, daily
log4j.rootLogger=DEBUG,console,daily
#设置终端打印记录器
#记录器类别 --控制台输出
log4j.appender.console=org.apache.log4j.ConsoleAppender
#记录器输出目标
log4j.appender.console.target=STDOUT_TARGET
#记录器输出布局 (包含日志产生的时间、线程、类别等信息)
log4j.appender.console.layout=org.apache.log4j.TTCCLayout
#记录器布局日期格式 (年-月-日 时:分:秒.毫秒)
log4j.appender.console.layout.dateFormat=yyy-MM-dd hh:mm:ss.zzz
#记录器布局包含上下文
log4j.appender.console.layout.contextPrinting=false
#记录器布局包含线程信息
#log4j.appender.console.layout.ThreadPrinting=false
#设置一个每日储存一个log文件的记录器
#记录器类别 --一天一个文件输出
log4j.appender.daily=org.apache.log4j.DailyRollingFileAppender
#记录器输出文件路径
log4j.appender.daily.file=${logpath}/log4qt.log
#记录器追加文件内容
log4j.appender.daily.appendFile=true
#记录器是否直接写入文件
#log4j.appender.daily.immediateFlush=true
#记录器文件名日期后缀 按天
log4j.appender.daily.datePattern=.yyyy-MM-dd
#记录器布局分隔符 (根据patten符号格式化输出数据,类似printf的格式化方式)
log4j.appender.daily.layout=org.apache.log4j.PatternLayout
log4j.appender.daily.layout.conversionPattern=%-5p|%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)|%m%n
#记录器输出格式
#日志信息格式中几个符号所代表的含义:
# -X号: X信息输出时左对齐;
# %p: 输出日志信息优先级,即DEBUG,INFO,WARN,ERROR,FATAL,
# %d: 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921
# %r: 输出自应用启动到输出该log信息耗费的毫秒数
# %c: 输出日志信息所属的类目,通常就是所在类的全名 (无效)
# %t: 输出产生该日志事件的线程名 (无效)
# %l: 输出日志事件的发生位置,相当于%C.%M(%F:%L)的组合,包括类目名、发生的线程,以及在代码中的行数(无效)。举例:Testlog4.main (TestLog4.java:10)
# %x: 输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像java servlets这样的多客户多线程的应用中。
# %%: 输出一个"%"字符
# %F: 输出日志消息产生时所在的文件名称(无效)
# %L: 输出代码中的行号(无效)
# %m: 输出代码中指定的消息,产生的日志具体信息(默认在消息内容前追加了文件名,行号,函数名)
# %n: 输出一个回车换行符,Windows平台为"\r\n",Unix平台为"\n"输出日志信息换行
# 可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如:
# 1) c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,默认的情况下右对齐。
# 2)%-20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,"-"号指定左对齐。
# 3)%.30c:指定输出category的名称,最大的宽度是30,如果category的名称大于30的话,就会将左边多出的字符截掉,但小于30的话也不会有空格。
# 4) .30c:如果category的名称小于20就补空格,并且右对齐,如果其名称长于30字符,就从左边较远输出的字符截掉。
ukui-interface/src/log4qt/ukui-log4qt.h 0000664 0001750 0001750 00000002601 15167726064 016767 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
//输出debug级别日志
#define KyDebug QMessageLogger(__FILE__, __LINE__, __FUNCTION__).debug
//输出info级别日志
#define KyInfo QMessageLogger(__FILE__, __LINE__, __FUNCTION__).info
//输出warning级别日志
#define KyWarning QMessageLogger(__FILE__, __LINE__, __FUNCTION__).warning
//输出critical级别日志
#define KyCritical QMessageLogger(__FILE__, __LINE__, __FUNCTION__).critical
//输出fatal级别日志
#define KyFatal QMessageLogger(__FILE__, __LINE__, __FUNCTION__).fatal
// 初始化ukui-log4qt库,传入application名称
int initUkuiLog4qt(QString strAppName);
#endif // __UKUILOG4QT_H__
ukui-interface/src/log4qt/ukui-log4qt.pro 0000664 0001750 0001750 00000002741 15167726076 017350 0 ustar feng feng QT -= gui
TEMPLATE = lib
DEFINES += LIBUKUILOG4QT_LIBRARY UKUILOG4QT_EXTRA_ENABLE
CONFIG += link_pkgconfig \
c++11
# Qt6 requires C++17 or higher
greaterThan(QT_MAJOR_VERSION, 5) {
CONFIG += c++17
PKGCONFIG += gsettings-qt6
} else {
PKGCONFIG += gsettings-qt
}
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
#log4qt
include($$PWD/log4qt/log4qt.pri)
SOURCES += \
ukui-logconfigurator.cpp \
ukui-logrolling.cpp \
ukui-log4qt.cpp
HEADERS += \
ukui-logmacros.h \
ukui-logconfigurator.h \
ukui-logrolling.h \
ukui-log4qt.h
# Default rules for deployment.
unix {
target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target
schemes.files += org.ukui.log4qt.gschema.xml
schemes.path = /usr/share/glib-2.0/schemas/
headers_main.path = /usr/include
headers_main.files += ukui-log4qt.h
INSTALLS += schemes \
headers_main
DISTFILES += \
log4qt.conf
ukui-interface/src/log4qt/README.txt 0000664 0001750 0001750 00000000053 15167726064 016126 0 ustar feng feng See HTML documentation under doc/index.html ukui-interface/src/log4qt/ukui-logmacros.h 0000664 0001750 0001750 00000004771 15167726064 017555 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#if defined(LIBUKUILOG4QT_LIBRARY)
# define LIBUKUILOG4QT_EXPORT Q_DECL_EXPORT
#else
# define LIBUKUILOG4QT_EXPORT Q_DECL_IMPORT
#endif
// 日志文件相对home目录路径
#define UKUILOG4QT_ROOTPATH "/.log/"
// gsettings相关相关属性
#define UKUILOG4QT_SETTINGS "org.ukui.ukui-log4qt"
#define UKUILOG4QT_SETTINGS_RESET "log4jReset"
#define UKUILOG4QT_SETTINGS_DEBUG "log4jDebug"
#define UKUILOG4QT_SETTINGS_HANDLEQT "log4jHandleqtmessages"
#define UKUILOG4QT_SETTINGS_ROOTLOGGER "log4jRootlogger"
#define UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN "log4jAppenderDailyDatepattern"
#define UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN "log4jAppenderDailyLayoutConversionpattern"
#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME "delaytime"
#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT "maxfilecount"
#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE "maxfilesize"
// log4qt相关属性
#define UKUILOG4QT_RESET "log4j.reset" //是否重置所有配置,恢复全局设置默认值
#define UKUILOG4QT_DEBUG "log4j.Debug" //设置日志sdk内部记录器级别
#define UKUILOG4QT_HANDLEQT "log4j.handleQtMessages" //设置是否监听QDebug输出的字符串
#define UKUILOG4QT_ROOTLOGGER "log4j.rootLogger" //设置根Logger的输出log等级和输出目的地
#define UKUILOG4QT_DAILY_DATEPATTERN "log4j.appender.daily.datePattern" //记录器文件名日期后缀 按天
#define UKUILOG4QT_DAILY_CONVERSIONPATTERN "log4j.appender.daily.layout.conversionPattern" //记录器日志输出格式
#endif // __UKUI_LOGMACROS__
ukui-interface/src/log4qt/LICENSE-2.0.txt 0000664 0001750 0001750 00000026136 15167726064 016562 0 ustar feng feng
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
ukui-interface/src/log4qt/org.ukui.log4qt.gschema.xml 0000664 0001750 0001750 00000004031 15167726064 021534 0 ustar feng feng "true"reset all log4j configControl if reset all log4j config"INFO"config logLogger's output levelconfig logLogger's output level: DEBUG/INFO/WARN/ERROR"true"hook qt messagesControl if hook qt messages"INFO,daily"config rootLogger's level and appendersconfig rootLogger's level and appenders:"level,appender"".yyyy-MM-dd"daily log file patternset daily log file pattern format:one day"%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)[%t]|%-5p| - %m%n"set log message's formatset log message's format3600set check log files delay timeset check log files delay time3set log files countset log files count,unit s512set log files total sizeset log files total size, unit M
ukui-interface/src/log4qt/ukui-logrolling.cpp 0000664 0001750 0001750 00000015152 15167726076 020270 0 ustar feng feng /*
* Copyright (C) 2021 Tianjin KYLIN Information Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
#include
#include
#include
/**
* @brief 构造函数
* @param strBaseFilePath 基础日志文件路径
* @param parent 父对象指针
*/
UkuiLog4qtRolling::UkuiLog4qtRolling(QString strBaseFilePath, QObject *parent)
: QThread(parent), m_isExit(0), m_strBaseFilePath(strBaseFilePath)
{
}
/**
* @brief 析构函数
*/
UkuiLog4qtRolling::~UkuiLog4qtRolling() {}
/**
* @brief 线程运行函数
*/
void UkuiLog4qtRolling::run()
{
// 检查退出标志,如果已设置则直接返回
if (m_isExit.loadAcquire()) {
return;
}
// 主循环:等待任务并执行清理操作
while (!m_isExit.loadAcquire()) {
QMutexLocker locker(&m_mutex);
// 等待条件变量唤醒(有新的清理任务)
m_condition.wait(&m_mutex);
// 再次检查退出标志,如果已设置则退出循环
if (m_isExit.loadAcquire()) {
break;
}
// 执行文件数量检查(如果设置了限制)
if (m_uMaxFileCount > 0) {
checkLogFilesCount(m_listFileInfo);
}
// 执行文件大小检查(如果设置了限制)
if (m_uMaxFileSize > 0) {
checkLogFilesSize(m_listFileInfo);
}
}
}
/**
* @brief 设置文件检查限制条件
* @param fileInfoList 要检查的文件信息列表
* @param uMaxFileCount 最大允许的文件数量(0表示不限制)
* @param uMaxFileSize 最大允许的文件总大小(0表示不限制)
*/
void UkuiLog4qtRolling::setFileCheckLimit(
const QFileInfoList &fileInfoList, unsigned uMaxFileCount, quint64 uMaxFileSize)
{
QMutexLocker locker(&m_mutex);
// 更新文件信息列表和限制条件
m_listFileInfo = fileInfoList;
m_uMaxFileCount = uMaxFileCount;
m_uMaxFileSize = uMaxFileSize;
// 唤醒等待的线程开始执行清理任务
m_condition.wakeOne();
}
/**
* @brief 停止线程
*/
void UkuiLog4qtRolling::stop()
{
// 设置退出标志
m_isExit = 1;
// 获取互斥锁并唤醒等待的线程
QMutexLocker locker(&m_mutex);
m_condition.wakeOne();
}
/**
* @brief 检查文件数量
* @param fileInfoList 要检查的文件信息列表
*/
void UkuiLog4qtRolling::checkLogFilesCount(const QFileInfoList &fileInfoList)
{
// 检查退出标志,如果已设置则直接返回
if (m_isExit.loadAcquire()) {
return;
}
// 检查文件数量是否超过限制
if (fileInfoList.size() <= (int)(m_uMaxFileCount)) {
return;
}
// 计算需要删除的文件数量
int filesToRemove = fileInfoList.size() - m_uMaxFileCount;
QTime startTime = QTime::currentTime();
// 从文件列表末尾开始删除(最旧的文件在前)
for (int i = fileInfoList.size() - 1; i >= 0 && filesToRemove > 0; i--) {
// 检查超时或退出标志,避免长时间阻塞
if (startTime.msecsTo(QTime::currentTime()) > 500 || m_isExit.loadAcquire()) {
break;
}
QString filePath = fileInfoList[i].absoluteFilePath();
// 跳过当前正在使用的基础文件,避免删除正在写入的文件
if (filePath == m_strBaseFilePath) {
continue;
}
// 尝试删除文件
QFile file(filePath);
if (file.remove()) {
KyDebug() << QString("Removed old log file: %1").arg(filePath);
filesToRemove--;
} else {
KyWarning() << "Failed to remove old log file:" << filePath;
}
}
}
/**
* @brief 检查文件大小
* @param fileInfoList 要检查的文件信息列表
*/
void UkuiLog4qtRolling::checkLogFilesSize(const QFileInfoList &fileInfoList)
{
// 检查退出标志,如果已设置则直接返回
if (m_isExit.loadAcquire()) {
return;
}
// 计算所有文件的总大小
qint64 totalSize = 0;
QTime startTime = QTime::currentTime();
// 遍历所有文件,累加文件大小
for (const QFileInfo &fileInfo : fileInfoList) {
// 设置200ms超时,避免大小计算耗时过长
if (startTime.msecsTo(QTime::currentTime()) > 200) {
qWarning("Size calculation timeout, using estimated size");
break;
}
totalSize += fileInfo.size();
}
// 检查总大小是否超过限制
if (totalSize <= (qint64)(m_uMaxFileSize)) {
return;
}
// 计算需要清理的大小
qint64 sizeToRemove = totalSize - m_uMaxFileSize;
QString currentFilePath = m_strBaseFilePath;
startTime = QTime::currentTime();
// 从文件列表末尾开始清理(最旧的文件在前)
for (int i = fileInfoList.size() - 1; i >= 0 && sizeToRemove > 0; i--) {
// 设置1秒超时,避免清理过程耗时过长
if (startTime.msecsTo(QTime::currentTime()) > 1000 || m_isExit.loadAcquire()) {
qWarning() << "Size cleanup timeout, stopping to avoid blocking";
break;
}
QString filePath = fileInfoList[i].absoluteFilePath();
qint64 fileSize = fileInfoList[i].size();
// 处理当前正在使用的文件
if (filePath == currentFilePath) {
// 对于当前文件,清空内容而不是删除,避免影响正在进行的日志记录
QProcess process;
process.start("sh", QStringList() << "-c" << QString("> %1").arg(filePath));
process.waitForFinished(100);
sizeToRemove -= fileSize;
} else {
// 对于历史文件,直接删除
QFile file(filePath);
if (file.remove()) {
KyDebug() << QString("Removed old log file: %1 (size: %2 bytes)").arg(filePath).arg(fileSize);
sizeToRemove -= fileSize;
} else {
qWarning() << QString("Failed to remove old log file: %1").arg(filePath);
}
}
}
}
ukui-interface/src/log4qt/log4qt/ 0000775 0001750 0001750 00000000000 15167726076 015647 5 ustar feng feng ukui-interface/src/log4qt/log4qt/level.h 0000664 0001750 0001750 00000013461 15167726064 017131 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: level.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LEVEL_H
#define LOG4QT_LEVEL_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class Level defines the level of a logging event.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT Level
{
public:
// Comparisson operators rely on the order:
// NULL_INT < ALL_INT < TRACE_INT < ...
// Serialisation uses unsigned 8 bit int
/*!
* The enumeration Value contains all possible Level values.
*/
enum Value
{
/*! NULL_INT is used for no level has been specified */
NULL_INT = 0,
ALL_INT = 32,
TRACE_INT = 64,
DEBUG_INT = 96,
INFO_INT = 128,
WARN_INT = 150,
ERROR_INT = 182,
FATAL_INT = 214,
OFF_INT = 255
};
public:
Level(Value value = NULL_INT);
// Level(const Level &rOther); // Use compiler default
// virtual ~Level(); // Use compiler default
// Level &operator=(const Level &rOther); // Use compiler default
int syslogEquivalent() const;
int toInt() const;
bool operator==(const Level &rOther) const;
bool operator!=(const Level &rOther) const;
bool operator<(const Level &rOther) const;
bool operator<=(const Level &rOther) const;
bool operator>(const Level &rOther) const;
bool operator>=(const Level &rOther) const;
QString toString() const;
static Level fromString(const QString &rName, bool *pOk = 0);
private:
// QMutex mObjectGuard;
volatile Value mValue;
#ifndef QT_NO_DATASTREAM
// Needs to be friend to stream objects
friend QDataStream &operator<<(QDataStream &rStream,
const Level &rLevel);
friend QDataStream &operator>>(QDataStream &rStream,
Level &rLevel);
#endif // QT_NO_DATASTREAM
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
/*!
* \relates Level
*
* Writes the given error \a rLevel to the given stream \a rStream,
* and returns a reference to the stream.
*/
QDataStream &operator<<(QDataStream &rStream,
const Level &rLevel);
/*!
* \relates Level
*
* Reads an error from the given stream \a rStream into the given
* error \a rLevel, and returns a reference to the stream.
*/
QDataStream &operator>>(QDataStream &rStream,
Level &rLevel);
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates Level
*
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %Level("ERROR")
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const Level &rLevel);
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Inline
**************************************************************************/
inline Level::Level(Value value) :
mValue(value)
{}
inline int Level::toInt() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue; }
inline bool Level::operator==(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue == rOther.mValue; }
inline bool Level::operator!=(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue != rOther.mValue; }
inline bool Level::operator<(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue < rOther.mValue; }
inline bool Level::operator<=(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue <= rOther.mValue; }
inline bool Level::operator>(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue > rOther.mValue; }
inline bool Level::operator>=(const Level &rOther) const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mValue >= rOther.mValue; }
} // namespace Log4Qt
Q_DECLARE_METATYPE(Log4Qt::Level)
Q_DECLARE_TYPEINFO(Log4Qt::Level, Q_MOVABLE_TYPE);
#endif // LOG4QT_LEVEL_H
ukui-interface/src/log4qt/log4qt/simplelayout.h 0000664 0001750 0001750 00000005745 15167726064 020557 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: simplelayout.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_SIMPLELAYOUT_H
#define LOG4QT_SIMPLELAYOUT_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/layout.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class SimpleLayout outputs the level and message of a logging
* event.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT SimpleLayout : public Layout
{
Q_OBJECT
public:
SimpleLayout(QObject *pParent = 0);
// virtual ~SimpleLayout(); // Use compiler default
private:
SimpleLayout(const SimpleLayout &rOther); // Not implemented
SimpleLayout &operator=(const SimpleLayout &rOther); // Not implemented
public:
virtual QString format(const LoggingEvent &rEvent);
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %SimpleLayout(name:"SL" referencecount:1)
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline SimpleLayout::SimpleLayout(QObject *pParent) :
Layout(pParent)
{}
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::SimpleLayout, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_SIMPLELAYOUT_H
ukui-interface/src/log4qt/log4qt/spi/ 0000775 0001750 0001750 00000000000 15167726076 016442 5 ustar feng feng ukui-interface/src/log4qt/log4qt/spi/filter.h 0000664 0001750 0001750 00000006633 15167726076 020110 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: filter.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_FILTER_H
#define LOG4QT_FILTER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/helpers/logobject.h"
#include "log4qt/helpers/logobjectptr.h"
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class LoggingEvent;
/*!
* \brief The class Filter is the base class for all filters.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT Filter : public LogObject
{
Q_OBJECT
/*!
* The property holds the next filter of this filter.
*
* The default is 0 for no next filter.
*
* \sa next(), setNext()
*/
Q_PROPERTY(Filter* next READ next WRITE setNext)
public:
enum Decision
{
ACCEPT,
DENY,
NEUTRAL
};
Q_ENUMS(Decision);
public:
Filter(QObject *pObject = 0);
// Filter(const Filter &rOther); // Use compiler default
virtual ~Filter();
// Filter &operator=(const Filter &rOther); // Use compiler default
Filter* next() const;
void setNext(Filter *pFilter);
virtual void activateOptions();
virtual Decision decide(const LoggingEvent &rEvent) const = 0;
private:
LogObjectPtr mpNext;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline Filter::Filter(QObject *pObject) :
LogObject(pObject),
mpNext(0)
{}
inline Filter::~Filter()
{}
inline Filter* Filter::next() const
{ return mpNext; }
inline void Filter::activateOptions()
{}
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::Filter, Q_COMPLEX_TYPE); // Use default
#if QT_VERSION < 0x060000
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE);
#else
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_COMPLEX_TYPE);
#endif
// Qt6 compatibility: opaque pointer declared in appender.h
#endif // LOG4QT_FILTER_H
ukui-interface/src/log4qt/log4qt/spi/filter.cpp 0000664 0001750 0001750 00000003707 15167726064 020437 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: filter.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/spi/filter.h"
#include
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: Filter
**************************************************************************/
void Filter::setNext(Filter *pFilter)
{
mpNext = pFilter;
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/patternlayout.cpp 0000664 0001750 0001750 00000007527 15167726064 021276 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: patternlayout.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/patternlayout.h"
#include
#include "log4qt/helpers/patternformatter.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: PatternLayout
**************************************************************************/
PatternLayout::PatternLayout(QObject *pParent) :
Layout(pParent),
mPattern(),
mpPatternFormatter(0)
{
setConversionPattern(DEFAULT_CONVERSION_PATTERN);
}
PatternLayout::PatternLayout(const QString &rPattern,
QObject *pParent) :
Layout(pParent),
mPattern(),
mpPatternFormatter(0)
{
setConversionPattern(rPattern);
}
PatternLayout::PatternLayout(ConversionPattern conversionPattern,
QObject *pParent) :
Layout(pParent),
mPattern(),
mpPatternFormatter(0)
{
setConversionPattern(conversionPattern);
}
PatternLayout::~PatternLayout()
{
delete mpPatternFormatter;
}
void PatternLayout::setConversionPattern(ConversionPattern conversionPattern)
{
switch (conversionPattern)
{
case DEFAULT_CONVERSION_PATTERN:
setConversionPattern(QLatin1String("%m%n"));
break;
case TTCC_CONVERSION_PATTERN:
setConversionPattern(QLatin1String("%r [%t] %p %c %x - %m%n"));
break;
default:
Q_ASSERT_X(false, "PatternLayout::setConversionFormat", "Unkown ConversionFormat");
setConversionPattern(QString());
}
}
QString PatternLayout::format(const LoggingEvent &rEvent)
{
Q_ASSERT_X(mpPatternFormatter, "PatternLayout::format()", "mpPatternConverter must not be null");
return mpPatternFormatter->format(rEvent);
}
void PatternLayout::updatePatternFormatter()
{
delete mpPatternFormatter;
mpPatternFormatter = new PatternFormatter(mPattern);
}
#ifndef QT_NO_DEBUG_STREAM
QDebug PatternLayout::debug(QDebug &rDebug) const
{
rDebug.nospace() << "PatternLayout("
<< "name:" << name() << " "
<< "pattern:" << conversionPattern() << " "
<< "referencecount:" << referenceCount()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/loggingevent.cpp 0000664 0001750 0001750 00000017076 15167726064 021053 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: loggingevent.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/loggingevent.h"
#include
#include
#include
#include
#include
#include
#include "log4qt/helpers/datetime.h"
#include "log4qt/helpers/initialisationhelper.h"
#include "log4qt/logger.h"
#include "log4qt/mdc.h"
#include "log4qt/ndc.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: LoggingEvent
**************************************************************************/
LoggingEvent::LoggingEvent() :
QEvent(eventId),
mLevel(Level::NULL_INT),
mpLogger(0),
mMessage(),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage) :
QEvent(eventId),
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
qint64 timeStamp) :
QEvent(eventId),
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(NDC::peek()),
mProperties(MDC::context()),
mSequenceNumber(nextSequenceNumber()),
mThreadName(),
mTimeStamp(timeStamp)
{
setThreadNameToCurrent();
}
LoggingEvent::LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
const QString &rNdc,
const QHash &rProperties,
const QString &rThreadName,
qint64 timeStamp) :
QEvent(eventId),
mLevel(level),
mpLogger(pLogger),
mMessage(rMessage),
mNdc(rNdc),
mProperties(rProperties),
mSequenceNumber(nextSequenceNumber()),
mThreadName(rThreadName),
mTimeStamp(timeStamp)
{
}
QString LoggingEvent::loggerName() const
{
if (mpLogger)
return mpLogger->name();
else
return QString();
}
QString LoggingEvent::toString() const
{
return level().toString() + QLatin1Char(':') + message();
}
qint64 LoggingEvent::sequenceCount()
{
QMutexLocker locker(sequence_guard());
return msSequenceCount;
}
qint64 LoggingEvent::startTime()
{
return InitialisationHelper::startTime();
}
void LoggingEvent::setThreadNameToCurrent()
{
if (QThread::currentThread()) {
mThreadName = QThread::currentThread()->objectName();
if (mThreadName.isEmpty()) {
mThreadName = QString("%1").arg((quint64)QThread::currentThreadId());
}
}
}
qint64 LoggingEvent::nextSequenceNumber()
{
QMutexLocker locker(sequence_guard());
return ++msSequenceCount;
}
qint64 LoggingEvent::msSequenceCount = 0;
const QEvent::Type LoggingEvent::eventId = static_cast(QEvent::registerEventType());
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
QDataStream stream(&buffer);
// version
quint16 version = 0;
stream << version;
// version 0 data
stream << rLoggingEvent.mLevel
<< rLoggingEvent.loggerName()
<< rLoggingEvent.mMessage
<< rLoggingEvent.mNdc
<< rLoggingEvent.mProperties
<< rLoggingEvent.mSequenceNumber
<< rLoggingEvent.mThreadName
<< rLoggingEvent.mTimeStamp;
buffer.close();
rStream << buffer.buffer();
return rStream;
}
QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)
{
QByteArray array;
rStream >> array;
QBuffer buffer(&array);
buffer.open(QIODevice::ReadOnly);
QDataStream stream(&buffer);
// version
quint16 version;
stream >> version;
// Version 0 data
QString logger;
stream >> rLoggingEvent.mLevel
>> logger
>> rLoggingEvent.mMessage
>> rLoggingEvent.mNdc
>> rLoggingEvent.mProperties
>> rLoggingEvent.mSequenceNumber
>> rLoggingEvent.mThreadName
>> rLoggingEvent.mTimeStamp;
if (logger.isEmpty())
rLoggingEvent.mpLogger = 0;
else
rLoggingEvent.mpLogger = Logger::logger(logger);
buffer.close();
return rStream;
}
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const LoggingEvent &rLoggingEvent)
{
QString logger;
if (rLoggingEvent.logger() != 0)
logger = rLoggingEvent.logger()->name();
debug.nospace() << "LoggingEvent("
<< "level:" << rLoggingEvent.level().toString() << " "
<< "logger:" << logger << " "
<< "message:" << rLoggingEvent.message() << " "
<< "sequencenumber:" << rLoggingEvent.sequenceNumber() << " "
<< "threadname:" << rLoggingEvent.threadName() << " "
<< "timestamp:" << rLoggingEvent.timeStamp()
<< "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")"
<< "sequenceCount:" << rLoggingEvent.sequenceCount()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/rollingfileappender.h 0000664 0001750 0001750 00000012752 15167726064 022051 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: rollingfileappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_ROLINGFILEAPPENDER_H
#define LOG4QT_ROLINGFILEAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/fileappender.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class RollingFileAppender extends FileAppender to backup
* the log files when they reach a certain size.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT RollingFileAppender : public FileAppender
{
Q_OBJECT
/*!
* The property holds the maximum backup count used by the appender.
*
* The default is 1.
*
* \sa maxBackupIndex(), setMaxBackupIndex()
*/
Q_PROPERTY(int maxBackupIndex READ maxBackupIndex WRITE setMaxBackupIndex)
/*!
* The property holds the maximum file size used by the appender.
*
* The default is 10 MB (10 * 1024 * 1024).
*
* \sa maximumFileSize(), setMaximumFileSize()
*/
Q_PROPERTY(qint64 maximumFileSize READ maximumFileSize WRITE setMaximumFileSize)
/*!
* The property sets the maximum file size from a string value.
*
* \sa setMaxFileSize(), maximumFileSize()
*/
Q_PROPERTY(QString maxFileSize WRITE setMaxFileSize)
public:
RollingFileAppender(QObject *pParent = 0);
RollingFileAppender(Layout *pLayout,
const QString &rFileName,
QObject *pParent = 0);
RollingFileAppender(Layout *pLayout,
const QString &rFileName,
bool append,
QObject *pParent = 0);
virtual ~RollingFileAppender();
private:
RollingFileAppender(const RollingFileAppender &rOther); // Not implemented
RollingFileAppender &operator=(const RollingFileAppender &rOther); // Not implemented
public:
int maxBackupIndex() const;
qint64 maximumFileSize() const;
void setMaxBackupIndex(int maxBackupIndex);
void setMaximumFileSize(qint64 maximumFileSize);
void setMaxFileSize(const QString &rMaxFileSize);
protected:
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %RollingFileAppender(name:"RFA" appendfile:false bufferedio:true
* encoding:"" file:"/log.txt" filter: 0x0
* immediateflush:true isactive:true
* isclosed:false layout:"TTCC" maxbackupindex:2
* maximumfilesize:40 referencecount:1
* threshold:"NULL" writer:0x4175af8)
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
private:
void rollOver();
private:
int mMaxBackupIndex;
qint64 mMaximumFileSize;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline int RollingFileAppender::maxBackupIndex() const
{ QMutexLocker locker(&mObjectGuard);
return mMaxBackupIndex; }
inline qint64 RollingFileAppender::maximumFileSize() const
{ QMutexLocker locker(&mObjectGuard);
return mMaximumFileSize; }
inline void RollingFileAppender::setMaxBackupIndex(int maxBackupIndex)
{ QMutexLocker locker(&mObjectGuard);
mMaxBackupIndex = maxBackupIndex; }
inline void RollingFileAppender::setMaximumFileSize(qint64 maximumFileSize)
{ QMutexLocker locker(&mObjectGuard);
mMaximumFileSize = maximumFileSize; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::RollingFileAppender, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_ROLINGFILEAPPENDER_H
ukui-interface/src/log4qt/log4qt/rollingfileappender.cpp 0000664 0001750 0001750 00000013755 15167726076 022413 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: rollingfileappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/rollingfileappender.h"
#include
#include
#if QT_VERSION < 0x060000
#include
#endif
#include "log4qt/helpers/optionconverter.h"
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/************************************************************************
Declarations
*************************************************************************/
/************************************************************************
C helper functions
*************************************************************************/
/************************************************************************
Class implementation: RollingFileAppender
*************************************************************************/
RollingFileAppender::RollingFileAppender(QObject *pParent) :
FileAppender(pParent),
mMaxBackupIndex(1),
mMaximumFileSize(10*1024*1024)
{
}
RollingFileAppender::RollingFileAppender(Layout *pLayout,
const QString &rFileName,
QObject *pParent) :
FileAppender(pLayout, rFileName, pParent),
mMaxBackupIndex(1),
mMaximumFileSize(10*1024*1024)
{
}
RollingFileAppender::RollingFileAppender(Layout *pLayout,
const QString &rFileName,
bool append,
QObject *pParent) :
FileAppender(pLayout, rFileName, append, pParent),
mMaxBackupIndex(1),
mMaximumFileSize(10*1024*1024)
{
}
RollingFileAppender::~RollingFileAppender()
{
close();
}
void RollingFileAppender::setMaxFileSize(const QString &rMaxFileSize)
{
bool ok;
qint64 max_file_size = OptionConverter::toFileSize(rMaxFileSize, &ok);
if (ok)
setMaximumFileSize(max_file_size);
}
void RollingFileAppender::append(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "RollingFileAppender::append()", "Lock must be held by caller")
FileAppender::append(rEvent);
#ifndef UKUILOG4QT_EXTRA_ENABLE
if (writer()->device()->size() > this->mMaximumFileSize)
rollOver();
#endif
}
void RollingFileAppender::asyncAppend(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "RollingFileAppender::asyncAppend()", "Lock must be held by caller")
FileAppender::asyncAppend(rEvent);
if (writer()->device()->size() > this->mMaximumFileSize)
rollOver();
}
void RollingFileAppender::rollOver()
{
// Q_ASSERT_X(, "RollingFileAppender::rollOver()", "Lock must be held by caller")
logger()->debug("Rolling over with maxBackupIndex = %1", mMaxBackupIndex);
closeFile();
QFile f;
f.setFileName(file() + QLatin1Char('.') + QString::number(mMaxBackupIndex));
if (f.exists() && !removeFile(f))
return;
QString target_file_name;
int i;
for (i = mMaxBackupIndex - 1; i >=1; i--)
{
f.setFileName(file() + QLatin1Char('.') + QString::number(i));
if (f.exists())
{
target_file_name = file() + QLatin1Char('.') + QString::number(i + 1);
if (!renameFile(f, target_file_name))
return;
}
}
f.setFileName(file());
target_file_name = file() + QLatin1String(".1");
if (!renameFile(f, target_file_name))
return;
openFile();
}
#ifndef QT_NO_DEBUG_STREAM
QDebug RollingFileAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
QString codec_name;
#if QT_VERSION < 0x060000
if (encoding())
codec_name = QLatin1String(encoding()->name());
#else
codec_name = QLatin1String(QStringConverter::nameForEncoding(encoding()));
#endif
rDebug.nospace() << "RollingFileAppender("
<< "name:" << name() << " "
<< "appendfile:" << appendFile() << " "
<< "bufferedio:" << bufferedIo() << " "
<< "encoding:" << codec_name << " "
<< "file:" << file() << " "
<< "filter:" << firstFilter() << " "
<< "immediateflush:" << immediateFlush() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "maxbackupindex:" << maxBackupIndex() << " "
<< "maximumfilesize:" << maximumFileSize() << " "
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString() << " "
<< "writer:" << writer()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/logmanager.cpp 0000664 0001750 0001750 00000041560 15167726076 020475 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: logmanager.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* changes: Sep 2008, Martin Heinrich:
* - Resolved compilation problem with Microsoft Visual Studio 2005
* Feb 2009, Martin Heinrich
* - Fixed VS 2008 unreferenced formal parameter warning by using
* Q_UNUSED in operator<<.
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/logmanager.h"
#include
#include
#include
#include
#include
#include
#include "log4qt/consoleappender.h"
#include "log4qt/helpers/datetime.h"
#include "log4qt/helpers/initialisationhelper.h"
#include "log4qt/helpers/optionconverter.h"
#include "log4qt/hierarchy.h"
#include "log4qt/propertyconfigurator.h"
#include "log4qt/ttcclayout.h"
#include "log4qt/varia/denyallfilter.h"
#include "log4qt/varia/levelrangefilter.h"
#include
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(static_logger, Log4Qt::LogManager)
LOG4QT_GLOBAL_STATIC(QMutex, singleton_guard)
/**************************************************************************
* Class implementation: LogManager
**************************************************************************/
LogManager::LogManager() :
#if QT_VERSION < 0x050E00
mObjectGuard(QMutex::Recursive), // Recursive for doStartup() to call doConfigureLogLogger()
#endif
mpLoggerRepository(new Hierarchy()),
mHandleQtMessages(false),
mOldQtMsgHandler(0)
{
}
LogManager::~LogManager()
{
static_logger()->warn("Unexpected destruction of LogManager");
// doSetConfigureHandleQtMessages(false);
// delete mpLoggerRepository;
}
Logger *LogManager::rootLogger()
{
return instance()->mpLoggerRepository->rootLogger();
}
QList LogManager::loggers()
{
return instance()->mpLoggerRepository->loggers();
}
Level LogManager::threshold()
{
return instance()->mpLoggerRepository->threshold();
}
void LogManager::setThreshold(Level level)
{
instance()->mpLoggerRepository->setThreshold(level);
}
bool LogManager::exists(const char *pName)
{
return instance()->mpLoggerRepository->exists(QLatin1String(pName));
}
LogManager *LogManager::instance()
{
// Do not use LOG4QT_GLOBAL_STATIC. The LogManager is rather expensive
// to construct, an exit handler must be set and doStartup must be
// called.
if (!mspInstance)
{
QMutexLocker locker(singleton_guard());
if (!mspInstance)
{
mspInstance = new LogManager;
// qAddPostRoutine(shutdown);
atexit(shutdown);
mspInstance->doConfigureLogLogger();
mspInstance->welcome();
mspInstance->doStartup();
}
}
return mspInstance;
}
Logger *LogManager::logger(const QString &rName)
{
return instance()->mpLoggerRepository->logger(rName);
}
void LogManager::resetConfiguration()
{
setHandleQtMessages(false);
instance()->mpLoggerRepository->resetConfiguration();
configureLogLogger();
}
const char* LogManager::version()
{
return LOG4QT_VERSION_STR;
}
void LogManager::shutdown()
{
instance()->mpLoggerRepository->shutdown();
}
void LogManager::doSetHandleQtMessages(bool handleQtMessages)
{
QMutexLocker locker(&mObjectGuard);
if (instance()->mHandleQtMessages == handleQtMessages)
return;
instance()->mHandleQtMessages = handleQtMessages;
if (instance()->mHandleQtMessages)
{
static_logger()->trace("Activate Qt message handling");
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
instance()->mOldQtMsgHandler = qInstallMsgHandler(qtMessageHandler);
#else
instance()->mOldQtMsgHandler = qInstallMessageHandler(qtMessageHandler);
#endif
}
else
{
static_logger()->trace("Deactivate Qt message handling");
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
qInstallMsgHandler(instance()->mOldQtMsgHandler);
#else
qInstallMessageHandler(instance()->mOldQtMsgHandler);
#endif
}
}
void LogManager::doConfigureLogLogger()
{
QMutexLocker locker(&instance()->mObjectGuard);
// Level
QString value = InitialisationHelper::setting(QLatin1String("Debug"),
QLatin1String("ERROR"));
logLogger()->setLevel(OptionConverter::toLevel(value, Level::DEBUG_INT));
// Common layout
TTCCLayout *p_layout = new TTCCLayout();
p_layout->setName(QLatin1String("LogLog TTCC"));
p_layout->setContextPrinting(false);
p_layout->activateOptions();
// Common deny all filter
Filter *p_denyall = new DenyAllFilter();
p_denyall->activateOptions();
// ConsoleAppender on stdout for all events <= INFO
ConsoleAppender *p_appender;
LevelRangeFilter *p_filter;
p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET);
p_filter = new LevelRangeFilter();
p_filter->setNext(p_denyall);
p_filter->setLevelMin(Level::NULL_INT);
p_filter->setLevelMax(Level::INFO_INT);
p_filter->activateOptions();
p_appender->setName(QLatin1String("LogLog stdout"));
p_appender->addFilter(p_filter);
p_appender->activateOptions();
logLogger()->addAppender(p_appender);
// ConsoleAppender on stderr for all events >= WARN
p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDERR_TARGET);
p_filter = new LevelRangeFilter();
p_filter->setNext(p_denyall);
p_filter->setLevelMin(Level::WARN_INT);
p_filter->setLevelMax(Level::OFF_INT);
p_filter->activateOptions();
p_appender->setName(QLatin1String("LogLog stderr"));
p_appender->addFilter(p_filter);
p_appender->activateOptions();
logLogger()->addAppender(p_appender);
}
void LogManager::doStartup()
{
QMutexLocker locker(&instance()->mObjectGuard);
// Override
QString default_value = QLatin1String("false");
QString value = InitialisationHelper::setting(QLatin1String("DefaultInitOverride"),
default_value);
if (value != default_value)
{
static_logger()->debug("DefaultInitOverride is set. Aborting default initialisation");
return;
}
// Configuration using setting Configuration
value = InitialisationHelper::setting(QLatin1String("Configuration"));
if (QFile::exists(value))
{
static_logger()->debug("Default initialisation configures from file '%1' specified by Configure", value);
PropertyConfigurator::configure(value);
return;
}
// Configuration using setting
if (QCoreApplication::instance())
{
const QLatin1String log4qt_group("Log4Qt");
const QLatin1String properties_group("Properties");
QSettings s;
s.beginGroup(log4qt_group);
if (s.childGroups().contains(properties_group))
{
const QString group(QLatin1String("Log4Qt/Properties"));
static_logger()->debug("Default initialisation configures from setting '%1/%2'", log4qt_group, properties_group);
s.beginGroup(properties_group);
PropertyConfigurator::configure(s);
return;
}
}
// Configuration using default file
const QString default_file(QLatin1String("log4qt.properties"));
if (QFile::exists(default_file))
{
static_logger()->debug("Default initialisation configures from default file '%1'", default_file);
PropertyConfigurator::configure(default_file);
return;
}
static_logger()->debug("Default initialisation leaves package unconfigured");
}
void LogManager::welcome()
{
static_logger()->info("Initialising Log4Qt %1",
QLatin1String(LOG4QT_VERSION_STR));
// Debug: Info
if (static_logger()->isDebugEnabled())
{
// Create a nice timestamp with UTC offset
DateTime start_time = DateTime::fromMilliSeconds(InitialisationHelper::startTime());
QString offset;
{
QDateTime utc = start_time.toUTC();
QDateTime local = start_time.toLocalTime();
QDateTime local_as_utc = QDateTime(local.date(), local.time(), Qt::UTC);
int min = utc.secsTo(local_as_utc) / 60;
if (min < 0)
offset += QLatin1Char('-');
else
offset += QLatin1Char('+');
min = abs(min);
offset += QString::number(min / 60).rightJustified(2, QLatin1Char('0'));
offset += QLatin1Char(':');
offset += QString::number(min % 60).rightJustified(2, QLatin1Char('0'));
}
static_logger()->debug("Program startup time is %1 (UTC%2)",
start_time.toString(QLatin1String("ISO8601")),
offset);
static_logger()->debug("Internal logging uses the level %1",
logLogger()->level().toString());
}
// Trace: Dump settings
if (static_logger()->isTraceEnabled())
{
static_logger()->trace("Settings from the system environment:");
QString entry;
Q_FOREACH (entry, InitialisationHelper::environmentSettings().keys())
static_logger()->trace(" %1: '%2'",
entry,
InitialisationHelper::environmentSettings().value(entry));
static_logger()->trace("Settings from the application settings:");
if (QCoreApplication::instance())
{
const QLatin1String log4qt_group("Log4Qt");
const QLatin1String properties_group("Properties");
static_logger()->trace(" %1:", log4qt_group);
QSettings s;
s.beginGroup(log4qt_group);
Q_FOREACH (entry, s.childKeys())
static_logger()->trace(" %1: '%2'",
entry,
s.value(entry).toString());
static_logger()->trace(" %1/%2:", log4qt_group, properties_group);
s.beginGroup(properties_group);
Q_FOREACH (entry, s.childKeys())
static_logger()->trace(" %1: '%2'",
entry,
s.value(entry).toString());
} else
static_logger()->trace(" QCoreApplication::instance() is not available");
}
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
void LogManager::qtMessageHandler(QtMsgType type, const char *pMessage)
{
Level level;
switch (type)
{
case QtDebugMsg:
level = Level::DEBUG_INT;
break;
case QtWarningMsg:
level = Level::WARN_INT;
break;
case QtInfoMsg:
level = Level::INFO_INT;
break;
case QtCriticalMsg:
level = Level::ERROR_INT;
break;
case QtFatalMsg:
level = Level::FATAL_INT;
break;
default:
level = Level::TRACE_INT;
}
instance()->qtLogger()->log(level, pMessage);
// Qt fatal behaviour copied from global.cpp qt_message_output()
// begin {
if ((type == QtFatalMsg) ||
((type == QtWarningMsg) && (!qgetenv("QT_FATAL_WARNINGS").isNull())) )
{
#if defined(Q_CC_MSVC) && defined(QT_DEBUG) && defined(_DEBUG) && defined(_CRT_ERROR)
// get the current report mode
int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
_CrtSetReportMode(_CRT_ERROR, reportMode);
int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, QT_VERSION_STR, pMessage);
if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW)
return; // ignore
else if (ret == 1)
_CrtDbgBreak();
#endif
#if defined(Q_OS_UNIX) && defined(QT_DEBUG)
//abort(); // trap; generates core dump
#else
//exit(1); // goodbye cruel world
#endif
}
// } end
}
#else
void LogManager::qtMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
Level level;
switch (type)
{
case QtDebugMsg:
level = Level::DEBUG_INT;
break;
case QtWarningMsg:
level = Level::WARN_INT;
break;
case QtInfoMsg:
level = Level::INFO_INT;
break;
case QtCriticalMsg:
level = Level::ERROR_INT;
break;
case QtFatalMsg:
level = Level::FATAL_INT;
break;
default:
level = Level::TRACE_INT;
}
QString newMsg = context.file?QString("|PID:%1|%2:%3(%4)|").arg(getpid()).arg(context.file).arg(context.line).arg(context.function):QString("|PID:%1|").arg(getpid());
instance()->qtLogger()->log(level, newMsg+message);
emit instance()->qtLogger()->logOutput();
// Qt fatal behaviour copied from global.cpp qt_message_output()
// begin {
if ((type == QtFatalMsg) ||
((type == QtWarningMsg) && (!qgetenv("QT_FATAL_WARNINGS").isNull())) )
{
#if defined(Q_CC_MSVC) && defined(QT_DEBUG) && defined(_DEBUG) && defined(_CRT_ERROR)
// get the current report mode
int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
_CrtSetReportMode(_CRT_ERROR, reportMode);
int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, QT_VERSION_STR, message.toUtf8().constData());
if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW)
return; // ignore
else if (ret == 1)
_CrtDbgBreak();
#endif
#if defined(Q_OS_UNIX) && defined(QT_DEBUG)
//abort(); // trap; generates core dump
#else
//exit(1); // goodbye cruel world
#endif
}
// } end
}
#endif
LogManager *LogManager::mspInstance = 0;
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const LogManager &rLogManager)
{
Q_UNUSED(rLogManager); // To avoid warning C4100 on VS 2008
QList loggers = rLogManager.loggers();
debug.nospace() << "LogManager("
<< "loggerrepository:" << *rLogManager.loggerRepository()
<< "log-level:" << rLogManager.logLogger()->level().toString()
<< "log-appenders:" << rLogManager.logLogger()->appenders().count()
<< "qt-level:" << rLogManager.qtLogger()->level().toString()
<< "qt-appenders:" << rLogManager.qtLogger()->appenders().count()
<< "handleqtmessages:" << rLogManager.handleQtMessages()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/ndc.cpp 0000664 0001750 0001750 00000007632 15167726064 017124 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: ndc.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* changes Feb 2009, Martin Heinrich
* - Fixed VS 2008 unreferenced formal parameter warning by using
* Q_UNUSED in operator<<.
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/ndc.h"
#include
#include
#include
#include "log4qt/helpers/initialisationhelper.h"
#include "log4qt/logger.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt:NDC)
/**************************************************************************
* Class implementation: NDC
**************************************************************************/
void NDC::clear()
{
if (!instance()->mStack.hasLocalData())
return;
instance()->mStack.localData()->clear();
}
int NDC::depth()
{
if (!instance()->mStack.hasLocalData())
return 0;
return instance()->mStack.localData()->count();
}
LOG4QT_IMPLEMENT_INSTANCE(NDC)
QString NDC::pop()
{
if (!instance()->mStack.hasLocalData() || instance()->mStack.localData()->isEmpty())
{
logger()->warn("Requesting pop from empty NDC stack");
return QString();
}
return instance()->mStack.localData()->pop();
}
void NDC::push(const QString &rMessage)
{
if (!instance()->mStack.hasLocalData())
instance()->mStack.setLocalData(new QStack);
instance()->mStack.localData()->push(rMessage);
}
void NDC::setMaxDepth(int maxDepth)
{
if (!instance()->mStack.hasLocalData() ||
instance()->mStack.localData()->size() <= maxDepth)
return;
instance()->mStack.localData()->resize(maxDepth);
}
QString NDC::peek()
{
if (!instance()->mStack.hasLocalData() ||
instance()->mStack.localData()->isEmpty())
return QString();
return instance()->mStack.localData()->top();
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const NDC &rNDC)
{
Q_UNUSED(rNDC); // To avoid warning C4100 on VS 2008
debug.nospace() << "NDC("
<< "thread:" << QThread::currentThread()->objectName() << " "
<< "peek:" << rNDC.peek() << " "
<< "depth:" << rNDC.depth()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/logmanager.h 0000664 0001750 0001750 00000030334 15167726076 020137 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: logmanager.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOGMANAGER_H
#define LOG4QT_LOGMANAGER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include
#include
#include
#include
#include "log4qt/level.h"
#include "log4qt/logger.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class LoggerRepository;
/*!
* \brief The class LogManager manages Logger in the default
* LoggerRepository.
*
* The LogManager manages logger in a single Hierarchy instance. It
* provides access to special logger over the logLogger(), qtLogger()
* and rootLogger() member functions.
*
* The LogManager is handling the initialisation on startup. The
* initialisation procedure will first attempt to configure the package
* based on environment variables. If the attempt fails it will check for
* the existence of configuration files in several location. For detailed
* description of the initialisation procedure see \ref Init
* "Initialization procedure".
*
* Messages created by qDebug(), qWarning(), qCritical() and qFatal() can
* be can be handled by the LogManager. By default the message handling
* is disabled. It can be enabled by calling setHandleQtMessages(). Once
* enabled all messages are logged using the logger qtLogger().
*
* The Log4Qt runtime version is accessible over version(). The macros
* \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION" and
* \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR" provide the
* compile time version.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT LogManager
{
private:
LogManager();
LogManager(const LogManager &rOther); // Not implemented
virtual ~LogManager();
LogManager &operator=(const LogManager &rOther); // Not implemented
public:
/*!
* Returns if the handling of messages created by calls to qDebug(),
* qWarning(), qCritical() and qFatal() is activated.
*
* \sa setHandleQtMessages()
*/
static bool handleQtMessages();
static LoggerRepository *loggerRepository();
/*!
* Returns the logger used for logging internal messages. See
* \ref LogLog "Logging within the package" for more details.
*
* Calling this function is equivalent to calling logger("Log4Qt").
*/
static Logger *logLogger();
/*!
* Returns a pointer to the logger used for logging messages created by
* calls to qDebug(), qWarning(), qCritical() and qFatal().
*
* Calling this function is equivalent to calling logger("Qt").
*
* \sa setHandleQtMessages()
*/
static Logger *qtLogger();
static Logger *rootLogger();
static QList loggers();
static Level threshold();
static void setThreshold(Level level);
/*!
* Activates or deactivates the handling of messages created by calls
* to qDebug(), qWarning(), qCritical() and qFatal() is activated.
*
* If activated, a Qt message handler is installed. Messages are logged
* using the logger returned by qtLogger(). For fatal messages the same
* exit procedure is implemented as for qFatal().
*
* The following mappping is used from QtMsgType to Level:
*
*
*
*
QtMsgType
*
%Level
*
*
QtDebugMsg
*
Level::DEBUG_INT
*
*
QtWarningMsg
*
Level::WARN_INT
*
*
QtCriticalMsg
*
Level::ERROR_INT
*
*
QtFatalMsg
*
Level::FATAL_INT
*
*
QtSystemMsg
*
Level::TRACE_INT
*
*
*
* The default value is false for not handling Qt messages.
*
* \sa handleQtMessages(), qInstallMsgHandler(), qFatal()
*/
static void setHandleQtMessages(bool handleQtMessages);
/*!
* Configures the logging for the package to its default behaviour.
*
* The logger logLogger() is configured to be not additive. Messages
* with the level Level::ERROR_INT and Level::FATAL_INT are written
* to \c stderr using a ConsoleAppender. The remaining messages are
* written to \c stdout using a second ConsoleAppender. The level is
* read from the system environment or application settings using
* InitialisationHelper::setting() with the key \c Debug. If a level
* value is found, but it is not a valid Level string,
* Level::DEBUG_INT is used. If no level string is found
* Level::ERROR_INT is used.
*
* The function does not remove any appender from the logger
* logLogger().
*
* \sa \ref LogLog "Logging within the package",
* \ref Env "Environment Variables",
* resetConfiguration(), InitialisationHelper::setting()
*/
static void configureLogLogger();
static bool exists(const char *pName);
// JAVA: void fireAddAppenderEvent(Logger *pLogger, Appender *pAppender);
/*!
* Returns the LogManager instance.
*/
static LogManager *instance();
static Logger *logger(const QString &rName);
/*!
* Reset all values contained in logger repository to their default.
*
* All appenders are removed from all loggers. The loggers are handled
* in no particular order. The last loggers to be reset are qtLogger(),
* logLogger() and rootLogger() in that order.
*
* The handling of messages created by calls to qDebug(), qWarning(),
* qCritical() and qFatal() is deactivated.
*
* The internal logging is initialised to its default bahaviour
* using configureLogLogger().
*
* \sa LoggerRepository::resetConfiguration(), setHandleQtMessages(),
* configureLogLogger()
*/
static void resetConfiguration();
static void shutdown();
/*!
* Executes the default initialisation procedure of the package.
*
* The function will test for the setting \c DefaultInitOverride in
* the system environment and application settings using
* \ref InitialisationHelper::setting(). If the value is present and
* set to anything else then \c false, the initialisation is aborted.
*
* The system environment and application settings are tested for the
* setting \c Configuration. If it is found and it is a valid path to
* a file, the package is configured with the file using
* \ref PropertyConfigurator::doConfigure(const QString &, LoggerRepository *)
* "PropertyConfigurator::doConfigure()". If the setting
* \c Configuration is not available and a QCoreApplication object is
* present, the application settings are tested for a group
* \c Log4Qt/Properties. If the group exists, the package is configured
* with the setting using the
* \ref PropertyConfigurator::doConfigure(const QSettings &r, LoggerRepository *)
* "PropertyConfiguratordoConfigure()". If neither a configuration
* file nor configuration settings could be found, the current working
* directory is searched for the file \c "log4qt.properties". If it is
* found, the package is configured with the file using
* \ref PropertyConfigurator::doConfigure(const QString &, LoggerRepository *)
* "PropertyConfigurator::doConfigure()".
*
* \sa \ref Init "Initialization procedure",
* \ref Env "Environment Variables",
* InitialisationHelper::setting()
*/
static void startup();
/*!
* Returns the version number of Log4Qt at run-time. This may be a
* different version than the version the application was compiled
* against.
*
* \sa \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION",
* \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR"
*/
static const char* version();
private:
void doSetHandleQtMessages(bool handleQtMessages);
void doConfigureLogLogger();
void doStartup();
void welcome();
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
static void qtMessageHandler(QtMsgType type,
const char *pMessage);
#else
static void qtMessageHandler(QtMsgType type,
const QMessageLogContext &context,
const QString &message);
#endif
private:
#if QT_VERSION < 0x050E00
mutable QMutex mObjectGuard;
#else
mutable QRecursiveMutex mObjectGuard;
#endif
LoggerRepository *mpLoggerRepository;
Logger *mpNullLogger;
bool mHandleQtMessages;
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
QtMsgHandler mOldQtMsgHandler;
#else
QtMessageHandler mOldQtMsgHandler;
#endif
static LogManager *mspInstance;
};
/***************************************************************************
* Operators, Helper
***************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates LogManager
*
* Writes all object member variables to the given debug stream \a rDebug and
* returns the stream.
*
*
* %LogManager(loggerrepository:Hierarchy(loggers:6 root-level:"DEBUG"
* root-appenders:0 log-level: "NULL" log-appenders:0
* qt-level: "NULL" qt-appenders:0 handleqtmessages: false )
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const LogManager &rLogManager);
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Inline
**************************************************************************/
inline LoggerRepository *LogManager::loggerRepository()
{ // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime
return instance()->mpLoggerRepository; }
inline bool LogManager::handleQtMessages()
{ // QMutexLocker locker(&instance()->mObjectGuard); // Read/Write of bool is safe
return instance()->mHandleQtMessages; }
inline Logger *LogManager::logLogger()
{ // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime
return logger(QLatin1String("Log4Qt")); }
inline Logger *LogManager::qtLogger()
{ // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime
return logger(QLatin1String("Qt")); }
inline void LogManager::setHandleQtMessages(bool handleQtMessages)
{ instance()->doSetHandleQtMessages(handleQtMessages); }
inline void LogManager::configureLogLogger()
{ instance()->doConfigureLogLogger(); }
inline void LogManager::startup()
{ instance()->doStartup(); }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::LogManager, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_LOGMANAGER_H
ukui-interface/src/log4qt/log4qt/dailyrollingfileappender.cpp 0000664 0001750 0001750 00000041006 15167726076 023424 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: dailyrollingfileappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/dailyrollingfileappender.h"
#include
#include
#include
#include
#if QT_VERSION < 0x060000
#include
#endif
#include "log4qt/helpers/datetime.h"
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: DailyRollingFileAppender
**************************************************************************/
DailyRollingFileAppender::DailyRollingFileAppender(QObject *pParent) :
FileAppender(pParent),
mDatePattern()
{
setDatePattern(DAILY_ROLLOVER);
}
DailyRollingFileAppender::DailyRollingFileAppender(Layout *pLayout,
const QString &rFileName,
const QString &rDatePattern,
QObject *pParent) :
FileAppender(pLayout, rFileName, pParent),
mDatePattern()
{
setDatePattern(rDatePattern);
}
DailyRollingFileAppender::~DailyRollingFileAppender()
{
close();
}
void DailyRollingFileAppender::setDatePattern(DatePattern datePattern)
{
switch (datePattern)
{
case MINUTELY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-MM-dd-hh-mm"));
break;
case HOURLY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-MM-dd-hh"));
break;
case HALFDAILY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-MM-dd-a"));
break;
case DAILY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-MM-dd"));
break;
case WEEKLY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-ww"));
break;
case MONTHLY_ROLLOVER:
setDatePattern(QLatin1String("'.'yyyy-MM"));
break;
default:
Q_ASSERT_X(false, "DailyRollingFileAppender::setDatePattern()", "Invalid datePattern constant");
setDatePattern(DAILY_ROLLOVER);
};
}
void DailyRollingFileAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
computeFrequency();
if (!mActiveDatePattern.isEmpty())
{
#ifdef UKUILOG4QT_EXTRA_ENABLE
QFileInfo fileInfo(file());
if (!fileInfo.exists()) {
computeRollOverTime();
} else {
computeRollOverTime(fileInfo.birthTime().isNull()?fileInfo.lastModified():fileInfo.birthTime());
}
#else
computeRollOverTime();
#endif
FileAppender::activateOptions();
}
}
void DailyRollingFileAppender::append(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "DailyRollingFileAppender::append()", "Lock must be held by caller")
if (QDateTime::currentDateTime() > mRollOverTime)
rollOver();
FileAppender::append(rEvent);
}
void DailyRollingFileAppender::asyncAppend(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "DailyRollingFileAppender::asyncAppend()", "Lock must be held by caller")
if (QDateTime::currentDateTime() > mRollOverTime)
rollOver();
FileAppender::asyncAppend(rEvent);
}
bool DailyRollingFileAppender::checkEntryConditions() const
{
// Q_ASSERT_X(, "DailyRollingFileAppender::checkEntryConditions()", "Lock must be held by caller")
if (mActiveDatePattern.isEmpty())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without having a valid date pattern set"),
APPENDER_USE_INVALID_PATTERN_ERROR);
e << name();
logger()->error(e);
return false;
}
return FileAppender::checkEntryConditions();
}
#ifndef QT_NO_DEBUG_STREAM
QDebug DailyRollingFileAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
QString codec_name;
#if QT_VERSION < 0x060000
if (encoding())
codec_name = QLatin1String(encoding()->name());
#else
codec_name = QLatin1String(QStringConverter::nameForEncoding(encoding()));
#endif
rDebug.nospace() << "DailyRollingFileAppender("
<< "name:" << name() << " "
<< "activedatepattern:" << mActiveDatePattern << " "
<< "appendfile:" << appendFile() << " "
<< "bufferedio:" << bufferedIo() << " "
<< "datepattern:" << datePattern() << " "
<< "encoding:" << codec_name << " "
<< "frequency:" << frequencyToString() << " "
<< "file:" << file() << " "
<< "filter:" << firstFilter() << " "
<< "immediateflush:" << immediateFlush() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "referencecount:" << referenceCount() << " "
<< "rollovertime:" << mRollOverTime
<< "threshold:" << threshold().toString()
<< "writer:" << writer()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
void DailyRollingFileAppender::computeFrequency()
{
// Q_ASSERT_X(, "DailyRollingFileAppender::computeFrequency()", "Lock must be held by caller")
const DateTime start_time(QDate(1999, 1, 1), QTime(0, 0));
const QString start_string = start_time.toString(mDatePattern);
mActiveDatePattern.clear();
if (start_string != static_cast(start_time.addSecs(60)).toString(mDatePattern))
mFrequency = MINUTELY_ROLLOVER;
else if (start_string != static_cast(start_time.addSecs(60 * 60)).toString(mDatePattern))
mFrequency = HOURLY_ROLLOVER;
else if (start_string != static_cast(start_time.addSecs(60 * 60 * 12)).toString(mDatePattern))
mFrequency = HALFDAILY_ROLLOVER;
else if (start_string != static_cast(start_time.addDays(1)).toString(mDatePattern))
mFrequency = DAILY_ROLLOVER;
else if (start_string != static_cast(start_time.addDays(7)).toString(mDatePattern))
mFrequency = WEEKLY_ROLLOVER;
else if (start_string != static_cast(start_time.addMonths(1)).toString(mDatePattern))
mFrequency = MONTHLY_ROLLOVER;
else
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("The pattern '%1' does not specify a frequency for appender '%2'"),
APPENDER_INVALID_PATTERN_ERROR);
e << mDatePattern << name();
logger()->error(e);
return;
}
mActiveDatePattern = mDatePattern;
logger()->trace("Frequency set to %2 using date pattern %1",
mActiveDatePattern,
frequencyToString());
}
void DailyRollingFileAppender::computeRollOverTime(QDateTime startTime)
{
// Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller")
Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");
QDateTime now = startTime;
QDate now_date = now.date();
QTime now_time = now.time();
QDateTime start;
switch (mFrequency)
{
case MINUTELY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(now_time.hour(),
now_time.minute(),
0, 0));
mRollOverTime = start.addSecs(60);
}
break;
case HOURLY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(now_time.hour(),
0, 0, 0));
mRollOverTime = start.addSecs(60*60);
}
break;
case HALFDAILY_ROLLOVER:
{
int hour = now_time.hour();
if (hour >= 12)
hour = 12;
else
hour = 0;
start = QDateTime(now_date,
QTime(hour, 0, 0, 0));
mRollOverTime = start.addSecs(60*60*12);
}
break;
case DAILY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(0, 0, 0, 0));
mRollOverTime = start.addDays(1);
}
break;
case WEEKLY_ROLLOVER:
{
// QT numbers the week days 1..7. The week starts on Monday.
// Change it to being numbered 0..6, starting with Sunday.
int day = now_date.dayOfWeek();
if (day == Qt::Sunday)
day = 0;
start = QDateTime(now_date,
QTime(0, 0, 0, 0)).addDays(-1 * day);
mRollOverTime = start.addDays(7);
}
break;
case MONTHLY_ROLLOVER:
{
start = QDateTime(QDate(now_date.year(),
now_date.month(),
1),
QTime(0, 0, 0, 0));
mRollOverTime = start.addMonths(1);
}
break;
default:
Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant");
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
mRollOverTime = QDateTime::fromTime_t(0);
#else
mRollOverTime = QDateTime::fromSecsSinceEpoch(0);
#endif
}
mRollOverSuffix = static_cast(start).toString(mActiveDatePattern);
Q_ASSERT_X(static_cast(now).toString(mActiveDatePattern) == mRollOverSuffix,
"DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
Q_ASSERT_X(mRollOverSuffix != static_cast(mRollOverTime).toString(mActiveDatePattern),
"DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3",
now,
start,
mRollOverTime);
}
void DailyRollingFileAppender::computeRollOverTime()
{
// Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller")
Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");
QDateTime now = QDateTime::currentDateTime();
QDate now_date = now.date();
QTime now_time = now.time();
QDateTime start;
switch (mFrequency)
{
case MINUTELY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(now_time.hour(),
now_time.minute(),
0, 0));
mRollOverTime = start.addSecs(60);
}
break;
case HOURLY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(now_time.hour(),
0, 0, 0));
mRollOverTime = start.addSecs(60*60);
}
break;
case HALFDAILY_ROLLOVER:
{
int hour = now_time.hour();
if (hour >= 12)
hour = 12;
else
hour = 0;
start = QDateTime(now_date,
QTime(hour, 0, 0, 0));
mRollOverTime = start.addSecs(60*60*12);
}
break;
case DAILY_ROLLOVER:
{
start = QDateTime(now_date,
QTime(0, 0, 0, 0));
mRollOverTime = start.addDays(1);
}
break;
case WEEKLY_ROLLOVER:
{
// QT numbers the week days 1..7. The week starts on Monday.
// Change it to being numbered 0..6, starting with Sunday.
int day = now_date.dayOfWeek();
if (day == Qt::Sunday)
day = 0;
start = QDateTime(now_date,
QTime(0, 0, 0, 0)).addDays(-1 * day);
mRollOverTime = start.addDays(7);
}
break;
case MONTHLY_ROLLOVER:
{
start = QDateTime(QDate(now_date.year(),
now_date.month(),
1),
QTime(0, 0, 0, 0));
mRollOverTime = start.addMonths(1);
}
break;
default:
Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant");
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
mRollOverTime = QDateTime::fromTime_t(0);
#else
mRollOverTime = QDateTime::fromSecsSinceEpoch(0);
#endif
}
mRollOverSuffix = static_cast(start).toString(mActiveDatePattern);
Q_ASSERT_X(static_cast(now).toString(mActiveDatePattern) == mRollOverSuffix,
"DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
Q_ASSERT_X(mRollOverSuffix != static_cast(mRollOverTime).toString(mActiveDatePattern),
"DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3",
now,
start,
mRollOverTime);
}
QString DailyRollingFileAppender::frequencyToString() const
{
QMetaEnum meta_enum = metaObject()->enumerator(metaObject()->indexOfEnumerator("DatePattern"));
return QLatin1String(meta_enum.valueToKey(mFrequency));
}
void DailyRollingFileAppender::rollOver()
{
// Q_ASSERT_X(, "DailyRollingFileAppender::rollOver()", "Lock must be held by caller")
Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::rollOver()", "No active date pattern");
QString roll_over_suffix = mRollOverSuffix;
computeRollOverTime();
if (roll_over_suffix == mRollOverSuffix)
return;
closeFile();
QString target_file_name = file() + roll_over_suffix;
QFile f(target_file_name);
if (f.exists() && !removeFile(f))
return;
f.setFileName(file());
if (!renameFile(f, target_file_name))
return;
openFile();
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/mdc.cpp 0000664 0001750 0001750 00000006160 15167726064 017116 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: mdc.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* changes Feb 2009, Martin Heinrich
* - Fixed unreferenced formal parameter warning by using
* Q_UNUSED in operator<<.
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/mdc.h"
#include
#include
#include
#include "log4qt/helpers/initialisationhelper.h"
#include "log4qt/logger.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: MDC
**************************************************************************/
QString MDC::get(const QString &rKey)
{
if (!instance()->mHash.hasLocalData())
return QString();
return instance()->mHash.localData()->value(rKey);
}
QHash MDC::context()
{
if (!instance()->mHash.hasLocalData())
return QHash();
return *instance()->mHash.localData();
}
LOG4QT_IMPLEMENT_INSTANCE(MDC)
QHash *MDC::localData()
{
if (!instance()->mHash.hasLocalData())
instance()->mHash.setLocalData(new QHash);
return instance()->mHash.localData();
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const MDC &rMDC)
{
Q_UNUSED(rMDC); // To avoid warning C4100 on VS 2008
debug.nospace() << "MDC("
<< "thread:" << QThread::currentThread()->objectName() << " "
<< "context:" << rMDC.context()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/loggingevent.h 0000664 0001750 0001750 00000015744 15167726064 020520 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: loggingevent.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOG4QTEVENT_H
#define LOG4QT_LOG4QTEVENT_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include
#include
#include
#include
#include "log4qt/level.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class Logger;
/*!
* \brief The class LoggingEvent is the internal representation of a
* logging event.
*
* The class uses milliseconds since 1970-01-01T00:00:00, Coordinated
* Universal Time for time values. For converstion from and to QDateTime
* use DateTime.
*/
class LIBUKUILOG4QT_EXPORT LoggingEvent : public QEvent
{
public:
static const QEvent::Type eventId;
LoggingEvent();
LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage);
LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
qint64 timeStamp);
LoggingEvent(const Logger *pLogger,
Level level,
const QString &rMessage,
const QString &rNdc,
const QHash &rProperties,
const QString &rThreadName,
qint64 timeStamp);
// LoggingEvent(const LoggingEvent &LoggingEvent::rOther); // Use compiler default
// virtual ~LoggingEvent(); // Use compiler default
// LoggingEvent &operator=(const LoggingEvent &LoggingEvent::rOther); // Use compiler default
// JAVA: QString fqnOfLoggerClass() const;
Level level() const;
// LocationInformation locationInformation() const;
const Logger *logger() const;
QString message() const;
QHash mdc() const;
QString ndc() const;
QHash properties() const;
qint64 sequenceNumber() const;
QString threadName() const;
// JAVA: ThrowableInformation throwableInformation() const;
qint64 timeStamp() const;
// JAVA: bool locationInformationExists() const;
QString loggerName() const;
QString property(const QString &rKey) const;
QStringList propertyKeys() const;
void setProperty(const QString &rKey, const QString &rValue);
// JAVA: QString throwableStrRep() const;
QString toString() const;
static qint64 sequenceCount();
static qint64 startTime();
private:
void setThreadNameToCurrent();
static qint64 nextSequenceNumber();
private:
Level mLevel;
const Logger *mpLogger;
QString mMessage;
QString mNdc;
QHash mProperties;
qint64 mSequenceNumber;
QString mThreadName;
qint64 mTimeStamp;
static qint64 msSequenceCount;
#ifndef QT_NO_DATASTREAM
// Needs to be friend to stream objects
friend QDataStream &operator<<(QDataStream &rStream,
const LoggingEvent &rLoggingEvent);
friend QDataStream &operator>>(QDataStream &rStream,
LoggingEvent &rLoggingEvent);
#endif // QT_NO_DATASTREAM
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
/*!
* \relates LoggingEvent
*
* Writes the given error \a rLoggingEvent to the given stream \a rStream,
* and returns a reference to the stream.
*/
QDataStream &operator<<(QDataStream &rStream,
const LoggingEvent &rLoggingEvent);
/*!
* \relates LoggingEvent
*
* Reads an error from the given stream \a rStream into the given
* error \a rLoggingEvent, and returns a reference to the stream.
*/
QDataStream &operator>>(QDataStream &rStream,
LoggingEvent &rLoggingEvent);
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates LoggingEvent
*
* Writes all object member variables to the given debug stream \a debug and
* returns the stream.
*
*
* %LoggingEvent(level:"WARN" logger:"Log4Qt::Properties"
* message:"Unknown escape sequence '\j' in property starting at line 1"
* sequencenumber:14 threadname:"main"
* timestamp:1194337148937(QDateTime("Tue Nov 6 03:19:08 2007") )
* sequenceCount: 14 )
*
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const LoggingEvent &rLoggingEvent);
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Inline
**************************************************************************/
inline Level LoggingEvent::level() const
{ return mLevel; }
inline const Logger *LoggingEvent::logger() const
{ return mpLogger; }
inline QString LoggingEvent::message() const
{ return mMessage; }
inline QHash LoggingEvent::mdc() const
{ return mProperties; }
inline QString LoggingEvent::ndc() const
{ return mNdc; }
inline QHash LoggingEvent::properties() const
{ return mProperties; }
inline qint64 LoggingEvent::sequenceNumber() const
{ return mSequenceNumber; }
inline QString LoggingEvent::threadName() const
{ return mThreadName; }
inline qint64 LoggingEvent::timeStamp() const
{ return mTimeStamp; }
inline QString LoggingEvent::property(const QString &rKey) const
{ return mProperties.value(rKey); }
inline QStringList LoggingEvent::propertyKeys() const
{ return QStringList(mProperties.keys()); }
inline void LoggingEvent::setProperty(const QString &rKey, const QString &rValue)
{ mProperties.insert(rKey, rValue); }
} // namespace Log4Qt
Q_DECLARE_METATYPE(Log4Qt::LoggingEvent)
Q_DECLARE_TYPEINFO(Log4Qt::LoggingEvent, Q_MOVABLE_TYPE);
#endif // LOG4QT_LOG4QTEVENT_H
ukui-interface/src/log4qt/log4qt/dailyrollingfileappender.h 0000664 0001750 0001750 00000015274 15167726064 023076 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: dailyrollingfileappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_DAILYROLLINGFILEAPPENDER_H
#define LOG4QT_DAILYROLLINGFILEAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/fileappender.h"
#include "ukui-logmacros.h"
#include
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class DailyRollingFileAppender extends FileAppender so that the
* underlying file is rolled over at a specified frequency.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT DailyRollingFileAppender : public FileAppender
{
Q_OBJECT
/*!
* The property holds the date pattern used by the appender.
*
* The default is DAILY_ROLLOVER for rollover at midnight each day.
*
* \sa datePattern(), setDatePattern()
*/
Q_PROPERTY(QString datePattern READ datePattern WRITE setDatePattern)
public:
/*!
* The enum DatePattern defines constants for date patterns.
*
* \sa setDatePattern(DatePattern)
*/
enum DatePattern
{
/*! The minutely date pattern string is "'.'yyyy-MM-dd-hh-mm". */
MINUTELY_ROLLOVER = 0,
/*! The hourly date pattern string is "'.'yyyy-MM-dd-hh". */
HOURLY_ROLLOVER,
/*! The half-daily date pattern string is "'.'yyyy-MM-dd-a". */
HALFDAILY_ROLLOVER,
/*! The daily date pattern string is "'.'yyyy-MM-dd". */
DAILY_ROLLOVER,
/*! The weekly date pattern string is "'.'yyyy-ww". */
WEEKLY_ROLLOVER,
/*! The monthly date pattern string is "'.'yyyy-MM". */
MONTHLY_ROLLOVER
};
Q_ENUMS(DatePattern)
DailyRollingFileAppender(QObject *pParent = 0);
DailyRollingFileAppender(Layout *pLayout,
const QString &rFileName,
const QString &rDatePattern,
QObject *pParent = 0);
virtual ~DailyRollingFileAppender();
private:
DailyRollingFileAppender(const DailyRollingFileAppender &rOther); // Not implemented
DailyRollingFileAppender &operator=(const DailyRollingFileAppender &rOther); // Not implemented
public:
QString datePattern() const;
/*!
* Sets the datePattern to the value specified by the \a datePattern
* constant.
*/
void setDatePattern(DatePattern datePattern);
void setDatePattern(const QString &rDatePattern);
virtual void activateOptions();
protected:
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false. Otherwise the result of
* FileAppender::checkEntryConditions() is returned.
*
* The checked conditions are:
* - A valid pattern has been set (APPENDER_USE_INVALID_PATTERN_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by AppenderSkeleton::doAppend().
*
* \sa AppenderSkeleton::doAppend(),
* AppenderSkeleton::checkEntryConditions()
*/
virtual bool checkEntryConditions() const;
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %DailyRollingFileAppender(name:"DRFA" activedatepattern:"'.'yyyy-MM-dd-hh-mm"
* appendfile:false bufferedio:true
* datepattern:"'.'yyyy-MM-dd-hh-mm"
* encoding:"" frequency:"MINUTELY_ROLLOVER"
* file:"/log.txt" filter:0x0 immediateflush:true
* isactive:true isclosed:false layout:"TTCC"
* referencecount:1
* rollovertime:QDateTime("Mon Oct 22 05:23:00 2007")
* threshold: "NULL" writer: 0x0 )
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
private:
void computeFrequency();
void computeRollOverTime();
void computeRollOverTime(QDateTime startTime);
QString frequencyToString() const;
void rollOver();
private:
QString mDatePattern;
DatePattern mFrequency;
QString mActiveDatePattern;
QDateTime mRollOverTime;
QString mRollOverSuffix;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline QString DailyRollingFileAppender::datePattern() const
{ QMutexLocker locker(&mObjectGuard);
return mDatePattern; }
inline void DailyRollingFileAppender::setDatePattern(const QString &rDatePattern)
{ QMutexLocker locker(&mObjectGuard);
mDatePattern = rDatePattern; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::DailyRollingFileAppender, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_DAILYROLLINGFILEAPPENDER_H
ukui-interface/src/log4qt/log4qt/level.cpp 0000664 0001750 0001750 00000017620 15167726064 017465 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: level.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/level.h"
#include
#include
#include
#include "log4qt/logger.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::Level)
/**************************************************************************
* Class implementation: Level
**************************************************************************/
int Level::syslogEquivalent() const
{
// QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
switch (mValue)
{
case NULL_INT:
case ALL_INT:
case TRACE_INT:
case DEBUG_INT:
return 7;
case INFO_INT:
return 6;
case WARN_INT:
return 4;
case ERROR_INT:
return 3;
case FATAL_INT:
case OFF_INT:
return 0;
default:
Q_ASSERT_X(false, "Level::syslogEquivalent()", "Unknown level value");
return 7;
}
}
QString Level::toString() const
{
// QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
const char *p_context = "Level";
switch (mValue)
{
case NULL_INT:
return QCoreApplication::translate(p_context, "NULL");
case ALL_INT:
return QCoreApplication::translate(p_context, "ALL");
case TRACE_INT:
return QCoreApplication::translate(p_context, "TRACE");
case DEBUG_INT:
return QCoreApplication::translate(p_context, "DEBUG");
case INFO_INT:
return QCoreApplication::translate(p_context, "INFO");
case WARN_INT:
return QCoreApplication::translate(p_context, "WARN");
case ERROR_INT:
return QCoreApplication::translate(p_context, "ERROR");
case FATAL_INT:
return QCoreApplication::translate(p_context, "FATAL");
case OFF_INT:
return QCoreApplication::translate(p_context, "OFF");
default:
Q_ASSERT_X(false, "Level::toString()", "Unknown level value");
return QCoreApplication::translate(p_context, "NULL");
}
}
Level Level::fromString(const QString &rLevel, bool *pOk)
{
const char *p_context = "Level";
if (pOk)
*pOk = true;
#if 1
if (!rLevel.compare(QLatin1String("OFF"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "OFF"), Qt::CaseInsensitive))
return OFF_INT;
if (!rLevel.compare(QLatin1String("FATAL"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "FATAL"), Qt::CaseInsensitive))
return FATAL_INT;
if (!rLevel.compare(QLatin1String("ERROR"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "ERROR"), Qt::CaseInsensitive))
return ERROR_INT;
if (!rLevel.compare(QLatin1String("WARN"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "WARN"), Qt::CaseInsensitive))
return WARN_INT;
if (!rLevel.compare(QLatin1String("INFO"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "INFO"), Qt::CaseInsensitive))
return INFO_INT;
if (!rLevel.compare(QLatin1String("DEBUG"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "DEBUG"), Qt::CaseInsensitive))
return DEBUG_INT;
if (!rLevel.compare(QLatin1String("TRACE"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "TRACE"), Qt::CaseInsensitive))
return TRACE_INT;
if (!rLevel.compare(QLatin1String("ALL"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "ALL"), Qt::CaseInsensitive))
return ALL_INT;
if (!rLevel.compare(QLatin1String("NULL"), Qt::CaseInsensitive) ||
!rLevel.compare(QCoreApplication::translate(p_context, "NULL"), Qt::CaseInsensitive))
return NULL_INT;
logger()->warn("Use of invalid level string '%1'. Using 'Level::OFF_INT' instead.", rLevel);
if (pOk)
*pOk = false;
return OFF_INT;
#else
if (rLevel == QLatin1String("OFF") ||
rLevel == QCoreApplication::translate(p_context, "OFF"))
return OFF_INT;
if (rLevel == QLatin1String("FATAL") ||
rLevel == QCoreApplication::translate(p_context, "FATAL"))
return FATAL_INT;
if (rLevel == QLatin1String("ERROR") ||
rLevel == QCoreApplication::translate(p_context, "ERROR"))
return ERROR_INT;
if (rLevel == QLatin1String("WARN") ||
rLevel == QCoreApplication::translate(p_context, "WARN"))
return WARN_INT;
if (rLevel == QLatin1String("INFO") ||
rLevel == QCoreApplication::translate(p_context, "INFO"))
return INFO_INT;
if (rLevel == QLatin1String("DEBUG") ||
rLevel == QCoreApplication::translate(p_context, "DEBUG"))
return DEBUG_INT;
if (rLevel == QLatin1String("TRACE") ||
rLevel == QCoreApplication::translate(p_context, "TRACE"))
return TRACE_INT;
if (rLevel == QLatin1String("ALL") ||
rLevel == QCoreApplication::translate(p_context, "ALL"))
return ALL_INT;
if (rLevel == QLatin1String("NULL") ||
rLevel == QCoreApplication::translate(p_context, "NULL"))
return NULL_INT;
logger()->warn("Use of invalid level string '%1'. Using 'Level::NULL_INT' instead.", rLevel);
if (pOk)
*pOk = false;
return NULL_INT;
#endif
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &rStream,
const Level &rLevel)
{
quint8 l = rLevel.mValue;
rStream << l;
return rStream;
}
QDataStream &operator>>(QDataStream &rStream,
Level &rLevel)
{
quint8 l;
rStream >> l;
rLevel.mValue = (Level::Value)l;
return rStream;
}
#endif // QT_NO_DATASTREAM
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const Level &rLevel)
{
debug.nospace() << "Level("
<< rLevel.toString()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/ 0000775 0001750 0001750 00000000000 15167726064 016746 5 ustar feng feng ukui-interface/src/log4qt/log4qt/varia/denyallfilter.h 0000664 0001750 0001750 00000006372 15167726064 021765 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: denyallfilter.h
* created: September 2007
* author: Martin Heinrich
*
*
* changes Feb 2009, Martin Heinrich
* - Fixed a compile error on VS 2008 by using Q_UNUSED(&rEvent)
* instead of Q_UNUSED(rEvent)
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_DENYALLFILTER_H
#define LOG4QT_DENYALLFILTER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/spi/filter.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class DenyAllFilter drops all logging events
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT DenyAllFilter : public Filter
{
Q_OBJECT
public:
DenyAllFilter(QObject *pParent = 0);
// DenyAllFilter(const DenyAllFilter &rOther); // Use compiler default
// virtual ~DenyAllFilter(); // Use compiler default
// DenyAllFilter &operator=(const DenyAllFilter &rOther); // Use compiler default
virtual Decision decide(const LoggingEvent &rEvent) const;
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %DenyAllFilter(next:QObject(0x0) referencecount:1 )
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
};
/*************************************************************************
* Operators, Helper
*************************************************************************/
/*************************************************************************
* Inline
*************************************************************************/
inline DenyAllFilter::DenyAllFilter(QObject *pParent) :
Filter(pParent)
{}
inline Filter::Decision DenyAllFilter::decide(const LoggingEvent &rEvent) const
{ Q_UNUSED(&rEvent); return Filter::DENY; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::DenyAllFilter, Q_MOVABLE_TYPE); // Use default
#endif // LOG4QT_DENYALLFILTER_H
ukui-interface/src/log4qt/log4qt/varia/nullappender.cpp 0000664 0001750 0001750 00000005454 15167726064 022153 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: nullappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/nullappender.h"
#include
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: NullAppender
**************************************************************************/
NullAppender::NullAppender(QObject *pParent) :
AppenderSkeleton(false, pParent)
{
}
NullAppender::~NullAppender()
{
close();
}
void NullAppender::append(const LoggingEvent &rEvent)
{
Q_UNUSED(rEvent);
}
void NullAppender::asyncAppend(const LoggingEvent &rEvent)
{
Q_UNUSED(rEvent);
}
#ifndef QT_NO_DEBUG_STREAM
QDebug NullAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
rDebug.nospace() << "NullAppender("
<< "name:" << name() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "threshold:" << threshold().toString() << " "
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/debugappender.cpp 0000664 0001750 0001750 00000010610 15167726064 022255 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: debugappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/debugappender.h"
#include
#include
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
#if defined(Q_WS_WIN) || defined(Q_OS_WIN32)
#include
#endif
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: DebugAppender
**************************************************************************/
DebugAppender::DebugAppender(Layout *pLayout,
QObject *pParent) :
AppenderSkeleton(pParent)
{
setLayout(pLayout);
}
bool DebugAppender::requiresLayout() const
{
return true;
}
void DebugAppender::append(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "DebugAppender::append()", "Lock must be held by caller");
Q_ASSERT_X(layout(), "DebugAppender::append()", "Layout must not be null");
QString message(layout()->format(rEvent));
#if defined(Q_OS_WIN32) || defined(Q_WS_WIN)
#if (QT_VERSION < 0x050000)
QT_WA({
OutputDebugStringW(reinterpret_cast(message.utf16()));
}, {
OutputDebugStringA(message.toLocal8Bit().data());
});
#else
OutputDebugStringW(reinterpret_cast(message.utf16()));
#endif
#else
fprintf(stderr, "%s", message.toLocal8Bit().data());
fflush(stderr);
#endif
}
void DebugAppender::asyncAppend(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "DebugAppender::asyncAppend()", "Lock must be held by caller");
Q_ASSERT_X(layout(), "DebugAppender::asyncAppend()", "Layout must not be null");
QString message(layout()->format(rEvent));
#if defined(Q_OS_WIN32) || defined(Q_WS_WIN)
#if (QT_VERSION < 0x050000)
QT_WA({
OutputDebugStringW(reinterpret_cast(message.utf16()));
}, {
OutputDebugStringA(message.toLocal8Bit().data());
});
#else
OutputDebugStringW(reinterpret_cast(message.utf16()));
#endif
#else
fprintf(stderr, "%s", message.toLocal8Bit().data());
fflush(stderr);
#endif
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug DebugAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
rDebug.nospace() << "DebugAppender("
<< "name:" << name() << " "
<< "filter:" << firstFilter() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namspace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/listappender.h 0000664 0001750 0001750 00000012670 15167726064 021617 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: listappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LISTAPPENDER_H
#define LOG4QT_LISTAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appenderskeleton.h"
#include "ukui-logmacros.h"
#include
#include
#include "log4qt/loggingevent.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class ListAppender appends logging events to a list for later
* processing.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT ListAppender : public AppenderSkeleton
{
Q_OBJECT
/*!
* The property holds, if the Appender is used by a configurator.
*
* The default value is false for not being a configurator list.
*
* \sa configuratorList(), setConfiguratorList()
*/
Q_PROPERTY(bool configuratorList READ configuratorList WRITE setConfiguratorList)
/*!
* The property holds the maximum count used by the appender.
*
* The default maximum count is -1 for unlimited.
*
* \sa maxCount(), setMaxCount()
*/
Q_PROPERTY(int maxCount READ maxCount WRITE setMaxCount)
public:
ListAppender(QObject *pParent = 0);
virtual ~ListAppender();
private:
ListAppender(const ListAppender &rOther); // Not implemented
ListAppender &operator=(const ListAppender &rOther); // Not implemented
public:
/*!
* Returns true, if the appender is used by a configurator. Otherweise it returns
* false.
*
* \sa setConfiguratorList()
*/
bool configuratorList() const;
QList list() const;
int maxCount() const;
/*!
* Sets that the appender is used by a configurator. If set to true, the appender
* will not be removed from a Logger when Logger::removeAllAppenders()is called.
* This way the appender can collect events raised during the configuration process.
*
* \sa configuratorList(), BasicConfigurator, PropertyConfigurator,
* ConfiguratorHelper::configureError()
*/
void setConfiguratorList(bool isConfiguratorList);
void setMaxCount(int n);
QList clearList();
virtual bool requiresLayout() const;
protected:
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %ListAppender(name:"LA" count:1 filter:0x41fa488 isactive:true
* isclosed:false maxcount:170 referencecount:1
* threshold:"TRACE_SET")
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
/*!
* Ensures that the count of events is less or equal then the maxium
* count. If the list contains too many items, items are deleted from
* the begin of the list.
*/
void ensureMaxCount();
private:
volatile bool mConfiguratorList;
QList mList;
volatile int mMaxCount;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline bool ListAppender::configuratorList() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mConfiguratorList; }
inline int ListAppender::maxCount() const
{ return mMaxCount; }
inline void ListAppender::setConfiguratorList(bool isConfiguratorList)
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
mConfiguratorList = isConfiguratorList; }
inline bool ListAppender::requiresLayout() const
{ return false; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::ListAppender, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_LISTAPPENDER_H
ukui-interface/src/log4qt/log4qt/varia/levelmatchfilter.h 0000664 0001750 0001750 00000010161 15167726064 022450 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: levelmatchfilter.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LEVELMATCHFILTER_H
#define LOG4QT_LEVELMATCHFILTER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/spi/filter.h"
#include "ukui-logmacros.h"
#include "log4qt/level.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class LevelMatchFilter allows logging events with a specified
* level.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT LevelMatchFilter : public Filter
{
Q_OBJECT
/*!
* The property holds if an event is accpeted on a match.
*
* The default is true.
*
* \sa acceptOnMatch(), setAcceptOnMatch()
*/
Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch)
/*!
* The property holds the level to match for this filter.
*
* The default is Level::NULL_INT.
*
* \sa levelToMatch(), setLevelToMatch()
*/
Q_PROPERTY(Level levelToMatch READ levelToMatch WRITE setLevelToMatch)
public:
LevelMatchFilter(QObject *pParent = 0);
// LevelMatchFilter(const LevelMatchFilter &rOther); // Use compiler default
// virtual ~LevelMatchFilter(); // Use compiler default
// LevelMatchFilter &operator=(const LevelMatchFilter &rOther); // Use compiler default
bool acceptOnMatch() const;
Level levelToMatch() const;
void setAcceptOnMatch(bool accept);
void setLevelToMatch(Level level);
virtual Decision decide(const LoggingEvent &rEvent) const;
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %LevelMatchFilter(acceptonmatch:true leveltomatch:"WARN"
* next:Log4Qt::DenyAllFilter(0x3bce3a8)
* referencecount:1 )
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
private:
bool mAcceptOnMatch;
Level mLevelToMatch;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline bool LevelMatchFilter::acceptOnMatch() const
{ return mAcceptOnMatch; }
inline Level LevelMatchFilter::levelToMatch() const
{ return mLevelToMatch; }
inline void LevelMatchFilter::setAcceptOnMatch(bool accept)
{ mAcceptOnMatch = accept; }
inline void LevelMatchFilter::setLevelToMatch(Level level)
{ mLevelToMatch = level; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::LevelMatchFilter, Q_MOVABLE_TYPE); // Use default
#endif // LOG4QT_LEVELMATCHFILTER_H
ukui-interface/src/log4qt/log4qt/varia/stringmatchfilter.h 0000664 0001750 0001750 00000010212 15167726064 022644 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: stringmatchfilter.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_STRINGMATCHFILTER_H
#define LOG4QT_STRINGMATCHFILTER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/spi/filter.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class StringMatchFilter allows logging events with a
* specified level.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT StringMatchFilter : public Filter
{
Q_OBJECT
/*!
* The property holds if an event is accpeted on a match.
*
* The default is true.
*
* \sa acceptOnMatch(), acceptOnMatch()
*/
Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch)
/*!
* The property holds the string to match for this filter.
*
* \sa stringToMatch(), setStringToMatch()
*/
Q_PROPERTY(QString stringToMatch READ stringToMatch WRITE setStringToMatch)
public:
StringMatchFilter(QObject *pParent = 0);
// StringMatchFilter(const StringMatchFilter &rOther); // Use compiler default
// virtual ~StringMatchFilter(); // Use compiler default
// StringMatchFilter &operator=(const StringMatchFilter &rOther); // Use compiler default
bool acceptOnMatch() const;
QString stringToMatch() const;
void setAcceptOnMatch(bool accept);
void setStringToMatch(const QString &rString);
virtual Decision decide(const LoggingEvent &rEvent) const;
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %StringMatchFilter(acceptonmatch:true referencecount:1
* stringtomatch:"LDAP_STRONG_AUTH_REQUIRED"
* next:Log4Qt::LevelMatchFilter(0x3bdd960) )
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
private:
bool mAcceptOnMatch;
QString mStringToMatch;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline bool StringMatchFilter::acceptOnMatch() const
{ return mAcceptOnMatch; }
inline QString StringMatchFilter::stringToMatch() const
{ return mStringToMatch; }
inline void StringMatchFilter::setAcceptOnMatch(bool accept)
{ mAcceptOnMatch = accept; }
inline void StringMatchFilter::setStringToMatch(const QString &rString)
{ mStringToMatch = rString; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::StringMatchFilter, Q_MOVABLE_TYPE); // Use default
#endif // LOG4QT_STRINGMATCHFILTER_H
ukui-interface/src/log4qt/log4qt/varia/debugappender.h 0000664 0001750 0001750 00000010157 15167726064 021730 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: debugappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_DEBUGAPPENDER_H
#define LOG4QT_DEBUGAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appenderskeleton.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class DebugAppender appends logging events to the platform
* specific debug output.
*
* A DebugAppender appends to the Debugger on Windows and to stderr on all
* other systems.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT DebugAppender : public AppenderSkeleton
{
Q_OBJECT
public:
/*!
* Creates a DebugAppender.
*/
DebugAppender(QObject *pParent = 0);
/*!
* Creates a DebugAppender with the specified layout \a pLayout
*/
DebugAppender(Layout *pLayout,
QObject *pParent = 0);
// virtual ~DebugAppender(); // Use compiler default
private:
DebugAppender(const DebugAppender &rOther); // Not implemented
DebugAppender &operator=(const DebugAppender &rOther); // Not implemented
public:
/*!
* The DebugAppended requires a layout. The function returns true.
*
* \sa setLayout()
*/
virtual bool requiresLayout() const;
protected:
/*!
* Appends the specified logging event \a rEvent to the debug output.
* The output is formatted using the appender's layout.
*
* The method is called by the AppenderSkeleton::doAppend() after it
* the entry conditions have been tested and it has been found that the
* logging event needs to be appended.
*
* \sa setLayout(), AppenderSkeleton::doAppend(), checkEntryConditions()
*/
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %DebugAppender(name:"DA" filter:0x3bee6b8 isactive:true isclosed:false
* layout:"SL" referencecount:1 threshold:"NULL")
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline DebugAppender::DebugAppender(QObject *pParent) :
AppenderSkeleton(pParent)
{}
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::DebugAppender, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_DEBUGAPPENDER_H
ukui-interface/src/log4qt/log4qt/varia/stringmatchfilter.cpp 0000664 0001750 0001750 00000005477 15167726064 023220 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: stringmatchfilter.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/stringmatchfilter.h"
#include
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: Filter
**************************************************************************/
StringMatchFilter::StringMatchFilter(QObject *pParent) :
Filter(pParent),
mAcceptOnMatch(true),
mStringToMatch()
{}
Filter::Decision StringMatchFilter::decide(const LoggingEvent &rEvent) const
{
if (rEvent.message().isEmpty() ||
mStringToMatch.isEmpty() ||
rEvent.message().indexOf(mStringToMatch) < 0)
return Filter::NEUTRAL;
if (mAcceptOnMatch)
return Filter::ACCEPT;
else
return Filter::DENY;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug StringMatchFilter::debug(QDebug &rDebug) const
{
rDebug.nospace() << "StringMatchFilter("
<< "acceptonmatch:" << mAcceptOnMatch << " "
<< "referencecount:" << referenceCount() << " "
<< "stringtomatch:" << mStringToMatch << " "
<< "next:" << next()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/levelmatchfilter.cpp 0000664 0001750 0001750 00000005442 15167726064 023011 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: levelmatchfilter.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/levelmatchfilter.h"
#include
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: Filter
**************************************************************************/
LevelMatchFilter::LevelMatchFilter(QObject *pParent) :
Filter(pParent),
mAcceptOnMatch(true),
mLevelToMatch(Level::NULL_INT)
{}
Filter::Decision LevelMatchFilter::decide(const LoggingEvent &rEvent) const
{
if (mLevelToMatch == Level::NULL_INT ||
rEvent.level() != mLevelToMatch)
return Filter::NEUTRAL;
if (mAcceptOnMatch)
return Filter::ACCEPT;
else
return Filter::DENY;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug LevelMatchFilter::debug(QDebug &rDebug) const
{
rDebug.nospace() << "LevelMatchFilter("
<< "acceptonmatch:" << mAcceptOnMatch << " "
<< "leveltomatch:" << mLevelToMatch.toString() << " "
<< "next:" << next()
<< "referencecount:" << referenceCount() << " "
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/levelrangefilter.h 0000664 0001750 0001750 00000011044 15167726064 022451 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: levelrangefilter.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LEVELRANGEFILTER_H
#define LOG4QT_LEVELRANGEFILTER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/spi/filter.h"
#include "ukui-logmacros.h"
#include "log4qt/level.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class LevelMatchFilter allows logging events with levels in a
* specified range.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT LevelRangeFilter : public Filter
{
Q_OBJECT
/*!
* The property holds if an event is accpeted on a match.
*
* The default is true.
*
* \sa acceptOnMatch(), acceptOnMatch()
*/
Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch)
/*!
* The property holds the maximum level of the range for this filter.
*
* The default is Level::OFF_INT.
*
* \sa levelMax(), setLevelMax()
*/
Q_PROPERTY(Level levelMax READ levelMax WRITE setLevelMax)
/*!
* The property holds the minimum level of the range for this filter.
*
* The default is Level::NULL_INT.
*
* \sa levelMin(), setLevelMin()
*/
Q_PROPERTY(Level levelMin READ levelMin WRITE setLevelMin)
public:
LevelRangeFilter(QObject *pParent = 0);
// LevelRangeFilter(const LevelRangeFilter &rOther); // Use compiler default
// virtual ~LevelRangeFilter(); // Use compiler default
// LevelRangeFilter &operator=(const LevelRangeFilter &rOther); // Use compiler default
bool acceptOnMatch() const;
Level levelMax() const;
Level levelMin() const;
void setAcceptOnMatch(bool accept);
void setLevelMax(Level level);
void setLevelMin(Level level);
virtual Decision decide(const LoggingEvent &rEvent) const;
protected:
/*!
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %LevelRangeFilter(acceptonmatch:true levelmin:"ERROR" levelmax:"FATAL"
* next:Log4Qt::LevelMatchFilter(0x3bcd960)
* referencecount:1 )
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
private:
bool mAcceptOnMatch;
Level mLevelMin;
Level mLevelMax;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline bool LevelRangeFilter::acceptOnMatch() const
{ return mAcceptOnMatch; }
inline Level LevelRangeFilter::levelMax() const
{ return mLevelMax; }
inline Level LevelRangeFilter::levelMin() const
{ return mLevelMin; }
inline void LevelRangeFilter::setAcceptOnMatch(bool accept)
{ mAcceptOnMatch = accept; }
inline void LevelRangeFilter::setLevelMax(Level level)
{ mLevelMax = level; }
inline void LevelRangeFilter::setLevelMin(Level level)
{ mLevelMin = level; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::LevelRangeFilter, Q_MOVABLE_TYPE); // Use default
#endif // LOG4QT_LEVELRANGEFILTER_H
ukui-interface/src/log4qt/log4qt/varia/denyallfilter.cpp 0000664 0001750 0001750 00000004270 15167726064 022313 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: denyallfilter.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/denyallfilter.h"
#include
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: Filter
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug DenyAllFilter::debug(QDebug &rDebug) const
{
rDebug.nospace() << "DenyAllFilter("
<< "next:" << next()
<< "referencecount:" << referenceCount() << " "
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/nullappender.h 0000664 0001750 0001750 00000006020 15167726064 021606 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: nullappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_NULLAPPENDER_H
#define LOG4QT_NULLAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appenderskeleton.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class NullAppender ignores all requests to append.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT NullAppender : public AppenderSkeleton
{
Q_OBJECT
public:
NullAppender(QObject *pParent = 0);
virtual ~NullAppender();
private:
NullAppender(const NullAppender &rOther); // Not implemented
NullAppender &operator=(const NullAppender &rOther); // Not implemented
public:
virtual bool requiresLayout() const;
protected:
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream \a rDebug and
* returns the stream.
*
*
* %NullAppender()
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
};
/******************************************************************************
* Operators, Helper
******************************************************************************/
/******************************************************************************
* Inline
******************************************************************************/
inline bool NullAppender::requiresLayout() const
{ return false; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::NullAppender, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_NULLAPPENDER_H
ukui-interface/src/log4qt/log4qt/varia/levelrangefilter.cpp 0000664 0001750 0001750 00000005543 15167726064 023013 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: levelrangefilter.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/levelrangefilter.h"
#include
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/******************************************************************************
* Declarations
******************************************************************************/
/******************************************************************************
* C helper functions
******************************************************************************/
/******************************************************************************
* Class implementation: Filter
******************************************************************************/
LevelRangeFilter::LevelRangeFilter(QObject *pParent) :
Filter(pParent),
mAcceptOnMatch(true),
mLevelMin(Level::NULL_INT),
mLevelMax(Level::OFF_INT)
{}
Filter::Decision LevelRangeFilter::decide(const LoggingEvent &rEvent) const
{
if (rEvent.level() < mLevelMin)
return Filter::DENY;
if (rEvent.level() > mLevelMax)
return Filter::DENY;
if (mAcceptOnMatch)
return Filter::ACCEPT;
else
return Filter::NEUTRAL;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug LevelRangeFilter::debug(QDebug &rDebug) const
{
rDebug.nospace() << "LevelRangeFilter("
<< "acceptonmatch:" << mAcceptOnMatch << " "
<< "levelmin:" << mLevelMin.toString() << " "
<< "levelmax:" << mLevelMax.toString() << " "
<< "next:" << next()
<< "referencecount:" << referenceCount() << " "
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/******************************************************************************
* Implementation: Operators, Helper
******************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/varia/listappender.cpp 0000664 0001750 0001750 00000010005 15167726064 022140 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: listappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/varia/listappender.h"
#include
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: ListAppender
**************************************************************************/
ListAppender::ListAppender(QObject *pParent) :
AppenderSkeleton(pParent),
mConfiguratorList(false),
mList(),
mMaxCount(0)
{
}
ListAppender::~ListAppender()
{
}
QList ListAppender::list() const
{
QMutexLocker locker(&mObjectGuard);
return mList;
}
void ListAppender::setMaxCount(int n)
{
QMutexLocker locker(&mObjectGuard);
if (n < 0)
{
logger()->warn("Attempt to set maximum count for appender '%1' to %2. Using zero instead", name(), n);
n = 0;
}
mMaxCount = n;
ensureMaxCount();
}
QList ListAppender::clearList()
{
QMutexLocker locker(&mObjectGuard);
QList result = mList;
mList.clear();
return result;
}
// bool ListAppender::requiresLayout() const;
void ListAppender::append(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "ListAppender::append()", "Lock must be held by caller")
if ((mMaxCount <= 0) || (mList.size() < mMaxCount))
mList << rEvent;
}
void ListAppender::asyncAppend(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "ListAppender::asyncAppend()", "Lock must be held by caller")
if ((mMaxCount <= 0) || (mList.size() < mMaxCount))
mList << rEvent;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug ListAppender::debug(QDebug &rDebug) const
{
rDebug.nospace() << "ListAppender("
<< "name:" << name() << " "
<< "count:" << list().count() << " "
<< "filter:" << firstFilter() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "maxcount:" << maxCount() << " "
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
void ListAppender::ensureMaxCount()
{
// Q_ASSERT_X(, "ListAppender::ensureMaxCount()", "Lock must be held by caller")
if (mMaxCount <= 0)
return;
while (mList.size() > mMaxCount)
mList.removeFirst();
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/log4qt.pri 0000664 0001750 0001750 00000006767 15167726064 017612 0 ustar feng feng # *******************************************************************************
#
# package: Log4Qt
# file: log4qt.pri
# created: September 2007
# author: Martin Heinrich
#
#
# Copyright 2007 Martin Heinrich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# *******************************************************************************
INCLUDEPATH += $$PWD/..
DEPENDPATH += $$PWD/..
HEADERS += \
$$PWD/appender.h \
$$PWD/appenderskeleton.h \
$$PWD/basicconfigurator.h \
$$PWD/consoleappender.h \
$$PWD/dailyrollingfileappender.h \
$$PWD/fileappender.h \
$$PWD/helpers/classlogger.h \
$$PWD/helpers/configuratorhelper.h \
$$PWD/helpers/datetime.h \
$$PWD/helpers/factory.h \
$$PWD/helpers/initialisationhelper.h \
$$PWD/helpers/logerror.h \
$$PWD/helpers/logobject.h \
$$PWD/helpers/logobjectptr.h \
$$PWD/helpers/optionconverter.h \
$$PWD/helpers/patternformatter.h \
$$PWD/helpers/properties.h \
$$PWD/helpers/asyncdispatcher.h \
$$PWD/hierarchy.h \
$$PWD/layout.h \
$$PWD/level.h \
$$PWD/log4qt.h \
$$PWD/logger.h \
$$PWD/loggerrepository.h \
$$PWD/loggingevent.h \
$$PWD/logmanager.h \
$$PWD/mdc.h \
$$PWD/ndc.h \
$$PWD/patternlayout.h \
$$PWD/propertyconfigurator.h \
$$PWD/rollingfileappender.h \
$$PWD/simplelayout.h \
$$PWD/spi/filter.h \
$$PWD/ttcclayout.h \
$$PWD/writerappender.h \
$$PWD/varia/debugappender.h \
$$PWD/varia/denyallfilter.h \
$$PWD/varia/nullappender.h \
$$PWD/varia/levelmatchfilter.h \
$$PWD/varia/levelrangefilter.h \
$$PWD/varia/listappender.h \
$$PWD/varia/stringmatchfilter.h
SOURCES += \
$$PWD/appenderskeleton.cpp \
$$PWD/basicconfigurator.cpp \
$$PWD/consoleappender.cpp \
$$PWD/dailyrollingfileappender.cpp \
$$PWD/fileappender.cpp \
$$PWD/helpers/classlogger.cpp \
$$PWD/helpers/configuratorhelper.cpp \
$$PWD/helpers/datetime.cpp \
$$PWD/helpers/factory.cpp \
$$PWD/helpers/initialisationhelper.cpp \
$$PWD/helpers/logerror.cpp \
$$PWD/helpers/logobject.cpp \
$$PWD/helpers/logobjectptr.cpp \
$$PWD/helpers/optionconverter.cpp \
$$PWD/helpers/patternformatter.cpp \
$$PWD/helpers/properties.cpp \
$$PWD/helpers/asyncdispatcher.cpp \
$$PWD/hierarchy.cpp \
$$PWD/layout.cpp \
$$PWD/level.cpp \
$$PWD/log4qt.cpp \
$$PWD/logger.cpp \
$$PWD/loggerrepository.cpp \
$$PWD/loggingevent.cpp \
$$PWD/logmanager.cpp \
$$PWD/mdc.cpp \
$$PWD/ndc.cpp \
$$PWD/patternlayout.cpp \
$$PWD/propertyconfigurator.cpp \
$$PWD/rollingfileappender.cpp \
$$PWD/simplelayout.cpp \
$$PWD/spi/filter.cpp \
$$PWD/ttcclayout.cpp \
$$PWD/writerappender.cpp \
$$PWD/varia/debugappender.cpp \
$$PWD/varia/denyallfilter.cpp \
$$PWD/varia/nullappender.cpp \
$$PWD/varia/levelmatchfilter.cpp \
$$PWD/varia/levelrangefilter.cpp \
$$PWD/varia/listappender.cpp \
$$PWD/varia/stringmatchfilter.cpp
ukui-interface/src/log4qt/log4qt/fileappender.cpp 0000664 0001750 0001750 00000021753 15167726076 021021 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: fileappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/fileappender.h"
#include
#include
#include
#include
#include
#if QT_VERSION < 0x060000
#include
#endif
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: FileAppender
**************************************************************************/
FileAppender::FileAppender(QObject *pParent) :
WriterAppender(pParent),
mAppendFile(false),
mBufferedIo(true),
mFileName(),
mpFile(0),
mpTextStream(0)
{
}
FileAppender::FileAppender(Layout *pLayout,
const QString &rFileName,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mAppendFile(false),
mBufferedIo(true),
mFileName(rFileName),
mpFile(0),
mpTextStream(0)
{
}
FileAppender::FileAppender(Layout *pLayout,
const QString &rFileName,
bool append,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mAppendFile(append),
mBufferedIo(true),
mFileName(rFileName),
mpFile(0),
mpTextStream(0)
{
}
FileAppender::FileAppender(Layout *pLayout,
const QString &rFileName,
bool append,
bool buffered,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mAppendFile(append),
mBufferedIo(buffered),
mFileName(rFileName),
mpFile(0),
mpTextStream(0)
{
}
FileAppender::~FileAppender()
{
close();
}
void FileAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
if (mFileName.isEmpty())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires file and has no file set"),
APPENDER_ACTIVATE_MISSING_FILE_ERROR);
e << name();
logger()->error(e);
return;
}
closeFile();
openFile();
WriterAppender::activateOptions();
}
void FileAppender::close()
{
QMutexLocker locker(&mObjectGuard);
if (isClosed())
return;
WriterAppender::close();
closeFile();
}
bool FileAppender::checkEntryConditions() const
{
// Q_ASSERT_X(, "FileAppender::checkEntryConditions()", "Lock must be held by caller")
if (!mpFile || !mpTextStream)
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without open file"),
APPENDER_NO_OPEN_FILE_ERROR);
e << name();
logger()->error(e);
return false;
}
return WriterAppender::checkEntryConditions();
}
void FileAppender::closeFile()
{
// Q_ASSERT_X(, "FileAppender::closeFile()", "Lock must be held by caller")
if (mpFile)
logger()->debug("Closing file '%1' for appender '%2'", mpFile->fileName(), name());
setWriter(0);
delete mpTextStream;
mpTextStream = 0;
delete mpFile;
mpFile = 0;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug FileAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
QString codec_name;
#if QT_VERSION < 0x060000
if (encoding())
codec_name = QLatin1String(encoding()->name());
#else
codec_name = QLatin1String(QStringConverter::nameForEncoding(encoding()));
#endif
rDebug.nospace() << "FileAppender("
<< "name:" << name() << " "
<< "appendfile:" << appendFile() << " "
<< "bufferedio:" << bufferedIo() << " "
<< "encoding:" << codec_name << " "
<< "file:" << file() << " "
<< "filter:" << firstFilter() << " "
<< "immediateflush:" << immediateFlush() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString() << " "
<< "writer:" << writer()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
bool FileAppender::handleIoErrors() const
{
// Q_ASSERT_X(, "FileAppender::handleIoErrors()", "Lock must be held by caller")
if (mpFile->error() == QFile::NoError)
return false;
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to write to file '%1' for appender '%2'"),
APPENDER_WRITING_FILE_ERROR);
e << mFileName << name();
e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
logger()->error(e);
return true;
}
void FileAppender::openFile()
{
Q_ASSERT_X(mpFile == 0 && mpTextStream == 0, "FileAppender::openFile()", "Opening file without closing previous file");
QFileInfo file_info(mFileName);
QDir parent_dir = file_info.dir();
if (!parent_dir.exists())
{
logger()->trace("Creating missing parent directory for file %1", mFileName);
QString name = parent_dir.dirName();
parent_dir.cdUp();
parent_dir.mkdir(name);
}
mpFile = new QFile(mFileName);
QFile::OpenMode mode = QIODevice::WriteOnly | QIODevice::Text;
if (mAppendFile)
mode |= QIODevice::Append;
else
mode |= QIODevice::Truncate;
if (!mBufferedIo)
mode |= QIODevice::Unbuffered;
if (!mpFile->open(mode))
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"),
APPENDER_OPENING_FILE_ERROR);
e << mFileName << name();
e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
logger()->error(e);
return;
}
mpTextStream = new QTextStream(mpFile);
setWriter(mpTextStream);
logger()->debug("Opened file '%1' for appender '%2'", mpFile->fileName(), name());
}
bool FileAppender::removeFile(QFile &rFile) const
{
if (rFile.remove())
return true;
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to remove file '%1' for appender '%2'"),
APPENDER_REMOVE_FILE_ERROR);
e << rFile.fileName() << name();
e.addCausingError(LogError(rFile.errorString(), rFile.error()));
logger()->error(e);
return false;
}
bool FileAppender::renameFile(QFile &rFile,
const QString &rFileName) const
{
logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName);
if (!rFileName.compare(rFile.fileName()))
return true;
if (rFile.rename(rFileName))
return true;
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"),
APPENDER_RENAMING_FILE_ERROR);
e << rFile.fileName() << rFileName << name();
e.addCausingError(LogError(rFile.errorString(), rFile.error()));
logger()->error(e);
return false;
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/mdc.h 0000664 0001750 0001750 00000006444 15167726064 016570 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: mdc.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_MDC_H
#define LOG4QT_MDC_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include
#include
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class MDC implements a mapped diagnostic context.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT MDC
{
private:
MDC();
MDC(const MDC &rOther); // Not implemented
// virtual ~MDC(); // Use compiler default
MDC &operator=(const MDC &rOther); // Not implemented
public:
static QString get(const QString &rKey);
static QHash context();
/*!
* Returns the MDC instance.
*/
static MDC *instance();
static void put(const QString &rKey, const QString &rValue);
static void remove(const QString &rKey);
private:
static QHash *localData();
private:
QThreadStorage< QHash * > mHash;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates MDC
*
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
*
* %MDC(thread:"main" context:QHash(("login", "Peter")("database", "UAT")) )
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const MDC &rMDC);
#endif // QT_NO_DEBUG_STREAM
/**************************************************************************
* Inline
**************************************************************************/
inline MDC::MDC() :
mHash()
{}
inline void MDC::put(const QString &rKey, const QString &rValue)
{ localData()->insert(rKey, rValue); }
inline void MDC::remove(const QString &rKey)
{ localData()->remove(rKey); }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::MDC, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_MDC_H
ukui-interface/src/log4qt/log4qt/ndc.h 0000664 0001750 0001750 00000006414 15167726064 016566 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: ndc.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_NDC_H
#define LOG4QT_NDC_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include
#include
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class NDC implements a nested diagnostic context.
*
* The method remove() is not required. QThreadStorage cleans up on thread
* exit.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT NDC
{
private:
NDC();
NDC(const NDC &rOther); // Not implemented
// virtual ~NDC(); // Use compiler default
NDC &operator=(const NDC &rOther); // Not implemented
public:
static void clear();
// JAVA: static QStack cloneStack();
// JAVA: static QString get();
static int depth();
// JAVA: inherit(Stack stack)
/*!
* Returns the NDC instance.
*/
static NDC *instance();
static QString pop();
static void push(const QString &rMessage);
// JAVA: static void remove(); // Not required
static void setMaxDepth(int maxDepth);
static QString peek();
private:
QThreadStorage< QStack * > mStack;
};
/******************************************************************************
* Operators, Helper
******************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates NDC
*
* Writes all object member variables to the given debug stream \a rDebug and
* returns the stream.
*
*
* %NDC(thread:"main" peek:"i = 3" depth:4)
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const NDC &rNDC);
#endif // QT_NO_DEBUG_STREAM
/******************************************************************************
* Inline
******************************************************************************/
inline NDC::NDC() :
mStack()
{}
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::NDC, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_NDC_H
ukui-interface/src/log4qt/log4qt/appenderskeleton.cpp 0000664 0001750 0001750 00000016041 15167726076 021720 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: appenderskeleton.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appenderskeleton.h"
#include
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
#include "log4qt/logmanager.h"
#include "log4qt/spi/filter.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
***************************************************************************/
/*!
* \brief The class RecursionGuardLocker controls a boolean flag.
*
* It is a helper class to control a boolean flag. The class sets the flag
* on creation and resets it on destruction.
*/
class RecursionGuardLocker
{
public:
RecursionGuardLocker(bool *pGuard);
~RecursionGuardLocker();
private:
RecursionGuardLocker(const RecursionGuardLocker &rOther); // Not implemented
RecursionGuardLocker &operator=(const RecursionGuardLocker &rOther); // Not implemented
private:
bool *mpGuard;
};
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: RecursionGuardLocker
***************************************************************************/
inline RecursionGuardLocker::RecursionGuardLocker(bool *pGuard)
{
Q_ASSERT_X(pGuard != 0, "RecursionGuardLocker::RecursionGuardLocker()", "Pointer to guard bool must not be null");
mpGuard = pGuard;
*mpGuard = true;
}
inline RecursionGuardLocker::~RecursionGuardLocker()
{
*mpGuard = false;
};
/**************************************************************************
* Class implementation: AppenderSkeleton
**************************************************************************/
AppenderSkeleton::AppenderSkeleton(QObject *pParent) :
Appender(pParent),
#if QT_VERSION < 0x050E00
mObjectGuard(QMutex::Recursive), // Recursive for doAppend()
#endif
mAppendRecursionGuard(false),
mIsActive(true),
mIsClosed(false),
mpLayout(0),
mThreshold(Level::NULL_INT),
mpHeadFilter(0),
mpTailFilter(0)
{
}
AppenderSkeleton::AppenderSkeleton(const bool isActive,
QObject *pParent) :
Appender(pParent),
#if QT_VERSION < 0x050E00
mObjectGuard(QMutex::Recursive), // Recursive for doAppend()
#endif
mAppendRecursionGuard(false),
mIsActive(isActive),
mIsClosed(false),
mpLayout(0),
mThreshold(Level::NULL_INT),
mpHeadFilter(0),
mpTailFilter(0)
{
}
void AppenderSkeleton::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
if (requiresLayout() && !layout())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of appender '%1' that requires layout and has no layout set"),
APPENDER_ACTIVATE_MISSING_LAYOUT_ERROR);
e << name();
logger()->error(e);
return;
}
mIsActive = true;
}
void AppenderSkeleton::addFilter(Filter *pFilter)
{
if(!pFilter)
{
logger()->warn("Adding null Filter to Appender '%1'", name());
return;
}
QMutexLocker locker(&mObjectGuard);
mpTailFilter = pFilter;
if (mpHeadFilter)
mpHeadFilter->setNext(pFilter);
else
mpHeadFilter = pFilter;
}
void AppenderSkeleton::clearFilters()
{
QMutexLocker locker(&mObjectGuard);
mpTailFilter = 0;
mpHeadFilter = 0;
}
void AppenderSkeleton::close()
{
QMutexLocker locker(&mObjectGuard);
mIsClosed = true;
mIsActive = false;
}
void AppenderSkeleton::doAppend(const LoggingEvent &rEvent)
{
// The mutex serialises concurrent access from multiple threads.
// - e.g. two threads using the same logger
// - e.g. two threads using different logger with the same appender
//
// A call from the same thread will pass the mutex (QMutex::Recursive)
// and get to the recursion guard. The recursion guard blocks recursive
// invocation and prevents a possible endless loop.
// - e.g. an appender logs an error with a logger that uses it
QMutexLocker locker(&mObjectGuard);
if (mAppendRecursionGuard)
return;
RecursionGuardLocker recursion_locker(&mAppendRecursionGuard);
if (!checkEntryConditions())
return;
if (!isAsSevereAsThreshold(rEvent.level()))
return;
Filter *p_filter = mpHeadFilter;
while(p_filter)
{
Filter::Decision decision = p_filter->decide(rEvent);
if (decision == Filter::ACCEPT)
break;
else if (decision == Filter::DENY)
return;
else
p_filter = p_filter->next();
}
append(rEvent);
}
bool AppenderSkeleton::checkEntryConditions() const
{
// Q_ASSERT_X(, "WriterAppender::checkEntryConditions()", "Lock must be held by caller")
if (!isActive())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of non activated appender '%1'"),
APPENDER_NOT_ACTIVATED_ERROR);
e << name();
logger()->error(e);
return false;
}
if (isClosed())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of closed appender '%1'"),
APPENDER_CLOSED_ERROR);
e << name();
logger()->error(e);
return false;
}
if (requiresLayout() && !layout())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' that requires layout and has no layout set"),
APPENDER_USE_MISSING_LAYOUT_ERROR);
e << name();
logger()->error(e);
return false;
}
return true;
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/patternlayout.h 0000664 0001750 0001750 00000011170 15167726064 020730 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: patternlayout.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_PATTERNLAYOUT_H
#define LOG4QT_PATTERNLAYOUT_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/layout.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class PatternFormatter;
/*!
* \brief The class PatternLayout outputs a logging event based on a
* pattern string.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT PatternLayout : public Layout
{
Q_OBJECT
/*!
* The property holds the conversion pattern used by the appender.
*
* The default is "%m%n".
*
* \sa conversionPattern(), setConversionPattern()
*/
Q_PROPERTY(QString conversionPattern READ conversionPattern WRITE setConversionPattern)
public:
/*!
* The enum ConversionPattern defines constants for pattern strings.
*
* \sa setConversionPattern(ConversionPattern);
*/
enum ConversionPattern
{
/*! The default conversion pattern string is "%m,%n". */
DEFAULT_CONVERSION_PATTERN,
/*!
* The ttcc conversion pattern string is
* "%r [%t] %p %c %x - %m%n".
*/
TTCC_CONVERSION_PATTERN,
};
Q_ENUMS(ConversionPattern)
PatternLayout(QObject *pParent = 0);
PatternLayout(const QString &rPattern,
QObject *pParent = 0);
/*!
* Creates a PatternLayout with the conversion pattern value specified
* by the \a conversionPattern constant.
*/
PatternLayout(ConversionPattern conversionPattern,
QObject *pParent = 0);
virtual ~PatternLayout();
private:
PatternLayout(const PatternLayout &rOther); // Not implemented
PatternLayout &operator=(const PatternLayout &rOther); // Not implemented
public:
QString conversionPattern() const;
void setConversionPattern(const QString &rPattern);
/*!
* Sets the conversion pattern to the value specified by the
* \a conversionPattern constant.
*/
void setConversionPattern(ConversionPattern conversionPattern);
virtual QString format(const LoggingEvent &rEvent);
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %PatternLayout(name:"PL" pattern:"%r [%t] %p %c %x - %m%n"
* "referencecount:3")
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject)
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
private:
void updatePatternFormatter();
private:
QString mPattern;
PatternFormatter *mpPatternFormatter;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline QString PatternLayout::conversionPattern() const
{ return PatternLayout::mPattern; }
inline void PatternLayout::setConversionPattern(const QString &rPattern)
{ mPattern = rPattern;
updatePatternFormatter(); }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::PatternLayout, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_PATTERNLAYOUT_H
ukui-interface/src/log4qt/log4qt/writerappender.cpp 0000664 0001750 0001750 00000021012 15167726076 021402 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: writerappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/writerappender.h"
#include
#if QT_VERSION < 0x060000
#include
#endif
#include
#include
#include
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
#include "log4qt/helpers/asyncdispatcher.h"
extern pid_t g_MainProcPid;
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: WriterAppender
**************************************************************************/
WriterAppender::WriterAppender(QObject *pParent) :
AppenderSkeleton(false, pParent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::Utf8),
#endif
mpWriter(0),
mImmediateFlush(true)
{
}
WriterAppender::WriterAppender(Layout *pLayout,
QObject *pParent) :
AppenderSkeleton(false, pParent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mpWriter(0),
mImmediateFlush(true)
{
setLayout(pLayout);
}
WriterAppender::WriterAppender(Layout *pLayout,
QTextStream *pTextStream,
QObject *pParent) :
AppenderSkeleton(false, pParent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mpWriter(pTextStream),
mImmediateFlush(true)
{
setLayout(pLayout);
}
WriterAppender::~WriterAppender()
{
close();
}
#if QT_VERSION < 0x060000
void WriterAppender::setEncoding(QTextCodec *encoding)
#else
void WriterAppender::setEncoding(QStringConverter::Encoding encoding)
#endif
{
QMutexLocker locker(&mObjectGuard);
if (mEncoding == encoding)
return;
mEncoding = encoding;
if (mpWriter != nullptr)
{
#if QT_VERSION < 0x060000
if (mEncoding)
mpWriter->setCodec(mEncoding);
else
mpWriter->setCodec(QTextCodec::codecForLocale());
#else
mpWriter->setEncoding(mEncoding);
#endif
}
}
void WriterAppender::setWriter(QTextStream *pTextStream)
{
QMutexLocker locker(&mObjectGuard);
closeWriter();
mpWriter = pTextStream;
#if QT_VERSION < 0x060000
if ((mEncoding != nullptr) && (mpWriter != nullptr))
mpWriter->setCodec(mEncoding);
#else
if (mpWriter != nullptr)
mpWriter->setEncoding(mEncoding);
#endif
writeHeader();
}
void WriterAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
if (!writer())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires writer and has no writer set"),
APPENDER_ACTIVATE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return;
}
AppenderSkeleton::activateOptions();
}
void WriterAppender::close()
{
QMutexLocker locker(&mObjectGuard);
if (isClosed())
return;
closeInternal();
AppenderSkeleton::close();
closeWriter();
}
void WriterAppender::closeInternal()
{
if (isClosed())
return;
}
bool WriterAppender::requiresLayout() const
{
return true;
}
void WriterAppender::append(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "WriterAppender::append()", "Lock must be held by caller");
Q_ASSERT_X(layout(), "WriterAppender::append()", "Layout must not be null");
QString message(layout()->format(rEvent));
if (!mpWriter)
return;
*mpWriter << message;
if (handleIoErrors())
return;
if (immediateFlush())
{
mpWriter->flush();
if (handleIoErrors())
return;
}
}
void WriterAppender::asyncAppend(const LoggingEvent &rEvent)
{
// Q_ASSERT_X(, "WriterAppender::asyncAppend()", "Lock must be held by caller");
Q_ASSERT_X(layout(), "WriterAppender::asyncAppend()", "Layout must not be null");
QString message(layout()->format(rEvent));
if (!mpWriter)
return;
*mpWriter << message;
if (handleIoErrors())
return;
if (immediateFlush())
{
mpWriter->flush();
if (handleIoErrors())
return;
}
}
bool WriterAppender::checkEntryConditions() const
{
// Q_ASSERT_X(, "WriterAppender::checkEntryConditions()", "Lock must be held by caller")
if (!writer())
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without a writer set"),
APPENDER_USE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return false;
}
return AppenderSkeleton::checkEntryConditions();
}
void WriterAppender::closeWriter()
{
// Q_ASSERT_X(, "WriterAppender::closeWriter()", "Lock must be held by caller")
if (!mpWriter)
return;
writeFooter();
mpWriter = 0;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug WriterAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
QString codec_name;
#if QT_VERSION < 0x060000
if (encoding())
codec_name = QLatin1String(encoding()->name());
#else
codec_name = QLatin1String(QStringConverter::nameForEncoding(encoding()));
#endif
rDebug.nospace() << "WriterAppender("
<< "name:" << name() << " "
<< "encoding:" << codec_name << " "
<< "filter:" << firstFilter()
<< "immediateFlush:" << immediateFlush()
<< "isactive:" << isActive()
<< "isclosed:" << isClosed()
<< "layout:" << layout_name
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString()
<< "writer:" << writer()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
bool WriterAppender::handleIoErrors() const
{
return false;
}
void WriterAppender::writeFooter() const
{
// Q_ASSERT_X(, "WriterAppender::writeFooter()", "Lock must be held by caller")
if (!layout() || !mpWriter)
return;
QString footer = layout()->footer();
if (footer.isEmpty())
return;
*mpWriter << footer << Layout::endOfLine();
if (handleIoErrors())
return;
}
void WriterAppender::writeHeader() const
{
// Q_ASSERT_X(, "WriterAppender::writeHeader()", "Lock must be held by caller")
if (!layout() || !mpWriter)
return;
QString header = layout()->header();
if (header.isEmpty())
return;
*mpWriter << header << Layout::endOfLine();
if (handleIoErrors())
return;
}
/******************************************************************************
* Implementation: Operators, Helper
******************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/loggerrepository.cpp 0000664 0001750 0001750 00000004162 15167726064 021772 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: loggerrepository.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/loggerrepository.h"
#include
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: LoggerRepository
**************************************************************************/
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const LoggerRepository &rLoggerRepository)
{
return rLoggerRepository.debug(debug);
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/hierarchy.cpp 0000664 0001750 0001750 00000012717 15167726064 020336 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: hierarchy.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* changes: Sep 2008, Martin Heinrich:
* - Fixed problem in Qt 4.4 where QReadWriteLock is by default
* non-recursive.
*
*
* Copyright 2007 - 2008 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/hierarchy.h"
#include
#include "log4qt/logger.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(static_logger, Log4Qt::LoggerRepository)
/**************************************************************************
* Class implementation: Hierarchy
**************************************************************************/
Hierarchy::Hierarchy() :
#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0)
mObjectGuard(),
#else
mObjectGuard(QReadWriteLock::Recursive),
#endif
mLoggers(),
mThreshold(Level::NULL_INT),
mpRootLogger(logger(QString()))
{
// Store root logger to allow rootLogger() to be const
}
Hierarchy::~Hierarchy()
{
static_logger()->warn("Unexpected destruction of Hierarchy");
// QWriteLocker locker(&mObjectGuard);
//
// resetConfiguration();
// clear();
// delete mpRootLogger;
}
bool Hierarchy::exists(const QString &rName) const
{
QReadLocker locker(&mObjectGuard);
return mLoggers.contains(rName);
}
Logger *Hierarchy::logger(const QString &rName)
{
QWriteLocker locker(&mObjectGuard);
return createLogger(rName);
}
QList Hierarchy::loggers() const
{
QReadLocker locker(&mObjectGuard);
return mLoggers.values();
}
void Hierarchy::setThreshold(const QString &rThreshold)
{
setThreshold(Level::fromString(rThreshold));
}
void Hierarchy::resetConfiguration()
{
QWriteLocker locker(&mObjectGuard);
// Reset all loggers.
// Leave log, qt and root logger to the last to allow debugging of shutdown.
Logger *p_logging_logger = logger(QLatin1String("Log4Qt"));
Logger *p_qt_logger = logger(QLatin1String("Qt"));
Logger *p_root_logger = rootLogger();
Logger *p_logger;
Q_FOREACH(p_logger, mLoggers)
{
if ((p_logger == p_logging_logger) || (p_logger == p_qt_logger) || (p_logger == p_root_logger))
continue;
resetLogger(p_logger, Level::NULL_INT);
}
resetLogger(p_qt_logger, Level::NULL_INT);
resetLogger(p_logging_logger, Level::NULL_INT);
resetLogger(p_root_logger, Level::DEBUG_INT);
}
void Hierarchy::shutdown()
{
static_logger()->debug("Shutting down Hierarchy");
resetConfiguration();
}
#ifndef QT_NO_DEBUG_STREAM
QDebug Hierarchy::debug(QDebug &rDebug) const
{
rDebug.nospace() << "Hierarchy("
<< "loggers:" << loggers().count() << " "
<< "threshold:" << threshold().toString() << " "
<< "root-level:" << rootLogger()->level().toString() << " "
<< "root-appenders:" << rootLogger()->appenders().count()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
Logger *Hierarchy::createLogger(const QString &rName)
{
// Q_ASSERT_X(, "Hierarchy::createLogger", "Lock must be held by caller")
const QString name_separator = QLatin1String("::");
Logger *p_logger = mLoggers.value(rName, 0);
if (p_logger != 0)
return p_logger;
if (rName.isEmpty())
{
p_logger = new Logger(this, Level::DEBUG_INT, QLatin1String("root"), 0);
mLoggers.insert(QString(), p_logger);
return p_logger;
}
QString parent_name;
int index = rName.lastIndexOf(name_separator);
if (index >=0)
parent_name = rName.left(index);
p_logger = new Logger(this, Level::NULL_INT, rName, createLogger(parent_name));
mLoggers.insert(rName, p_logger);
return p_logger;
}
void Hierarchy::resetLogger(Logger *pLogger, Level level) const
{
// Q_ASSERT_X(, "Hierarchy::resetLogger", "Lock must be held by caller")
pLogger->removeAllAppenders();
pLogger->setAdditivity(true);
pLogger->setLevel(level);
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/loggerrepository.h 0000664 0001750 0001750 00000010416 15167726064 021436 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: loggerrepository.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOGGERREPOSITORY_H
#define LOG4QT_LOGGERREPOSITORY_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include "log4qt/level.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class Logger;
/*!
* \brief The class LoggerRepository is abstract base class for a logger
* repository.
*/
class LIBUKUILOG4QT_EXPORT LoggerRepository
{
public:
// LoggerRepository(); // Use compiler default
// LoggerRepository(const LoggerRepository &rOther); // Use compiler default
// virtual ~LoggerRepository(); // Use compiler default
// LoggerRepository &operator=(const LoggerRepository &rOther); // Use compiler default
public:
virtual bool exists(const QString &rName) const = 0;
virtual Logger *logger(const QString &rName) = 0;
// JAVA: virtual Logger *logger(const String &rName, LoggerFactory *pFactory);
virtual QList loggers() const = 0;
virtual Logger *rootLogger() const = 0;
virtual Level threshold() const = 0;
virtual void setThreshold(Level level) = 0;
virtual void setThreshold(const QString &rThreshold) = 0;
virtual bool isDisabled(Level level) = 0;
virtual void resetConfiguration() = 0;
virtual void shutdown() = 0;
// JAVA: virtual void addHierarchyEventListener(HierarchyEventListener *pEventListener);
// JAVA: virtual void emitNoAppenderWarning(Logger *plogger) const;
// JAVA: virtual void fireAddAppenderEvent(Logger *plogger, Appender *pAppender) const;
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
*\relates LoggerRepository
*
* Writes all object member variables to the given debug stream \a rDebug
* and returns the stream.
*
* The member function is used by
* QDebug operator<<(QDebug debug, const LoggerRepository &rLoggerRepository)
* to generate class specific output.
*
* \sa QDebug operator<<(QDebug debug, const LoggerRepository &rLoggerRepository)
*/
virtual QDebug debug(QDebug &rDebug) const = 0;
friend QDebug operator<<(QDebug debug,
const LoggerRepository &rLoggerRepository);
#endif
};
/******************************************************************************
* Operators, Helper
******************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates LoggerRepository
* Writes all object member variables to the given debug stream \a debug
* and returns the stream.
*
* To handle subclassing the function uses the virtual member function
* debug(). This allows each class to generate its own output.
*
* \sa QDebug, debug()
*/
QDebug operator<<(QDebug debug,
const LoggerRepository &rLoggerRepository);
#endif
/**************************************************************************
* Inline
**************************************************************************/
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::LoggerRepository, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_LOGGERREPOSITORY_H
ukui-interface/src/log4qt/log4qt/consoleappender.cpp 0000664 0001750 0001750 00000012035 15167726064 021532 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: consoleappender.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/consoleappender.h"
#include
#include
#include "log4qt/helpers/optionconverter.h"
#include "log4qt/layout.h"
#include "log4qt/loggingevent.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
* Class implementation: ConsoleAppender
**************************************************************************/
ConsoleAppender::ConsoleAppender(QObject *pParent) :
WriterAppender(pParent),
mTarget(STDOUT_TARGET),
mpTextStream(0)
{
}
ConsoleAppender::ConsoleAppender(Layout *pLayout,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mTarget(STDOUT_TARGET),
mpTextStream(0)
{
}
ConsoleAppender::ConsoleAppender(Layout *pLayout,
const QString &rTarget,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mTarget(STDOUT_TARGET),
mpTextStream(0)
{
setTarget(rTarget);
}
ConsoleAppender::ConsoleAppender(Layout *pLayout,
Target target,
QObject *pParent) :
WriterAppender(pLayout, pParent),
mTarget(target),
mpTextStream(0)
{
}
ConsoleAppender::~ConsoleAppender()
{
close();
}
QString ConsoleAppender::target() const
{
// QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
if (mTarget == STDOUT_TARGET)
return QLatin1String("STDOUT_TARGET");
else
return QLatin1String("STDERR_TARGET");
}
void ConsoleAppender::setTarget(const QString &rTarget)
{
bool ok;
Target target = (Target)OptionConverter::toTarget(rTarget, &ok);
if (ok)
setTarget(target);
}
void ConsoleAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
closeStream();
if (mTarget == STDOUT_TARGET)
mpTextStream = new QTextStream(stdout);
else
mpTextStream = new QTextStream(stderr);
setWriter(mpTextStream);
WriterAppender::activateOptions();
}
void ConsoleAppender::close()
{
QMutexLocker locker(&mObjectGuard);
if (isClosed())
return;
WriterAppender::close();
closeStream();
}
void ConsoleAppender::closeStream()
{
// Q_ASSERT_X(, "ConsoleAppender::closeStream()", "Lock must be held by caller")
setWriter(0);
delete mpTextStream;
mpTextStream = 0;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug ConsoleAppender::debug(QDebug &rDebug) const
{
QString layout_name;
if (layout())
layout_name = layout()->name();
QString target;
if (mTarget == STDOUT_TARGET)
target = QLatin1String("STDOUT");
else
target = QLatin1String("STDERR");
rDebug.nospace() << "ConsoleAppender("
<< "name:" << name() << " "
<< "filter:" << firstFilter() << " "
<< "isactive:" << isActive() << " "
<< "isclosed:" << isClosed() << " "
<< "layout:" << layout_name << " "
<< "target:" << target << " "
<< "referencecount:" << referenceCount() << " "
<< "threshold:" << threshold().toString()
<< ")";
return rDebug.space();
}
#endif // QT_NO_DEBUG_STREAM
/******************************************************************************
* Implementation: Operators, Helper
******************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/log4qt.cpp 0000664 0001750 0001750 00000003243 15167726064 017564 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: logging.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
/******************************************************************************
*Dependencies
******************************************************************************/
#include "log4qt/log4qt.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
/**************************************************************************
*Implementation: Operators, Helper
**************************************************************************/
} // namespace Log4Qt
ukui-interface/src/log4qt/log4qt/appenderskeleton.h 0000664 0001750 0001750 00000016471 15167726076 021374 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: appenderskeleton.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_APPENDERSKELETON_H
#define LOG4QT_APPENDERSKELETON_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appender.h"
#include
#include "log4qt/helpers/logobjectptr.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class Filter;
class Layout;
class Logger;
class LoggingEvent;
/*!
* \brief The class AppenderSkeleton implements general Appender functionality.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT AppenderSkeleton : public Appender
{
Q_OBJECT
/*!
* The property holds if the Appender has been activated.
*
* \sa isActive()
*/
Q_PROPERTY(bool isActive READ isActive)
/*!
* The property holds if the Appender has been closed.
*
* \sa isClosed()
*/
Q_PROPERTY(bool isClosed READ isClosed)
/*!
* The property holds the threshold level used by the Appender.
*
* \sa threshold(), setThreshold()
*/
Q_PROPERTY(Level threshold READ threshold WRITE setThreshold)
public:
AppenderSkeleton(QObject *pParent = 0);
protected:
AppenderSkeleton(const bool isActive,
QObject *pParent = 0);
public:
// virtual ~AppenderSkeleton(); Use compiler default
private:
AppenderSkeleton(const AppenderSkeleton &rOther); // Not implemented
AppenderSkeleton &operator=(const AppenderSkeleton &rOther); // Not implemented
public:
// JAVA: ErrorHandler* errorHandler();
virtual Filter *filter() const;
virtual Layout *layout() const;
bool isActive() const;
bool isClosed() const;
virtual QString name() const;
Level threshold() const;
// JAVA: void setErrorHandler(ErrorHandler *pErrorHandler);
virtual void setLayout(Layout *pLayout);
virtual void setName(const QString &rName);
void setThreshold(Level level);
virtual void activateOptions();
virtual void addFilter(Filter *pFilter);
virtual void clearFilters();
virtual void close();
/*!
* Performs checks and delegates the actuall appending to the subclass
* specific append() function.
*
* \sa append(), checkEntryConditions(), isAsSevereAsThreshold(), Filter
*/
virtual void doAppend(const LoggingEvent &rEvent);
// JAVA: void finalize();
Filter* firstFilter() const;
bool isAsSevereAsThreshold(Level level) const;
protected:
virtual void append(const LoggingEvent &rEvent) = 0;
virtual void asyncAppend(const LoggingEvent &rEvent) = 0;
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false.
*
* The checked conditions are:
* - That the appender has been activated (APPENDER_NOT_ACTIVATED_ERROR)
* - That the appender was not closed (APPENDER_CLOSED_ERROR)
* - That the appender has a layout set, if it requires one
* (logging_error(APPENDER_USE_MISSING_LAYOUT_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by doAppend(). The doAppend() function calls the subclass
* specific checkEntryConditions() function. The function checks the
* class specific conditions and calls checkEntryConditions() of
* it's parent class. The last function called is
* AppenderSkeleton::checkEntryConditions().
*
* \sa doAppend()
*/
virtual bool checkEntryConditions() const;
protected:
#if QT_VERSION < 0x050E00
mutable QMutex mObjectGuard;
#else
mutable QRecursiveMutex mObjectGuard;
#endif
private:
bool mAppendRecursionGuard;
volatile bool mIsActive;
volatile bool mIsClosed;
LogObjectPtr mpLayout;
Level mThreshold;
LogObjectPtr mpHeadFilter;
LogObjectPtr mpTailFilter;
// need AsyncDispatcher to call asyncAppend method
friend class AsyncDispatcher;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline Filter *AppenderSkeleton::filter() const
{ QMutexLocker locker(&mObjectGuard);
return mpHeadFilter; }
inline Layout *AppenderSkeleton::layout() const
{ QMutexLocker locker(&mObjectGuard);
return mpLayout; }
inline QString AppenderSkeleton::name() const
{ QMutexLocker locker(&mObjectGuard);
return objectName(); }
inline Level AppenderSkeleton::threshold() const
{ // QMutexLocker locker(&mObjectGuard); // Level is threadsafe
return mThreshold; }
inline void AppenderSkeleton::setLayout(Layout *pLayout)
{ QMutexLocker locker(&mObjectGuard);
mpLayout = pLayout; }
inline void AppenderSkeleton::setName(const QString &rName)
{ QMutexLocker locker(&mObjectGuard);
setObjectName(rName); }
inline void AppenderSkeleton::setThreshold(Level level)
{ // QMutexLocker locker(&mObjectGuard); // Level is threadsafe
mThreshold = level; }
inline bool AppenderSkeleton::isActive() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mIsActive; }
inline bool AppenderSkeleton::isClosed() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mIsClosed; }
inline Filter *AppenderSkeleton::firstFilter() const
{ QMutexLocker locker(&mObjectGuard);
return filter(); }
inline bool AppenderSkeleton::isAsSevereAsThreshold(Level level) const
{ // QMutexLocker locker(&mObjectGuard); // Level is threadsafe
return (mThreshold <= level); }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::AppenderSkeleton, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_APPENDERSKELETON_H
ukui-interface/src/log4qt/log4qt/layout.h 0000664 0001750 0001750 00000010635 15167726076 017342 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: layout.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LAYOUT_H
#define LOG4QT_LAYOUT_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/helpers/logobject.h"
#include "log4qt/helpers/logobjectptr.h"
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class LoggingEvent;
/*!
* \brief The class Layout is the base class for all layouts.
*
* \note The ownership and lifetime of objects of this class are managed. See
* \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT Layout : public LogObject
{
Q_OBJECT
/*!
* The property holds the content type of the layout.
*
* \sa contentType()
*/
Q_PROPERTY(QString footercontentType READ contentType)
/*!
* The property holds the footer used by the layout.
*
* \sa footer(), setFooter()
*/
Q_PROPERTY(QString footer READ footer WRITE setFooter)
/*!
* The property holds the header used by the layout.
*
* \sa header(), setHeader()
*/
Q_PROPERTY(QString header READ header WRITE setHeader)
public:
Layout(QObject *pParent = 0);
virtual ~Layout();
private:
Layout(const Layout &rOther); // Not implemented
Layout &operator=(const Layout &rOther); // Not implemented
public:
virtual QString contentType() const;
QString footer() const;
QString header() const;
// JAVA: virtual bool ignoresThrowable() const;
QString name() const;
void setFooter(const QString &rFooter);
void setHeader(const QString &rHeader);
void setName(const QString &rName);
// JAVA: void setIgnoresThrowable(bool) const;
virtual void activateOptions();
virtual QString format(const LoggingEvent &rEvent) = 0;
/*!
* Returns the end of line seperator for the operating system.
*
* Windows: \\r\\n
* Mac: \\r
* UNIX: \\n
*/
static QString endOfLine();
// Member variables
private:
QString mFooter;
QString mHeader;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline Layout::Layout(QObject *pParent) :
LogObject(pParent)
{}
inline Layout::~Layout()
{}
inline QString Layout::footer() const
{ return mFooter; }
inline QString Layout::header() const
{ return mHeader; }
inline QString Layout::name() const
{ return objectName(); }
inline void Layout::setFooter(const QString &rFooter)
{ mFooter = rFooter; }
inline void Layout::setHeader(const QString &rHeader)
{ mHeader = rHeader; }
inline void Layout::setName(const QString &rName)
{ setObjectName(rName); }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::Layout, Q_COMPLEX_TYPE); // Use default
#if QT_VERSION < 0x060000
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE);
#else
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_COMPLEX_TYPE);
#endif
// Qt6 compatibility: opaque pointer declared in appender.h
#endif // LOG4QT_LAYOUT_H
ukui-interface/src/log4qt/log4qt/log4qt.h 0000664 0001750 0001750 00000062764 15167726064 017246 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: logging.h
* created: September 2007
* author: Martin Heinrich
*
*
* changes: Sep 2008, Martin Heinrich:
* - Added a compile time version check for the Qt version
* Jan 2009, Martin Heinrich:
* - Updated documentation and version information for version 0.2
* Feb 2009, Martin Heinrich:
* - Updated version information for version 0.3
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_H
#define LOG4QT_H
/*!
* \mainpage
*
* %Log4Qt is a C++ port of the Apache Software Foundation Log4j package
* using the Trolltech Qt Framework.
*
* The documentation describes classes and methods that have been added or
* changed compared to Log4j.
*
* The following sections are describing the implementation in more detail:
* - \ref Changes "Differences to Log4j"
* - \ref Ownership "Object ownership"
* - \ref LogLog "Logging within the package"
* - \ref Init "Initialization procedure"
* - \ref Env "Environment Variables"
* - \ref Undocumented "Undocumented functions"
* - \ref Assumptions "Assumptions"
*
* \author Martin Heinrich
* \version 0.3 (January 2009)
*
*/
/*!
* \page Changes Differences to Log4j
*
* The following fundamental differences exist between %Log4Qt and Log4j:
*
* - As a JAVA package Log4j does not have to manage object ownership and
* lifetime in the same way then it is required in C++. For details on
* how object ownership is handled see \ref Ownership "Object ownership".
* - The package uses itself for its internal logging similar to Log4j 1.3.
* For details see \ref LogLog "Logging within the package".
* - The configuration using system properties was replaced with a combination
* of environment variables and application settings. For details see
* \ref Env "Environment Variables".
* - Custom levels are not supported.
* - Multiple Logger Repositories are not supported
*
* The following classes have been changed:
*
* - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton"
* - The procedure of checking, if logging is possible, originally used by
* \ref Log4Qt::WriterAppender "WriterAppender" was generalised and is used
* in \ref Log4Qt::AppenderSkeleton "AppenderSkeleton" and derived classes
* (\ref Log4Qt::AppenderSkeleton::checkEntryConditions() "checkEntryConditions()").
* - The \ref Log4Qt::AppenderSkeleton::doAppend() "doAppend()" member function will
* check the entry conditions by calling the sub-class specific
* \ref Log4Qt::AppenderSkeleton::checkEntryConditions() "checkEntryConditions()".
* If successful the sub-class specific
* \ref Log4Qt::AppenderSkeleton::append() "append()" function is called.
*
* - Configurator
* - Configure functions return a boolean indicating, if the configuration
* was successful.
* - Configure errors are accessible over
* \ref Log4Qt::ConfiguratorHelper::configureError()
* "ConfiguratorHelper::configureError()".
* - Watching for configuration file changes is a function performed
* centrally by the \ref Log4Qt::ConfiguratorHelper "ConfiguratorHelper".
* The class provides signals to notify on configuration change and errors.
* - The class \ref Log4Qt::PropertyConfigurator "PropertyConfigurator" was
* extended to be able to read configuration data from a QSettings object.
*
* - \ref Log4Qt::Level "Level"
* - A new value \ref Log4Qt::Level::NULL_INT "Level::NULL_INT" was
* introduced to indicate there is no level set.
*
* - \ref Log4Qt::Logger "Logger"
* - The method \ref Log4Qt::Logger::isEnabledFor() "isEnabledFor()"
* does also take the repository threshold into account.
* - Several overloaded convenience member function are available to log
* messages with arguments of different types.
* - Two macros, \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER"
* and \ref Log4Qt::LOG4QT_DECLARE_QCLASS_LOGGER "LOG4QT_DECLARE_QCLASS_LOGGER",
* allows retrieving and caching of a pointer to a logger object.
*
* - \ref Log4Qt::LogManager "LogManager"
* - A QtMessage handler can be installed via
* \ref Log4Qt::LogManager::setHandleQtMessages() "setHandleQtMessages()",
* to redirect all messages created by calls to qDebug(), qWarning(),
* qCritical() and qFatal() to a logger. The logger is named Qt and can be
* accessed using \ref Log4Qt::LogManager::qtLogger() "qtLogger()".
* - The initialisation procedure is available over a public method
* (\ref Log4Qt::LogManager::startup() "startup()").
* - The LogManager provides access to the logger used internally by the
* package (\ref Log4Qt::LogManager::logLogger() "logLogger()") and to
* its default initialisation procedure
* (\ref Log4Qt::LogManager::configureLogLogger() "configureLogLogger()").
*
* - \ref Log4Qt::WriterAppender "WriterAppender"
* - The class will call \ref Log4Qt::WriterAppender::handleIoErrors()
* "handleIoErrors()" after all I/O operations. Sub-classes should
* re-implement the function to handle errors.
*
* The following classes have been added:
*
* - An additional appender class, \ref Log4Qt::DebugAppender "DebugAppender",
* was added. The class appends logging events to the platform specific debug
* output.
* - Various helper class have been introduced:
* - \ref Log4Qt::ClassLogger "ClassLogger": The class ClassLogger provides
* logging for a QObject derived class.
* - \ref Log4Qt::ConfiguratorHelper "ConfiguratorHelper": The class
* ConfiguratorHelper provides a configuration file watch and last error
* for configurator classes.
* - \ref Log4Qt::DateTime "DateTime": The class DateTime provides extended
* functionality for QDateTime.
* - \ref Log4Qt::LogError "LogError": The class LogError represents an error.
* - \ref Log4Qt::Factory "Factory": The class Factory provides factories
* for Appender, Filter and Layout objects.
* - \ref Log4Qt::InitialisationHelper "InitialisationHelper": The class
* InitialisationHelper performs static initialisation tasks.
* - \ref Log4Qt::LogObject "LogObject": The class LogObject is the common
* base class for many classes in the package.
* - \ref Log4Qt::LogObjectPtr "LogObjectPtr": The class LogObjectPtr
* implements automatic reference counting for LogObject objects.
* - \ref Log4Qt::PatternFormatter "PatternFormatter": The class
* PatternFormatter formats a logging event based on a pattern string.
* - \ref Log4Qt::Properties "Properties": The class Properties implements a
* JAVA property hash.
*/
/*!
* \page Ownership Object ownership
*
* In difference to the JAVA Log4j package %Log4Qt must manage ownership and
* lifetime of the objects used. This is non trivial as objects are created
* and used in different ways.
*
* In general an object can be created explicitly for example an application
* may create Loggers, Appenders and Layouts during creation of a QApplication
* object. But they can also be automatically created by the package on
* startup using a \ref Log4Qt::PropertyConfigurator "PropertyConfigurator"
* configuration file. Objects may also be created the one way and then used
* the other. Object may be used by multiple other objects. A Layout for example
* may be used by multiple Appenders. Objects are also created from multiple
* threads. The creation may happen during static initialisation and the
* deletion during static de-initialization.
*
* The parent child model used by QObject cannot be used to handle this. It
* cannot automatically delete an object that is used by multiple others as
* for example an Appender used by multiple Loggers. In addition to this
* QObjects and their children must reside in the same thread. This would
* either mean to impose restriction on how objects can be created or to move
* objects to a specific thread.
*
* To allow an automatic deletion of not required objects the package
* implements reference counting for Appenders, Layouts and Filters. The
* reference counting is implemented in \ref Log4Qt::LogObject "LogObject",
* which is used as a common base class. The reference count can be explicitly
* changed using the methods \ref Log4Qt::LogObject::retain() "retain()" and
* \ref Log4Qt::LogObject::release() "release()". Alternatively an auto pointer
* is available \ref Log4Qt::LogObjectPtr "LogObjectPtr", which is used
* throughout the package.
*
* The reference counting mechanism will test, if an object has a QObject
* parent object set. If a parent is set, the object will not be deleted, if
* the reference count reaches 0. This allows to mix the reference counted
* paradigm with the QObject parent child one.
*
* The following example configures a logger and uses reference counting to
* manage the ownership of objects.
*
* \code
* // Create layout
* TTCCLayout *p_layout = new TTCCLayout();
*
* // Create appender
* ConsoleAppender *p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET);
* p_appender->activateOptions();
*
* // Get logger
* Logger *p_logger = Logger::logger("MyClass");
* p_logger->addAppender(p_appender);
*
* // ...
*
* // Remove appender from Logger
* p_logger->removeAllAppenders(); // p_appender and p_layout are deleted here
* \endcode
*
* The following example configures a logger and uses QObject ownership of
* objects.
*
* \code
* QObject *p_parent = new MyObject;
*
* // Create objects
* ConsoleAppender *p_appender = new ConsoleAppender(p_parent);
* TTCCLayout *p_layout = new TTCCLayout(p_appender);
*
* // Configure appender
* p_appender->setTarget(ConsoleAppender::STDOUT_TARGET);
* p_appender->setLayout(p_layout);
* p_appender->activateOptions();
*
* // Get logger
* Logger *p_logger = Logger::logger("MyClass");
* p_logger->addAppender(p_appender);
*
* // ...
*
* // Remove appender from Logger
* p_logger->removeAllAppenders();
*
* delete p_parent; // p_appender and p_layout are deleted here
* \endcode
*
* The following example shows how to use objects created on the stack.
*
* \code
* {
* // Create layout
* TTCCLayout layout;
* layout.retain();
*
* // Create appender
* ConsoleAppender appender(&layout, ConsoleAppender::STDOUT_TARGET);
* appender.retain();
* appender.activateOptions();
*
* // Get logger
* Logger *p_logger = Logger::logger("MyClass");
* p_logger->addAppender(&appender);
*
* // ...
*
* // Remove appender from Logger
* p_logger->removeAllAppenders(); // Without retain() program crashes here
*
* } // p_appender and p_layout are deleted here
* \endcode
*/
/*!
* \page LogLog Logging within the package
*
* The package uses itself for logging similar to Log4j 1.3. This brings much
* more flexibility over logging to stdout, stderr like in Log4j 1.2 using
* logLog. It also enables the program to capture and handle errors raised by
* the package.
*
* Using this approach introduces the issue of recursion. The following example
* explains a situation where this happens. Let's say all logger are configured
* to be additive and only the root logger has an appender set. The appender
* is a \ref Log4Qt::FileAppender "FileAppender". During the logging of an
* event an I/O error occurs. The \ref Log4Qt::FileAppender "FileAppender" logs
* an event by itself using the logger %Log4Qt::FileAppender. The event is
* passed to the root logger, which calls then the \ref Log4Qt::FileAppender
* "FileAppender". This causes another I/O error, which is logged by
* the \ref Log4Qt::FileAppender "FileAppender".
*
* To avoid an endless loop the appender will drop the event on a recursive
* invocation. This check is done by \ref Log4Qt::AppenderSkeleton
* "AppenderSkeleton" in \ref Log4Qt::AppenderSkeleton::doAppend()
* "doAppend()".
*
* The problem only occurs, if a logger, appender, layout or filter log an
* event while an event is appended. Neither the logger class nor any of the
* layout or filter classes log events during appending of an event. Most of
* the appender classes may log errors during appending. Only the
* \ref Log4Qt::ListAppender "ListAppender" and
* \ref Log4Qt::ListAppender "ConsoleAppender" are not logging events.
*
* The default configuration uses two \ref Log4Qt::ListAppender
* "ConsoleAppender", one for stderr and one for stdout. No event will be
* dropped, because no recursive invocations can occur.
*/
/*!
* \page Init Initialization procedure
*
* The package is initialised in two stages. The first stage takes place during
* static initialization. The second stage takes place when the
* \ref Log4Qt::LogManager "LogManager" singleton is created.
*
* During static initialisation the \ref Log4Qt::InitialisationHelper
* "InitialisationHelper" singleton is created . On construction it captures
* the program startup time, reads the required values from the system
* environment and registers the package types with the Qt type system.
*
* The \ref Log4Qt::LogManager "LogManager" singleton is created on first use.
* The creation is usually triggered by the request for a \ref Log4Qt::Logger
* "Logger" object. The call to \ref Log4Qt::Logger::logger()
* "Logger::logger()" is passed through to \ref Log4Qt::LogManager::logger()
* "LogManager::logger()". On creation the \ref Log4Qt::LogManager "LogManager"
* creates a \ref Log4Qt::Hierarchy "Hierarchy" object as logger repository.
*
* After the singleton is created the logging of the package is configured to
* its default by a call to \ref Log4Qt::LogManager::configureLogLogger()
* "LogManager::configureLogLogger()". The logger
* \ref Log4Qt::LogManager::logLogger() "logLogger()" is configured to be not
* additive. Messages with the level \ref Log4Qt::Level::ERROR_INT
* "Level::ERROR_INT" and \ref Log4Qt::Level::FATAL_INT "Level::FATAL_INT" are
* written to \c stderr using a ConsoleAppender. The remaining messages are
* written to \c stdout using a second ConsoleAppender. The level is read from
* the system environment or application settings using
* \ref Log4Qt::InitialisationHelper::setting()
* "InitialisationHelper::setting()" with the key \c Debug. If a level value
* is found, but it is not a valid Level string,
* \ref Log4Qt::Level::DEBUG_INT "Level::DEBUG_INT" is used. If no level string
* is found \ref Log4Qt::Level::ERROR_INT "Level::ERROR_INT" is used.
*
* Once the logging is configured the package is initialised by a call to
* \ref Log4Qt::LogManager::startup() "LogManager::startup()". The function
* will test for the setting \c DefaultInitOverride in the system environment
* and application settings using \ref Log4Qt::InitialisationHelper::setting()
* "InitialisationHelper::setting()". If the value is present and set to
* anything else then \c false, the initialisation is aborted.
* The system environment and application settings are tested for the setting
* \c Configuration. If it is found and it is a valid path to a file, the
* package is configured with the file using
* \ref Log4Qt::PropertyConfigurator::doConfigure(const QString &, LoggerRepository *)
* "PropertyConfigurator::doConfigure()". If the setting \c Configuration is
* not available and a QCoreApplication object is present, the application
* settings are tested for a group \c Log4Qt/Properties. If the group exists,
* the package is configured with the setting using the
* \ref Log4Qt::PropertyConfigurator::doConfigure(const QSettings &r, LoggerRepository *)
* "PropertyConfiguratordoConfigure()". If neither a configuration file nor
* configuration settings could be found, the current working directory is
* searched for the file \c "log4qt.properties". If it is found, the package
* is configured with the file using
* \ref Log4Qt::PropertyConfigurator::doConfigure(const QString &, LoggerRepository *)
* "PropertyConfigurator::doConfigure()".
*
* The following example shows how to use application settings to initialise the
* package.
*
* \code
* # file: myapplication.h
*
* #include qapplication.h
*
* class MyApplication : public QApplication
* {
* Q_OBJECT
*
* public:
* MyApplication();
* ~MyApplication();
* void setupLog4Qt();
* }
* \endcode
* \code
* # file: myapplication.cpp
*
* #include myapplication.h
*
* MyApplication::MyApplication(
* {
* // Set Application data to allow Log4Qt initialisation to read the
* // correct values
* setApplicationName("MyApplication");
* setOrganisationName("MyOrganisation");
* setOrganizationDomain("www.myorganisation.com");
*
* // Log first message, which initialises Log4Qt
* Log4Qt::Logger::logger("MyApplication")->info("Hello World");
* }
*
* MyApplication::~MyApplication()
* {
* }
*
* void MyApplication::setupLog4Qt()
* {
* QSettings s;
*
* // Set logging level for Log4Qt to TRACE
* s.beginGroup("Log4Qt");
* s.setValue("Debug", "TRACE");
*
* // Configure logging to log to the file C:/myapp.log using the level TRACE
* s.beginGroup("Properties");
* s.setValue("log4j.appender.A1", "org.apache.log4j.FileAppender");
* s.setValue("log4j.appender.A1.file", "C:/myapp.log");
* s.setValue("log4j.appender.A1.layout", "org.apache.log4j.TTCCLayout");
* s.setValue("log4j.appender.A1.layout.DateFormat", "ISO8601");
* s.setValue("log4j.rootLogger", "TRACE, A1");
*
* // Settings will become active on next application startup
* }
* \endcode
*/
/*!
* \page Env Environment Variables
*
* The package uses environment variables to control the initialization
* procedure. The environment variables replace the system property entries
* used by Log4j.
*
* For compability reasons the Log4j entry is recognised. Alternatively a
* environment variable style Log4Qt form can be used. The following entries
* are used:
*
* - LOG4QT_DEBUG
* The variable controls the \ref Log4Qt::Level "Level" value for the
* logger \ref Log4Qt::LogManager::logLogger() "LogManager::logLogger()".
* If the value is a valid \ref Log4Qt::Level "Level" string, the level for
* the is set to the level. If the value is not a valid
* \ref Log4Qt::Level "Level" string, \ref Log4Qt::Level::DEBUG_INT
* "DEBUG_INT" is used. Otherwise \ref Log4Qt::Level::ERROR_INT "ERROR_INT"
* is used.
* - \ref Log4Qt::LogManager::configureLogLogger()
* "LogManager::configureLogLogger()"
*
* - LOG4QT_DEFAULTINITOVERRIDE
* The variable controls the \ref Init "initialization procedure" performed
* by the \ref Log4Qt::LogManager "LogManager" on startup. If it is set to
* any other value then \c false the \ref Init "initialization procedure"
* is skipped.
* - \ref Log4Qt::LogManager::startup() "LogManager::startup()"
*
* - LOG4QT_CONFIGURATION
* The variable specifies the configuration file used for initialising the
* package.
* - \ref Log4Qt::LogManager::startup() "LogManager::startup()"
*
* - LOG4QT_CONFIGURATORCLASS
* The variable specifies the configurator class used for initialising the
* package.
*
* Environment variables are read during static initialisation on creation of
* the \ref Log4Qt::InitialisationHelper "InitialisationHelper". They can be
* accessed by calling \ref Log4Qt::InitialisationHelper::environmentSettings()
* "InitialisationHelper::environmentSettings()".
*
* All settings can also be made in the application settings under the group
* \c %Log4Qt. For example the environment variable \c LOG4QT_DEBUG is
* equivalent to the setting \c Log4Qt/Debug. If an environment variable is
* set it takes precedence over the application setting. Settings are only
* used, if an QApplication object is available, when the
* \ref Log4Qt::LogManager "LogManager" is
* initialised (see \ref Log4Qt::InitialisationHelper::setting()
* "InitialisationHelper::setting()" for details).
*/
/*!
* \page Undocumented Undocumented functions
*
* In general it was tried to avoid the usage of undocumented features of Qt.
* Nice to have features like for example Q_DECLARE_PRIVATE are not used. Only
* features that would have been resulted in re-coding the same functionality
* are used.
*
* - QT_WA: The macro is used to call Windows A/W functions
* - \ref Log4Qt::DebugAppender "DebugAppender"
* - QBasicAtomicPointer: The class is used instead of QAtomicPointer, because
* it allows the initialisation as plain old data type.
* - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC"
* - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE"
* - \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER"
* - Q_BASIC_ATOMIC_INITIALIZER: The macro is used to initialise QAtomicPointer
* objects as plain old data type.
* - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC"
* - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE"
* - \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER"
*/
/*!
* \page Assumptions Assumptions
*
* The following assumptions are used throughout the package:
*
* - Reading / writing of bool or int is thread-safe, if declared volatile
* - \ref Log4Qt::ListAppender "ListAppender"
* - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton"
* - \ref Log4Qt::ConsoleAppender "ConsoleAppender"
* - \ref Log4Qt::FileAppender "FileAppender"
* - \ref Log4Qt::Hierarchy "Hierarchy"
* - \ref Log4Qt::Level "Level"
* - \ref Log4Qt::Logger "Logger"
* - \ref Log4Qt::WriterAppender "WriterAppender"
* - \ref Log4Qt::Layout::format() "Layout::format()" is implemented reentrant
* in all sub-classes.
* - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton"
* - Being able to use singleton objects during static de-initialization without
* order issues is more valuable then their destruction.
* - \ref Log4Qt::LogManager "LogManager"
* - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC"
* - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE"
*/
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include "ukui-logmacros.h"
#if QT_VERSION < QT_VERSION_CHECK(4, 3, 0)
# error "Log4Qt requires Qt version 4.3.0 or higher"
#endif
/******************************************************************************
* Declarations
******************************************************************************/
/*!
* \brief The namespace %Log4Qt encloses all parts of the package.
*/
namespace Log4Qt
{
/*!
* This macro expands a numeric value of the form 0xMMmmPP (MM = major,
* mm = minor, PP = patch) that specifies Log4Qt's version number.
* This is the version against which the application is compiled.
*
* \sa \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR",
* \ref Log4Qt::LogManager::version() "LogManager::version()"
*/
#define LOG4QT_VERSION 0x000200
/*!
* The macro expands to a string that specifies the Log4Qt's version
* number. This is the version against which the application is compiled.
*
* \sa \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION",
* \ref Log4Qt::LogManager::version() "LogManager::version()"
*/
#define LOG4QT_VERSION_STR "0.3.0"
enum ErrorCode
{
OK = 0,
// AppenderSkeleton, FileAppender, WriterAppender
APPENDER_ACTIVATE_MISSING_LAYOUT_ERROR,
APPENDER_ACTIVATE_MISSING_WRITER_ERROR,
APPENDER_ACTIVATE_MISSING_FILE_ERROR,
APPENDER_CLOSED_ERROR,
APPENDER_INVALID_PATTERN_ERROR,
APPENDER_NO_OPEN_FILE_ERROR,
APPENDER_NOT_ACTIVATED_ERROR,
APPENDER_OPENING_FILE_ERROR,
APPENDER_RENAMING_FILE_ERROR,
APPENDER_REMOVE_FILE_ERROR,
APPENDER_USE_INVALID_PATTERN_ERROR,
APPENDER_USE_MISSING_LAYOUT_ERROR,
APPENDER_USE_MISSING_WRITER_ERROR,
APPENDER_WRITING_FILE_ERROR,
// Level
LEVEL_INVALID_LEVEL_STRING,
// Layouts, PatternFormatter
LAYOUT_EXPECTED_DIGIT_ERROR,
LAYOUT_OPTION_IS_NOT_INTEGER_ERROR,
LAYOUT_INTEGER_IS_NOT_POSITIVE_ERROR,
// Logger
LOGGER_INVALID_LEVEL_FOR_ROOT,
// PropertyConfigurator, OptionHandler
CONFIGURATOR_OPENING_FILE_ERROR,
CONFIGURATOR_READING_FILE_ERROR,
CONFIGURATOR_INVALID_SUBSTITUTION_ERROR,
CONFIGURATOR_INVALID_OPTION_ERROR,
CONFIGURATOR_MISSING_APPENDER_ERROR,
CONFIGURATOR_UNKNOWN_APPENDER_CLASS_ERROR,
CONFIGURATOR_MISSING_LAYOUT_ERROR,
CONFIGURATOR_UNKNOWN_LAYOUT_CLASS_ERROR,
CONFIGURATOR_PROPERTY_ERROR,
CONFIGURATOR_UNKNOWN_TYPE_ERROR
};
/******************************************************************************
* Operators, Helpers
******************************************************************************/
/******************************************************************************
* Inline
******************************************************************************/
} // namespace Log4Qt
#endif // LOG4QT_H
ukui-interface/src/log4qt/log4qt/appender.h 0000664 0001750 0001750 00000010406 15167726076 017617 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: appender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#ifndef LOG4QT_APPENDER_H
#define LOG4QT_APPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/helpers/logobject.h"
#include "log4qt/helpers/logobjectptr.h"
#include "log4qt/logger.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class Filter;
class Layout;
class LoggingEvent;
/*!
* \brief The class Appender is the base class for all Appenders.
*
* To allow the whole hirarchy to be an ascendant of QObject Appender is
* not an interface.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT Appender : public LogObject
{
Q_OBJECT
/*!
* The property holds the Layout used by the Appender.
*
* \sa layout(), setLayout()
*/
Q_PROPERTY(Layout* layout READ layout WRITE setLayout)
/*!
* The property holds the name of the Appender.
*
* \sa name(), setName()
*/
Q_PROPERTY(QString name READ name WRITE setName)
/*!
* The property holds if the Appender requires a Layout or not.
*
* \sa requiresLayout(), setRequiresLayout()
*/
Q_PROPERTY(bool requiresLayout READ requiresLayout)
public:
Appender(QObject *pParent = 0);
virtual ~Appender();
private:
Appender(const Appender &rOther); // Not implemented
Appender &operator=(const Appender &rOther); // Not implemented
public:
// JAVA: ErrorHandler* errorHandler();
virtual Filter *filter() const = 0;
virtual QString name() const = 0;
virtual Layout *layout() const = 0;
virtual bool requiresLayout() const = 0;
// JAVA: void setErrorHandler(ErrorHandler *pErrorHandler);
virtual void setLayout(Layout *pLayout) = 0;
virtual void setName(const QString &rName) = 0;
virtual void addFilter(Filter *pFilter) = 0;
virtual void clearFilters() = 0;
virtual void close() = 0;
virtual void doAppend(const LoggingEvent &rEvent) = 0;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline Appender::Appender(QObject *pParent) :
LogObject(pParent)
{}
inline Appender::~Appender()
{}
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::Appender, Q_COMPLEX_TYPE); // Use default
#if QT_VERSION < 0x060000
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE);
#else
Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_COMPLEX_TYPE);
#endif
// Qt6 compatibility: declare opaque pointers for incomplete types
#if QT_VERSION >= 0x060000
Q_DECLARE_OPAQUE_POINTER(Log4Qt::Layout*)
Q_DECLARE_OPAQUE_POINTER(Log4Qt::Filter*)
Q_DECLARE_OPAQUE_POINTER(Log4Qt::LoggingEvent*)
#endif
#endif // LOG4QT_APPENDER_H
ukui-interface/src/log4qt/log4qt/basicconfigurator.h 0000664 0001750 0001750 00000005047 15167726064 021527 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: basicconfigurator.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_BASICCONFIGURATOR_H
#define LOG4QT_BASICCONFIGURATOR_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
class Appender;
/*!
* \brief The class BasicConfigurator provides a simple package
* configuration.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT BasicConfigurator
{
private:
BasicConfigurator(); // Not implemented
// BasicConfigurator(const BasicConfigurator &rOther); // Use compiler default
// virtual ~BasicConfigurator(); // Use compiler default
// BasicConfigurator &operator=(const BasicConfigurator &rOther); // Use compiler default
public:
static bool configure();
static void configure(Appender *pAppender);
static void resetConfiguration();
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
} // namspace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::BasicConfigurator, Q_MOVABLE_TYPE); // Use default
#endif // LOG4QT_BASICCONFIGURATOR_H
ukui-interface/src/log4qt/log4qt/propertyconfigurator.h 0000664 0001750 0001750 00000015233 15167726064 022330 0 ustar feng feng /******************************************************************************
*
* package: Logging
* file: propertyconfigurator.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_PROPERTYCONFIGURATOR_H
#define LOG4QT_PROPERTYCONFIGURATOR_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#include "log4qt/helpers/logobjectptr.h"
#include "log4qt/log4qt.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
class QSettings;
namespace Log4Qt
{
class Appender;
class Layout;
class ListAppender;
class Logger;
class Properties;
class LoggerRepository;
/*!
* \brief The class PropertyConfigurator allows the configuration of the
* package from a JAVA properties file.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT PropertyConfigurator
{
public:
PropertyConfigurator();
// virtual ~PropertyConfigurator(); // Use compiler default
private:
PropertyConfigurator(const PropertyConfigurator &rOther); // Not implemented
PropertyConfigurator &operator=(const PropertyConfigurator &rOther); // Not implemented
public:
/*!
* \sa ConfiguratorHelper::configureError()
*/
bool doConfigure(const Properties &rProperties,
LoggerRepository *pLoggerRepository = 0);
/*!
* \sa ConfiguratorHelper::configureError()
*/
bool doConfigure(const QString &rConfigFileName,
LoggerRepository *pLoggerRepository = 0);
/*!
* Reads the configuration data from the QSettings object
* \a rSettings.
*
* \sa \ref Properties::load(const QSettings &) "Properties::load()",
* ConfiguratorHelper::configureError()
*/
bool doConfigure(const QSettings &rSettings,
LoggerRepository *pLoggerRepository = 0);
// JAVA: void doConfigure(const QUrl &rUrl, LoggerRepository *pLoggerRepository);
/*!
* \sa ConfiguratorHelper::configureError()
*/
static bool configure(const Properties &rProperties);
/*!
* \sa ConfiguratorHelper::configureError()
*/
static bool configure(const QString &rConfigFilename);
/*!
* Reads the configuration data from the QSettings object
* \a rSettings.
*
* \sa \ref doConfigure(const QSettings &, LoggerRepository *) "doConfigure()",
* \ref Properties::load(const QSettings &) "Properties::load()",
* ConfiguratorHelper::configureError()
*/
static bool configure(const QSettings &rSettings);
// JAVA: static void configure(const QUrl &rUrl);
/*!
* \sa ConfiguratorHelper::configureError(),
* ConfiguratorHelper::configurationFile()
*/
static bool configureAndWatch(const QString &rConfigFilename);
private:
void configureFromFile(const QString &rConfigFileName,
LoggerRepository *pLoggerRepository);
void configureFromProperties(const Properties &rProperties,
LoggerRepository *pLoggerRepository);
void configureFromSettings(const QSettings &rSettings,
LoggerRepository *pLoggerRepository);
void configureGlobalSettings(const Properties &rProperties,
LoggerRepository *pLoggerRepository) const;
void configureNonRootElements(const Properties &rProperties,
LoggerRepository *pLoggerRepository);
void configureRootLogger(const Properties &rProperties,
LoggerRepository *pLoggerRepository);
void parseAdditivityForLogger(const Properties &rProperties,
Logger *pLogger,
const QString &rLog4jName) const;
LogObjectPtr parseAppender(const Properties &rProperties,
const QString &rName);
LogObjectPtr parseLayout(const Properties &rProperties,
const QString &rAppenderName);
void parseLogger(const Properties &rProperties,
Logger *pLogger,
const QString &rKey,
const QString &rValue);
void setProperties(const Properties &rProperties,
const QString &rPrefix,
const QStringList &rExclusions,
QObject *pObject);
void startCaptureErrors();
bool stopCaptureErrors();
private:
LogObjectPtr mpConfigureErrors;
QHash< QString, LogObjectPtr > mAppenderRegistry;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
/*!
* \relates PropertyConfigurator
*
* Writes all object member variables to the given debug stream \a debug
* and returns the stream.
*
*
* %PropertyConfigurator()
*
* \sa QDebug
*/
QDebug operator<<(QDebug debug,
const PropertyConfigurator &rPropertyConfigurator);
#endif
/**************************************************************************
* Inline
**************************************************************************/
inline PropertyConfigurator::PropertyConfigurator()
{}
} // namspace Logging
// Q_DECLARE_TYPEINFO(Log4Qt::PropertyConfigurator, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_PROPERTYCONFIGURATOR_H
ukui-interface/src/log4qt/log4qt/writerappender.h 0000664 0001750 0001750 00000016504 15167726076 021061 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: writerappender.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_WRITERAPPENDER_H
#define LOG4QT_WRITERAPPENDER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/appenderskeleton.h"
#include "ukui-logmacros.h"
/******************************************************************************
* Declarations
******************************************************************************/
#if QT_VERSION >= 0x060000
#include
#endif
#if QT_VERSION < 0x060000
class QTextCodec;
#endif
class QTextStream;
namespace Log4Qt
{
class AsyncDispatcher;
/*!
* \brief The class WriterAppender appends log events to a QTextStream.
*
* \note All the functions declared in this class are thread-safe.
*
* \note The ownership and lifetime of objects of this class are managed.
* See \ref Ownership "Object ownership" for more details.
*/
class LIBUKUILOG4QT_EXPORT WriterAppender : public AppenderSkeleton
{
Q_OBJECT
/*!
* The property holds the codec the appender uses.
*
* The default is null to use the codec the writer has set.
*
* \sa encoding(), setEncoding()
*/
#if QT_VERSION < 0x060000
Q_PROPERTY(QTextCodec *encoding READ encoding WRITE setEncoding)
#else
Q_PROPERTY(QStringConverter::Encoding encoding READ encoding WRITE setEncoding)
#endif
/*!
* The property holds the writer the appender uses.
*
* \sa writer(), setWriter()
*/
Q_PROPERTY(QTextStream* writer READ writer WRITE setWriter)
/*!
* The property holds, if the writer flushes after all write operations.
*
* The default is true for flushing.
*
* \sa immediateFlush(), setImmediateFlush()
*/
Q_PROPERTY(bool immediateFlush READ immediateFlush WRITE setImmediateFlush)
public:
WriterAppender(QObject *pParent = 0);
WriterAppender(Layout *pLayout,
QObject *pParent = 0);
WriterAppender(Layout *pLayout,
QTextStream *pTextStream,
QObject *pParent = 0);
virtual ~WriterAppender();
private:
WriterAppender(const WriterAppender &rOther); // Not implemented
WriterAppender &operator=(const WriterAppender &rOther); // Not implemented
void closeInternal();
public:
virtual bool requiresLayout() const;
#if QT_VERSION < 0x060000
QTextCodec *encoding() const;
#else
QStringConverter::Encoding encoding() const;
#endif
bool immediateFlush() const;
QTextStream *writer() const;
/*!
* Sets the codec used by the writer to \a pTextCoded.
*
* If a codec is set with setEncoding, it will overwrite the codec set
* in the text stream. A subsequent call with \a pTextCoded equals null
* will resets the codec to the default QTextCodec::codecForLocale().
*
* \sa encoding(), QTextSream::setCodec(), QTextCodec::codecForLocale()
*/
#if QT_VERSION < 0x060000
void setEncoding(QTextCodec *encoding);
#else
void setEncoding(QStringConverter::Encoding encoding);
#endif
void setImmediateFlush(bool immediateFlush);
void setWriter(QTextStream *pTextStream);
virtual void activateOptions();
virtual void close();
protected:
virtual void append(const LoggingEvent &rEvent);
virtual void asyncAppend(const LoggingEvent &rEvent);
/*!
* Tests if all entry conditions for using append() in this class are
* met.
*
* If a conditions is not met, an error is logged and the function
* returns false. Otherwise the result of
* AppenderSkeleton::checkEntryConditions() is returned.
*
* The checked conditions are:
* - A writer has been set (APPENDER_USE_MISSING_WRITER_ERROR)
*
* The function is called as part of the checkEntryConditions() chain
* started by AppenderSkeleton::doAppend().
*
* \sa AppenderSkeleton::doAppend(),
* AppenderSkeleton::checkEntryConditions()
*/
virtual bool checkEntryConditions() const;
void closeWriter();
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream
* \a rDebug and returns the stream.
*
*
* %WriterAppender(name:"WA" encoding:"" immediateFlush:true
* isactive:false isclosed:false layout:"TTCC"
* referencecount:1 threshold:"NULL"
* writer:0x0)
*
* \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject )
*/
virtual QDebug debug(QDebug &rDebug) const;
#endif // QT_NO_DEBUG_STREAM
virtual bool handleIoErrors() const;
void writeFooter() const;
void writeHeader() const;
private:
#if QT_VERSION < 0x060000
QTextCodec *mEncoding;
#else
QStringConverter::Encoding mEncoding;
#endif
QTextStream *mpWriter;
volatile bool mImmediateFlush;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
#if QT_VERSION < 0x060000
inline QTextCodec *WriterAppender::encoding() const
{
QMutexLocker locker(&mObjectGuard);
return mEncoding;
}
#else
inline QStringConverter::Encoding WriterAppender::encoding() const
{
QMutexLocker locker(&mObjectGuard);
return mEncoding;
}
#endif
inline bool WriterAppender::immediateFlush() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mImmediateFlush; }
inline QTextStream *WriterAppender::writer() const
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
return mpWriter; }
inline void WriterAppender::setImmediateFlush(bool immediateFlush)
{ // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe
mImmediateFlush = immediateFlush; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::WriterAppender, Q_COMPLEX_TYPE); // Use default
// Qt6 compatibility: declare opaque pointers for incomplete types
#if QT_VERSION >= 0x060000
Q_DECLARE_OPAQUE_POINTER(QTextStream*)
#endif
#endif // LOG4QT_WRITERAPPENDER_H
ukui-interface/src/log4qt/log4qt/hierarchy.h 0000664 0001750 0001750 00000011242 15167726064 017773 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: hierarchy.h
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_HIERARCHY_H
#define LOG4QT_HIERARCHY_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/loggerrepository.h"
#include "ukui-logmacros.h"
#include
#include
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* \brief The class Hierarchy implements a logger repository.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT Hierarchy : public LoggerRepository
{
public:
Hierarchy();
// Hierarchy(const Hierarchy &rOther); // Use compiler default
virtual ~Hierarchy();
// Hierarchy &operator=(const Hierarchy &rOther); // Use compiler default
public:
virtual bool exists(const QString &rName) const;
virtual Logger *logger(const QString &rName);
virtual QList loggers() const;
// JAVA: virtual Logger *logger(const String &rName, LoggerFactory *pFactory);
virtual Logger *rootLogger() const;
virtual Level threshold() const;
virtual void setThreshold(Level level);
virtual void setThreshold(const QString &rThreshold);
// JAVA: void clear();
virtual bool isDisabled(Level level);
virtual void resetConfiguration();
virtual void shutdown();
// JAVA: virtual void addHierarchyEventListener(HierarchyEventListener *pEventListener);
// JAVA: virtual void emitNoAppenderWarning(Logger *plogger) const;
// JAVA: virtual void fireAddAppenderEvent(Logger *plogger, Appender *pAppender) const;
// JAVA: void addRenderer(const QString &rClass, ObjectRenderer *pObjectRenderer);
// JAVA: QHash getRendererMap() const;
// JAVA: setRenderer(const QString &rClass, ObjectRenderer *pObjectRenderer);
protected:
#ifndef QT_NO_DEBUG_STREAM
/*!
* Writes all object member variables to the given debug stream \a rDebug and
* returns the stream.
*
*
* %Hierarchy(loggers:6 threshold:"ALL" root-level:"DEBUG" root-appenders:0)
*
* \sa QDebug, operator<<(QDebug debug, const LoggerRepository &rLoggerRepository)
*/
virtual QDebug debug(QDebug &rdebug) const;
#endif
private:
Logger *createLogger(const QString &rName);
void resetLogger(Logger *pLogger, Level level) const;
private:
mutable QReadWriteLock mObjectGuard;
QHash mLoggers;
volatile bool mHandleQtMessages;
Level mThreshold;
Logger *mpRootLogger;
};
/**************************************************************************
* Operators, Helper
**************************************************************************/
/**************************************************************************
* Inline
**************************************************************************/
inline Logger *Hierarchy::rootLogger() const
{ // QReadLocker locker(&mObjectGuard); // Constant for object lifetime
return mpRootLogger; }
inline Level Hierarchy::threshold() const
{ // QReadLocker locker(&mObjectGuard); // Level is threadsafe
return mThreshold; }
inline void Hierarchy::setThreshold(Level level)
{ // QReadLocker locker(&mObjectGuard); // Level is threadsafe
mThreshold = level; }
inline bool Hierarchy::isDisabled(Level level)
{ // QReadLocker locker(&mObjectGuard); // Level is threadsafe
return level < mThreshold; }
} // namespace Log4Qt
// Q_DECLARE_TYPEINFO(Log4Qt::Hierarchy, Q_COMPLEX_TYPE); // Use default
#endif // LOG4QT_HIERARCHY_H
ukui-interface/src/log4qt/log4qt/propertyconfigurator.cpp 0000664 0001750 0001750 00000053641 15167726064 022670 0 ustar feng feng /******************************************************************************
*
* package: Logging
* file: propertyconfigurator.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* changes Feb 2009, Martin Heinrich
* - Fixed VS 2008 unreferenced formal parameter warning by using
* Q_UNUSED in operator<<.
*
*
* Copyright 2007 - 2009 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "log4qt/propertyconfigurator.h"
#include
#include
#include "log4qt/helpers/configuratorhelper.h"
#include "log4qt/helpers/factory.h"
#include "log4qt/helpers/optionconverter.h"
#include "log4qt/helpers/properties.h"
#include "log4qt/appender.h"
#include "log4qt/layout.h"
#include "log4qt/logger.h"
#include "log4qt/logmanager.h"
#include "log4qt/loggerrepository.h"
#include "log4qt/varia/listappender.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::PropertyConfigurator)
/**************************************************************************
* Class implementation: PropertyConfigurator
**************************************************************************/
bool PropertyConfigurator::doConfigure(const Properties &rProperties,
LoggerRepository *pLoggerRepository)
{
startCaptureErrors();
configureFromProperties(rProperties, pLoggerRepository);
return stopCaptureErrors();
}
bool PropertyConfigurator::doConfigure(const QString &rConfigFileName,
LoggerRepository *pLoggerRepository)
{
startCaptureErrors();
configureFromFile(rConfigFileName, pLoggerRepository);
return stopCaptureErrors();
}
bool PropertyConfigurator::doConfigure(const QSettings &rSettings,
LoggerRepository *pLoggerRepository)
{
startCaptureErrors();
configureFromSettings(rSettings, pLoggerRepository);
return stopCaptureErrors();
}
bool PropertyConfigurator::configure(const Properties &rProperties)
{
PropertyConfigurator configurator;
return configurator.doConfigure(rProperties);
}
bool PropertyConfigurator::configure(const QString &rConfigFilename)
{
PropertyConfigurator configurator;
return configurator.doConfigure(rConfigFilename);
}
bool PropertyConfigurator::configure(const QSettings &rSettings)
{
PropertyConfigurator configurator;
return configurator.doConfigure(rSettings);
}
bool PropertyConfigurator::configureAndWatch(const QString &rConfigFileName)
{
// Stop an existing watch to avoid a possible concurrent configuration
ConfiguratorHelper::setConfigurationFile();
if (rConfigFileName.isEmpty())
return true;
PropertyConfigurator configurator;
bool result = configurator.doConfigure(rConfigFileName);
ConfiguratorHelper::setConfigurationFile(rConfigFileName, configure);
return result;
}
void PropertyConfigurator::configureFromFile(const QString &rConfigFileName,
LoggerRepository *pLoggerRepository)
{
QFile file(rConfigFileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to open property file '%1'"),
CONFIGURATOR_OPENING_FILE_ERROR,
"Log4Qt::PropertyConfigurator");
e << rConfigFileName;
e.addCausingError(LogError(file.errorString(), file.error()));
logger()->error(e);
return;
}
Properties properties;
properties.load(&file);
if (file.error())
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to read property file '%1'"),
CONFIGURATOR_READING_FILE_ERROR,
"Log4Qt::PropertyConfigurator");
e << rConfigFileName;
e.addCausingError(LogError(file.errorString(), file.error()));
logger()->error(e);
return;
}
configureFromProperties(properties, pLoggerRepository);
}
void PropertyConfigurator::configureFromProperties(const Properties &rProperties,
LoggerRepository *pLoggerRepository)
{
if (!pLoggerRepository)
pLoggerRepository = LogManager::loggerRepository();
configureGlobalSettings(rProperties, pLoggerRepository);
configureRootLogger(rProperties, pLoggerRepository);
configureNonRootElements(rProperties, pLoggerRepository);
mAppenderRegistry.clear();
}
void PropertyConfigurator::configureFromSettings(const QSettings &rSettings,
LoggerRepository *pLoggerRepository)
{
Properties properties;
properties.load(rSettings);
configureFromProperties(properties, pLoggerRepository);
}
void PropertyConfigurator::configureGlobalSettings(const Properties &rProperties,
LoggerRepository *pLoggerRepository) const
{
Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureGlobalSettings()", "pLoggerRepository must not be null.");
const QLatin1String key_reset("log4j.reset");
const QLatin1String key_debug("log4j.Debug");
const QLatin1String key_config_debug("log4j.configDebug");
const QLatin1String key_threshold("log4j.threshold");
const QLatin1String key_handle_qt_messages("log4j.handleQtMessages");
// Test each global setting and set it
// - Reset: log4j.reset
// - Debug: log4j.Debug, log4j.configDebug
// - Threshold: log4j.threshold
// - Handle Qt Messages: log4j.handleQtMessages
// Reset
QString value = rProperties.property(key_reset);
if (!value.isEmpty() && OptionConverter::toBoolean(value, false))
{
// Use LogManager and not pLoggerRepository to reset internal
// logging.
LogManager::resetConfiguration();
logger()->debug("Reset configuration");
}
// Debug
value = rProperties.property(key_debug);
if (value.isNull())
{
value = rProperties.property(key_config_debug);
if (!value.isNull())
logger()->warn("[%1] is deprecated. Use [%2] instead.", key_config_debug, key_debug);
}
if (!value.isNull())
{
// Don't use OptionConverter::toLevel(). Invalid level string is a valid setting
bool ok;
Level level = Level::fromString(value, &ok);
if (!ok)
level = Level::DEBUG_INT;
LogManager::logLogger()->setLevel(level);
logger()->debug("Set level for Log4Qt logging to %1",
LogManager::logLogger()->level().toString());
}
// Threshold
value = rProperties.property(key_threshold);
if (!value.isNull())
{
pLoggerRepository->setThreshold(OptionConverter::toLevel(value, Level::ALL_INT));
logger()->debug("Set threshold for LoggerRepository to %1",
pLoggerRepository->threshold().toString());
}
// Handle Qt messages
value = rProperties.property(key_handle_qt_messages);
if (!value.isNull())
{
LogManager::setHandleQtMessages(OptionConverter::toBoolean(value, false));
logger()->debug("Set handling of Qt messages LoggerRepository to %1",
QVariant(LogManager::handleQtMessages()).toString());
}
}
void PropertyConfigurator::configureNonRootElements(const Properties &rProperties,
LoggerRepository *pLoggerRepository)
{
Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureNonRootElements()", "pLoggerRepository must not be null.");
const QString logger_prefix = QLatin1String("log4j.logger.");
const QString category_prefix = QLatin1String("log4j.category.");
// Iterate through all entries:
// - Test for the logger/category prefix
// - Convert JAVA class names to C++ ones
// - Parse logger data (Level, Appender)
// - Parse logger additivity
QStringList keys = rProperties.propertyNames();
QString key;
Q_FOREACH(key, keys)
{
QString java_name;
if (key.startsWith(logger_prefix))
java_name = key.mid(logger_prefix.length());
else if (key.startsWith(category_prefix))
java_name = key.mid(category_prefix.length());
QString cpp_name = OptionConverter::classNameJavaToCpp(java_name);
if (!java_name.isEmpty())
{
Logger *p_logger = pLoggerRepository->logger(cpp_name);
QString value = OptionConverter::findAndSubst(rProperties, key);
parseLogger(rProperties, p_logger, key, value);
parseAdditivityForLogger(rProperties, p_logger, java_name);
}
}
}
void PropertyConfigurator::configureRootLogger(const Properties &rProperties,
LoggerRepository *pLoggerRepository)
{
Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureRootLogger()", "pLoggerRepository must not be null.");
const QLatin1String key_root_logger("log4j.rootLogger");
const QLatin1String key_root_category("log4j.rootCategory");
// - Test for the logger/category prefix
// - Parse logger data for root logger
QString key = key_root_logger;
QString value = OptionConverter::findAndSubst(rProperties, key);
if (value.isNull())
{
key = key_root_category;
value = OptionConverter::findAndSubst(rProperties, key);
if (!value.isNull())
logger()->warn("[%1] is deprecated. Use [%2] instead.", key_root_category, key_root_logger);
}
if (value.isNull())
logger()->debug("Could not find root logger information. Is this correct?");
else
parseLogger(rProperties, pLoggerRepository->rootLogger(), key, value);
}
void PropertyConfigurator::parseAdditivityForLogger(const Properties &rProperties,
Logger *pLogger,
const QString &rLog4jName) const
{
Q_ASSERT_X(pLogger, "parseAdditivityForLogger()", "pLogger must not be null.");
const QLatin1String additivity_prefix("log4j.additivity.");
// - Lookup additivity key for logger
// - Set additivity, if specified
QString key = additivity_prefix + rLog4jName;
QString value = OptionConverter::findAndSubst(rProperties, key);
logger()->debug("Parsing additivity for logger: key '%1', value '%2'", key, value);
if (!value.isEmpty())
{
bool additivity = OptionConverter::toBoolean(value, true);
logger()->debug("Setting additivity for logger '%1' to '%2'", pLogger->name(), QVariant(value).toString());
pLogger->setAdditivity(additivity);
}
}
LogObjectPtr PropertyConfigurator::parseAppender(const Properties &rProperties,
const QString &rName)
{
// - Test if appender has been parsed before
// - Find appender key
// - Create appender object
// - Set layout, if required by appender
// - Set properties
// - Activate options
// - Add appender to registry
const QLatin1String appender_prefix("log4j.appender.");
logger()->debug("Parsing appender named '%1'", rName);
if (mAppenderRegistry.contains(rName))
{
logger()->debug("Appender '%1' was already parsed.", rName);
return mAppenderRegistry.value(rName);
}
QString key = appender_prefix + rName;
QString value = OptionConverter::findAndSubst(rProperties, key);
if (value.isNull())
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Missing appender definition for appender named '%1'"),
CONFIGURATOR_MISSING_APPENDER_ERROR,
"Log4Qt::PropertyConfigurator");
e << rName;
logger()->error(e);
return 0;
}
LogObjectPtr p_appender = Factory::createAppender(value);
if (!p_appender)
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to create appender of class '%1' namd '%2'"),
CONFIGURATOR_UNKNOWN_APPENDER_CLASS_ERROR,
"Log4Qt::PropertyConfigurator");
e << value << rName;
logger()->error(e);
return 0;
}
p_appender->setName(rName);
if (p_appender->requiresLayout())
{
LogObjectPtr p_layout = parseLayout(rProperties, key);
if (p_layout)
p_appender->setLayout(p_layout);
else
return 0;
}
QStringList exclusions;
exclusions << QLatin1String("layout");
setProperties(rProperties, key + QLatin1String("."), exclusions, p_appender);
AppenderSkeleton *p_appenderskeleton = qobject_cast(p_appender);
if (p_appenderskeleton)
p_appenderskeleton->activateOptions();
mAppenderRegistry.insert(rName, p_appender);
return p_appender;
}
LogObjectPtr PropertyConfigurator::parseLayout(const Properties &rProperties,
const QString &rAppenderKey)
{
Q_ASSERT_X(!rAppenderKey.isEmpty(), "PropertyConfigurator::parseLayout()", "rAppenderKey must not be empty.");
// - Find layout key
// - Create layput object
// - Set properties
// - Activate options
const QLatin1String layout_suffix(".layout");
logger()->debug("Parsing layout for appender named '%1'", rAppenderKey);
QString key = rAppenderKey + layout_suffix;
QString value = OptionConverter::findAndSubst(rProperties, key);
if (value.isNull())
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Missing layout definition for appender '%1'"),
CONFIGURATOR_MISSING_LAYOUT_ERROR,
"Log4Qt::PropertyConfigurator");
e << rAppenderKey;
logger()->error(e);
return 0;
}
LogObjectPtr p_layout = Factory::createLayout(value);
if (!p_layout)
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to create layoput of class '%1' requested by appender '%2'"),
CONFIGURATOR_UNKNOWN_LAYOUT_CLASS_ERROR,
"Log4Qt::PropertyConfigurator");
e << value << rAppenderKey;
logger()->error(e);
return 0;
}
QStringList exclusions;
setProperties(rProperties, key + QLatin1String("."), QStringList(), p_layout);
p_layout->activateOptions();
return p_layout;
}
void PropertyConfigurator::parseLogger(const Properties &rProperties,
Logger *pLogger,
const QString &rKey,
const QString &rValue)
{
Q_ASSERT_X(pLogger, "PropertyConfigurator::parseLogger()", "pLogger must not be null.");
Q_ASSERT_X(!rKey.isEmpty(), "PropertyConfigurator::parseLogger()", "rKey must not be empty.");
const QLatin1String keyword_inherited("INHERITED");
// - Split value on comma
// - If level value, is specified
// - Test for NULL and INHERITED
// - Ensure root logger is not set to NULL
// - Set level
// - For each entry
// - Create Appender
logger()->debug("Parsing logger: key '%1', value '%2'", rKey, rValue);
QStringList appenders = rValue.split(QLatin1Char(','));
QStringListIterator i (appenders);
// First entry is the level. There will be always one entry, even if the rValue is
// empty or does not contain a comma.
QString value = i.next().trimmed();
if (!value.isEmpty())
{
Level level;
if (value.compare(keyword_inherited,Qt::CaseInsensitive) == 0)
level = Level::NULL_INT;
else
level = OptionConverter::toLevel(value, Level::DEBUG_INT);
if (level == Level::NULL_INT && pLogger->name() == QString())
logger()->warn("The root logger level cannot be set to NULL.");
else
{
pLogger->setLevel(level);
logger()->debug("Set level for logger '%1' to '%2'",
pLogger->name(), pLogger->level().toString());
}
}
pLogger->removeAllAppenders();
while(i.hasNext())
{
value = i.next().trimmed();
if(value.isEmpty())
continue;
LogObjectPtr p_appender = parseAppender(rProperties, value);
if (p_appender)
pLogger->addAppender(p_appender);
}
}
void PropertyConfigurator::setProperties(const Properties &rProperties,
const QString &rPrefix,
const QStringList &rExclusions,
QObject *pObject)
{
Q_ASSERT_X(!rPrefix.isEmpty(), "PropertyConfigurator::setProperties()", "rPrefix must not be empty.");
Q_ASSERT_X(pObject, "PropertyConfigurator::setProperties()", "pObject must not be null.");
// Iterate through all entries:
// - Test for prefix to determine, if setting is for object
// - Skip empty property name
// - Skip property names in exclusion list
// - Set property on object
logger()->debug("Setting properties for object of class '%1' from keys starting with '%2'",
QLatin1String(pObject->metaObject()->className()),
rPrefix);
QStringList keys = rProperties.propertyNames();
QString key;
Q_FOREACH(key, keys)
{
if (!key.startsWith(rPrefix))
continue;
QString property = key.mid(rPrefix.length());
if (property.isEmpty())
continue;
QStringList split_property = property.split(QLatin1Char('.'));
if (rExclusions.contains(split_property.at(0), Qt::CaseInsensitive))
continue;
QString value = OptionConverter::findAndSubst(rProperties, key);
Factory::setObjectProperty(pObject, property, value);
}
}
void PropertyConfigurator::startCaptureErrors()
{
Q_ASSERT_X(!mpConfigureErrors, "PropertyConfigurator::startCaptureErrors()", "mpConfigureErrors must be empty.");
mpConfigureErrors = new ListAppender;
mpConfigureErrors->setName(QLatin1String("PropertyConfigurator"));
mpConfigureErrors->setConfiguratorList(true);
mpConfigureErrors->setThreshold(Level::ERROR_INT);
LogManager::logLogger()->addAppender(mpConfigureErrors);
}
bool PropertyConfigurator::stopCaptureErrors()
{
Q_ASSERT_X(mpConfigureErrors, "PropertyConfigurator::stopCaptureErrors()", "mpConfigureErrors must not be empty.");
LogManager::logLogger()->removeAppender(mpConfigureErrors);
ConfiguratorHelper::setConfigureError(mpConfigureErrors->list());
bool result = (mpConfigureErrors->list().count() == 0);
mpConfigureErrors = 0;
return result;
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const PropertyConfigurator &rPropertyConfigurator)
{
Q_UNUSED(rPropertyConfigurator);
debug.nospace() << "PropertyConfigurator("
<< ")";
return debug.space();
}
#endif
} // namespace Logging
ukui-interface/src/log4qt/log4qt/logger.h 0000664 0001750 0001750 00000176512 15167726076 017313 0 ustar feng feng /******************************************************************************
*
* package: Log4Qt
* file: logger.h
* created: September 2007
* author: Martin Heinrich
*
*
* changes: Sep 2008, Martin Heinrich:
* - Replaced usage of q_atomic_test_and_set_ptr with
* QBasicAtomicPointer
*
*
* Copyright 2007 - 2008 Martin Heinrich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#ifndef LOG4QT_LOGGER_H
#define LOG4QT_LOGGER_H
/******************************************************************************
* Dependencies
******************************************************************************/
#include
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include
#endif
#include
#include
#include "log4qt/helpers/logerror.h"
#include "log4qt/helpers/classlogger.h"
#include "log4qt/helpers/logobjectptr.h"
#include "log4qt/level.h"
#include "ukui-logmacros.h"
#if QT_VERSION >= 0x040400 && QT_VERSION < 0x060000
# ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
# warning "QAtomicPointer test and set is not native. The macro Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER is not thread-safe."
# endif
#endif
/******************************************************************************
* Declarations
******************************************************************************/
namespace Log4Qt
{
/*!
* LOG4QT_DECLARE_STATIC_LOGGER declares a static function \a FUNCTION that
* returns a pointer to a \ref Log4Qt::Logger "Logger" named after \a CLASS.
*
* On the first invocation the \ref Log4Qt::Logger "Logger" is requested
* by calling \ref Log4Qt::Logger::logger(const char *pName)
* "Logger::logger( #CLASS )". The pointer is stored to be returned on
* subsequent invocations.
*
* The following example shows how to use the macro to define a logger to be
* used within a class not derived from QObject.
*
* \code
* #file: counter.h
*
* #include logger.h
*
* class Counter
* {
* public:
* Counter();
* Counter(int preset);
* private:
* int mCount;
* }
* \endcode
* \code
* #file: counter.cpp
*
* #include counter.h
*
* LOG4QT_DECLARE_STATIC_LOGGER(logger, Counter)
*
* Counter::Counter() :
* mCount(0)
* {}
*
* void Counter::Counter(int preset) :
* mCount(preset)
* {
* if (preset < 0)
* {
* logger()->warn("Invalid negative counter preset %1. Using 0 instead.", preset);
* mCount = 0;
* }
* }
* \endcode
*
* \note The function created by the macro is thread-safe.
*
* \sa \ref Log4Qt::Logger::logger(const char *pName) "Logger::logger(const char *pName)"
*/
#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0)
#define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \
static Log4Qt::Logger *FUNCTION() \
{ \
static Log4Qt::Logger *p_logger = 0; \
if (!p_logger) \
{ \
q_atomic_test_and_set_ptr( \
&p_logger, \
0, \
Log4Qt::Logger::logger( #CLASS )); \
} \
return p_logger; \
}
#elif QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \
static Log4Qt::Logger *FUNCTION() \
{ \
static QBasicAtomicPointer p_logger = \
Q_BASIC_ATOMIC_INITIALIZER(0); \
if (!p_logger) \
{ \
p_logger.testAndSetOrdered(0, \
Log4Qt::Logger::logger( #CLASS )); \
} \
return p_logger; \
}
#else
#define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \
static Log4Qt::Logger *FUNCTION() \
{ \
static QBasicAtomicPointer p_logger = \
Q_BASIC_ATOMIC_INITIALIZER(0); \
if (!p_logger.loadAcquire()) \
{ \
p_logger.testAndSetOrdered(0, \
Log4Qt::Logger::logger( #CLASS )); \
} \
return p_logger.loadAcquire(); \
}
#endif
/*!
* LOG4QT_DECLARE_QCLASS_LOGGER declares member functions to retrieve
* \ref Log4Qt::Logger "Logger" for the class it is used in.
*
* On the first invocation the \ref Log4Qt::Logger "Logger" is requested
* by a call to \ref Log4Qt::Logger::logger(const char *pName)
* "Logger::logger(const char *pName)". The pointer is stored to be
* returned on subsequent invocations.
*
* The following example shows how to use the macro to define a logger to be
* used within a class derived from QObject.
*
* \code
* #file: counter.h
*
* #include qobject.h
* #include logger.h
*
* class Counter : public QObject
* {
* Q_OBJECT
* LOG4QT_DECLARE_QCLASS_LOGGER
* public:
* Counter();
* Counter(int preset);
* private:
* int mCount;
* }
* \endcode
* \code
* #file: counter.cpp
*
* #include counter.h
*
* Counter::Counter() :
* mCount(0)
* {}
*
* void Counter::Counter(int preset)
* mCount(preset)
* {
* if (preset < 0)
* {
* logger()->warn("Invalid negative counter preset %1. Using 0 instead.", preset);
* mCount = 0;
* }
* }
* \endcode
*
* \note The function created by the macro is thread-safe.
*
* \sa \ref Log4Qt::Logger::logger(const char *pName) "Logger::logger(const char *pName)",
* \ref Log4Qt::ClassLogger "ClassLogger"
*/
#define LOG4QT_DECLARE_QCLASS_LOGGER \
private: \
mutable Log4Qt::ClassLogger mLog4QtClassLogger; \
public: \
inline Log4Qt::Logger *logger() const \
{ return mLog4QtClassLogger.logger(this); } \
private:
class Appender;
class LoggingEvent;
class LoggerRepository;
/*!
* \brief The class Logger provides logging services.
*
* A pointer to a logger can be retrieved by calling Logger::logger() or
* LogManager::logger() with the class name as argument. Because a logger
* is never destroyed it is possible to store the pointer to the logger.
* This way the lookup of the pointer in the repository is only required
* on the first logging operation. The macros \ref
* Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER" and
* \ref Log4Qt::LOG4QT_DECLARE_QCLASS_LOGGER "LOG4QT_DECLARE_QCLASS_LOGGER"
* provide a thread-safe implementation to store the logger pointer.
*
* \note All the functions declared in this class are thread-safe.
*/
class LIBUKUILOG4QT_EXPORT Logger : public QObject
{
Q_OBJECT
/*!
* The property holds, if the logger is additive.
*
* The default is true for being additive.
*
* \sa additive(), setAdditive()
*/
Q_PROPERTY(bool additivity READ additivity WRITE setAdditivity)
/*!
* The property holds the level used by the logger.
*
* The default is Level::NULL_INT.
* \sa level(), setLevel()
*/
Q_PROPERTY(Level level READ level WRITE setLevel)
/*!
* The property holds the LoggerRepository of the logger.
*
* \sa loggerRepository()
*/
Q_PROPERTY(LoggerRepository* loggerRepository READ loggerRepository)
/*!
* The property holds the name of the logger.
*
* \sa name()
*/
Q_PROPERTY(QString name READ name)
/*!
* The property holds the parent logger of the logger.
*
* \sa parentLogger()
*/
Q_PROPERTY(Logger* parentLogger READ parentLogger)
LOG4QT_DECLARE_QCLASS_LOGGER
protected:
Logger(LoggerRepository* pLoggerRepository, Level level, const QString &rName, Logger *pParent = 0);
virtual ~Logger();
private:
Logger(const Logger &rOther); // Not implemented
Logger &operator=(const Logger &rOther); // Not implemented
public:
bool additivity() const;
QList appenders() const;
Level level() const;
LoggerRepository *loggerRepository() const;
QString name() const;
Logger *parentLogger() const;
// JAVA: ResourceBundle *resourceBundle() const;
// JAVA: void setResourceBundle(ResourceBundle *pResourceBundle);
void setAdditivity(bool additivity);
virtual void setLevel(Level level);
void addAppender(Appender *pAppender);
Appender *appender(const QString &rName) const;
void callAppenders(const LoggingEvent &rEvent) const;
bool isAttached(Appender *pAppender) const;
/*!
* Removes all appenders that have been previously added from this
* Logger.
*
* To allow configurators to collect events during the configuration
* process ListAppenders with the configuratorList property set, will
* not be removed.
*
* \sa LisAppender::setConfiguratorList()
*/
void removeAllAppenders();
void removeAppender(Appender *pAppender);
void removeAppender(const QString &rName);
// JAVA: QString resourceBundleString(const QString &rKey) const;
Level effectiveLevel() const;
bool isDebugEnabled() const;
/*!
* Checks if this logger is enabled for a given Level \a level. If the
* logger is enabled the function returns true. Otherwise it returns
* false.
*
* A logger is enabled for a level, if the level is greater or equal
* then the repository threshold and greater and equal then the loggers
* effective level.
*
* \sa LoggerRepository::isDisabled(), effectiveLevel()
*/
bool isEnabledFor(Level level) const;
bool isErrorEnabled() const;
bool isFatalEnabled() const;
bool isInfoEnabled() const;
bool isTraceEnabled() const;
bool isWarnEnabled() const;
void debug(const QString &rMessage) const;
void debug(const LogError &rLogError) const;
void debug(const char *pMessage) const;
void debug(const char *pMessage,
const QString &rArg1) const;
void debug(const char *pMessage,
int arg1) const;
void debug(const char *pMessage,
const QString &rArg1,
const QString &rArg2) const;
void debug(const char *pMessage,
const QString &rArg1,
int arg2) const;
void debug(const char *pMessage,
int arg1,
const QString &rArg2) const;
void debug(const char *pMessage,
int arg1,
int arg2) const;
void debug(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
const QString &rArg3) const;
void debug(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
int arg3) const;
void debug(const char *pMessage,
const QString &rArg1,
int arg2,
const QString &rArg3) const;
void debug(const char *pMessage,
const QString &rArg1,
int arg2,
int arg3) const;
void debug(const char *pMessage,
int arg1,
const QString &rArg2,
const QString &rArg3) const;
void debug(const char *pMessage,
int arg1,
const QString &rArg2,
int arg3) const;
void debug(const char *pMessage,
int arg1,
int arg2,
const QString &rArg3) const;
void debug(const char *pMessage,
int arg1,
int arg2,
int arg3) const;
void debug(const char *pMessage,
const QVariant &rArg1,
const QVariant &rArg2,
const QVariant &rArg3) const;
void error(const QString &rMessage) const;
void error(const LogError &rLogError) const;
void error(const char *pMessage) const;
void error(const char *pMessage,
const QString &rArg1) const;
void error(const char *pMessage,
int arg1) const;
void error(const char *pMessage,
const QString &rArg1,
const QString &rArg2) const;
void error(const char *pMessage,
const QString &rArg1, int arg2) const;
void error(const char *pMessage,
int arg1,
const QString &rArg2) const;
void error(const char *pMessage,
int arg1,
int arg2) const;
void error(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
const QString &rArg3) const;
void error(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
int arg3) const;
void error(const char *pMessage,
const QString &rArg1,
int arg2,
const QString &rArg3) const;
void error(const char *pMessage,
const QString &rArg1,
int arg2,
int arg3) const;
void error(const char *pMessage,
int arg1,
const QString &rArg2,
const QString &rArg3) const;
void error(const char *pMessage,
int arg1,
const QString &rArg2,
int arg3) const;
void error(const char *pMessage,
int arg1,
int arg2,
const QString &rArg3) const;
void error(const char *pMessage,
int arg1,
int arg2,
int arg3) const;
void error(const char *pMessage,
const QVariant &rArg1,
const QVariant &rArg2,
const QVariant &rArg3) const;
void fatal(const QString &rMessage) const;
void fatal(const LogError &rLogError) const;
void fatal(const char *pMessage) const;
void fatal(const char *pMessage,
const QString &rArg1) const;
void fatal(const char *pMessage,
int arg1) const;
void fatal(const char *pMessage,
const QString &rArg1,
const QString &rArg2) const;
void fatal(const char *pMessage,
const QString &rArg1,
int arg2) const;
void fatal(const char *pMessage,
int arg1,
const QString &rArg2) const;
void fatal(const char *pMessage,
int arg1,
int arg2) const;
void fatal(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
const QString &rArg3) const;
void fatal(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
int arg3) const;
void fatal(const char *pMessage,
const QString &rArg1,
int arg2,
const QString &rArg3) const;
void fatal(const char *pMessage,
const QString &rArg1,
int arg2,
int arg3) const;
void fatal(const char *pMessage,
int arg1,
const QString &rArg2,
const QString &rArg3) const;
void fatal(const char *pMessage,
int arg1,
const QString &rArg2,
int arg3) const;
void fatal(const char *pMessage,
int arg1,
int arg2,
const QString &rArg3) const;
void fatal(const char *pMessage,
int arg1,
int arg2,
int arg3) const;
void fatal(const char *pMessage,
const QVariant &rArg1,
const QVariant &rArg2,
const QVariant &rArg3) const;
void info(const QString &rMessage) const;
void info(const LogError &rLogError) const;
void info(const char *pMessage) const;
void info(const char *pMessage,
const QString &rArg1) const;
void info(const char *pMessage,
int arg1) const;
void info(const char *pMessage,
const QString &rArg1,
const QString &rArg2) const;
void info(const char *pMessage,
const QString &rArg1,
int arg2) const;
void info(const char *pMessage,
int arg1,
const QString &rArg2) const;
void info(const char *pMessage,
int arg1,
int arg2) const;
void info(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
const QString &rArg3) const;
void info(const char *pMessage,
const QString &rArg1,
const QString &rArg2,
int arg3) const;
void info(const char *pMessage,
const QString &rArg1,
int arg2,
const QString &rArg3) const;
void info(const char *pMessage,
const QString &rArg1,
int arg2,
int arg3) const;
void info(const char *pMessage,
int arg1,
const QString &rArg2,
const QString &rArg3) const;
void info(const char *pMessage,
int arg1,
const QString &rArg2,
int arg3) const;
void info(const char *pMessage,
int arg1,
int arg2,
const QString &rArg3) const;
void info(const char *pMessage,
int arg1,
int arg2,
int arg3) const;
void info(const char *pMessage,
const QVariant &rArg1,
const QVariant &rArg2,
const QVariant &rArg3) const;
void log(Level level,
const QString &rMessage) const;
void log(Level level,
const LogError &rLogError) const;
void log(Level level,
const char *pMessage) const;
void log(Level level,
const char *pMessage,
const QString &rArg1) const;
void log(Level level,
const char *pMessage,
int arg1) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
const QString &rArg2) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
int arg2) const;
void log(Level level,
const char *pMessage,
int arg1,
const QString &rArg2) const;
void log(Level level,
const char *pMessage,
int arg1,
int arg2) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
const QString &rArg2,
const QString &rArg3) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
const QString &rArg2,
int arg3) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
int arg2,
const QString &rArg3) const;
void log(Level level,
const char *pMessage,
const QString &rArg1,
int arg2,
int arg3) const;
void log(Level level,
const char *pMessage,
int arg1,
const QString &rArg2,
const QString &rArg3) const;
void log(Level level,
const char *pMessage,
int arg1,
const QString &rArg2,
int arg3) const;
void log(Level level,
const char *pMessage,
int arg1,
int arg2,
const QString &rArg3) const;
void log(Level level,
const char *pMessage,
int arg1,
int arg2,
int arg3) const;
void log(Level level,
const char *pMessage,
const QVariant &rArg1,
const QVariant &rArg2,
const QVariant &rArg3) const;
// JAVA: void l7dlog(Level level,
// const QString &rKey);
// JAVA: void l7dlog(Level level,
// const QString &rKey,
// const QList