Merge pull request #4 from WangZhongDian/dev

Dev 0.2.2
This commit is contained in:
youmetme
2024-09-19 13:20:31 +08:00
committed by GitHub
19 changed files with 682 additions and 383 deletions

246
.clang-format Normal file
View File

@@ -0,0 +1,246 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: true
AcrossEmptyLines: true
AcrossComments: true
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseColons: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
- __capability
BinPackArguments: false
BinPackParameters: false
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
KeepEmptyLinesAtEOF: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
...

3
.gitignore vendored
View File

@@ -1,5 +1,4 @@
.cache
.vscode/**
bin
build
CMakeUserPresets.json

View File

@@ -1,9 +1,5 @@
cmake_minimum_required( VERSION 3.28)
project(Logging)
aux_source_directory(${CMAKE_SOURCE_DIR}/src SRC)
set(LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
set(ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
@@ -11,15 +7,11 @@ set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin)
include_directories(${CMAKE_SOURCE_DIR}/include)
if (SHARED)
add_library(${PROJECT_NAME} SHARED ${SRC})
else()
add_library(${PROJECT_NAME} ${SRC})
endif()
#编译库文件
add_subdirectory(src)
#测试单元
if (SKIPTEST)
else()
add_executable(test_simple ${CMAKE_SOURCE_DIR}/test_package/test_simple.c ${SRC})
add_executable(test_interceptor ${CMAKE_SOURCE_DIR}/test_package/test_interceptor.c ${SRC})
add_subdirectory(tests)
endif()

View File

@@ -99,3 +99,9 @@ int main() {
```
![](docs/img/![](2024-08-13-22-20-18.png).png)
![](docs/img/2024-08-13-22-21-37.png)
# build
```shell
conan create . --build=missing
```

View File

@@ -6,10 +6,9 @@ from conan import tools
import os
class loggingRecipe(ConanFile):
name = "logging"
version = "0.1.1"
version = "0.2.2"
license = "MIT"
author = "321640253@qq.com"
url = "https://github.com/WangZhongDian/logging.git"

View File

@@ -1,87 +1,37 @@
#ifndef __LOGGING_H__
#define __LOGGING_H__
#ifndef __LOGGING_H
#define __LOGGING_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
typedef enum {
LOG_FATAL,
LOG_ERROR,
LOG_WARNING,
LOG_INFO,
LOG_DEBUG,
} log_level;
#include "logging/logging-core.h"
#include "logging/logging-handler.h"
#include "logging/logging-interceptor.h"
typedef enum {
L_ERROR,
L_OK,
} log_status;
// 日志操作器
typedef struct Logger {
log_level level;
log_Handler *handler;
log_Interceptor *interceptor;
const char *name;
void (*fatal)(const char *format, ...);
void (*error)(const char *format, ...);
void (*warning)(const char *format, ...);
void (*info)(const char *format, ...);
void (*debug)(const char *format, ...);
typedef struct log_Handler {
void* stream;
bool apply_color;
void (*_free)(struct log_Handler* handler);//释放资源
void (*output)(struct log_Handler* handler,const char* message);
} log_Handler;
typedef struct log_Interceptor {
log_level level; //拦截级别
log_Handler* handler; //拦截目标处理器
bool (*_dispose)(char* level,const char *message, ...); //拦截触发器
void (*_free)(struct log_Interceptor* Interceptor); //释放资源
} log_Interceptor;
//日志操作器
typedef struct Logger
{
log_level level;
log_Handler* handler;
log_Interceptor* interceptor;
const char* name;
void (*fatal)(const char* format, ...);
void (*error)(const char* format, ...);
void (*warning)(const char* format, ...);
void (*info)(const char* format, ...);
void (*debug)(const char* format, ...);
void (*addHandler)(log_Handler* handler);
// void (*addFormat)(const char* format);
// void (*addFilter)(const char* filter);
void (*addInterceptor)(log_Interceptor* Interceptor);
void (*addHandler)(log_Handler *handler);
void (*addInterceptor)(log_Interceptor *Interceptor);
} Logger;
//日志类对象
// 日志类对象
typedef struct Logging {
Logger* (*getLogger)(const char* name, log_level level);
log_status (*setLevel)(Logger* logger, log_level level);
Logger *(*getLogger)(const char *name, log_level level);
log_status (*setLevel)(Logger *logger, log_level level);
} Logging;
Logging *createLogging(); // 创建日志类对象
log_status destroyLogging(Logging *logging); // 销毁日志类对象
Logger *getCurrentLogger(void); // 获取当前日志记录器
Logging* createLogging();
log_status destroyLogging(Logging* logging);
Logger* getCurrentLogger(void);
/**
* @def 创建日志处理器
* @file logging-handler.c
*/
log_Handler* fileHandler(const char* name);
log_Handler* consoleHandler(const char* name);
log_Interceptor* substringInterceptor(char *keywords[], int count, log_level level, log_Handler* handler);
#endif // __LOGGING_H
#endif // __LOGGING_H__

View File

@@ -0,0 +1,18 @@
#ifndef __LOGGING_CORE_H__
#define __LOGGING_CORE_H__
typedef enum {
LOG_FATAL,
LOG_ERROR,
LOG_WARNING,
LOG_INFO,
LOG_DEBUG,
} log_level;
typedef enum {
L_ERROR,
L_OK,
} log_status;
#endif // __LOGGING_CORE_H__

View File

@@ -0,0 +1,17 @@
#ifndef __LOGGING_HANDLER_H__
#define __LOGGING_HANDLER_H__
#include <stdbool.h>
typedef struct log_Handler {
void* stream;
bool apply_color;
void (*_free)(struct log_Handler* handler);//释放资源
void (*output)(struct log_Handler* handler,const char* message);
} log_Handler;
log_Handler* fileHandler(const char* name);
log_Handler* consoleHandler();
#endif //__LOGGING_HANDLER_H__

View File

@@ -0,0 +1,20 @@
#ifndef __LOGGING_INTERCEPTOR_H__
#define __LOGGING_INTERCEPTOR_H__
#include "logging-core.h"
#include "logging-handler.h"
typedef struct log_Interceptor {
log_level level; // 拦截级别
log_Handler *handler; // 拦截目标处理器
bool (*_dispose)(char *level, const char *message, ...); // 拦截触发器
void (*_free)(struct log_Interceptor *Interceptor); // 释放资源
} log_Interceptor;
log_Interceptor *substringInterceptor(char *keywords[],
int count,
log_level level,
log_Handler *handler);
#endif // __LOGGING_INTERCEPTOR_H__

12
src/CMakeLists.txt Normal file
View File

@@ -0,0 +1,12 @@
project(Logging)
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SRC)
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/handler SRC)
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/interceptor SRC)
if (SHARED)
add_library(${PROJECT_NAME} SHARED ${SRC})
else()
add_library(${PROJECT_NAME} ${SRC})
endif()

View File

@@ -0,0 +1,37 @@
/********************************************
* @Date: 2024 09 18
* @Description: 控制台日志处理器
********************************************/
#include "logging/logging-handler.h"
#include <stdio.h>
#include <stdlib.h>
/**
* @brief 释放组件
* @param handler 处理器
*/
static void __freeConsoleHandler(log_Handler *handler) { free(handler); }
/**
* @brief 输出组件
* @param handler 处理器
* @param message 消息
*/
static void outputConsoleHandler(log_Handler *handler, const char *message) {
fputs(message, handler->stream);
}
/**
* @brief :控制台日志处理器
* @param
*/
log_Handler *consoleHandler() {
log_Handler *handler = (log_Handler *)malloc(sizeof(log_Handler));
handler->stream = stdout;
handler->apply_color = true;
handler->_free = __freeConsoleHandler;
handler->output = outputConsoleHandler;
return handler;
}

View File

@@ -0,0 +1,47 @@
/********************************************
* @Date: 2024 09 18
* @Description: 文件日志处理器
********************************************/
#include "logging/logging-handler.h"
#include <stdio.h>
#include <stdlib.h>
/**
* @brief 文件日志处理器释放组件
* @param
* @return
*/
static void __freeFileHandler(log_Handler *handler) {
fclose(handler->stream);
free(handler);
}
/**
* @brief 文件日志处理器输出组件
* @param
* @return
*/
static void outputFileHandler(log_Handler *handler, const char *message) {
fputs(message, handler->stream);
}
/**
* @brief 文件日志处理器
* @param
* @return
*/
log_Handler *fileHandler(const char *name) {
char new_file_name[100];
sprintf(new_file_name, "%s.log", name);
FILE *fp = fopen(new_file_name, "at");
log_Handler *handler = (log_Handler *)malloc(sizeof(log_Handler));
handler->stream = fp;
handler->apply_color = false;
handler->_free = __freeFileHandler;
handler->output = outputFileHandler;
return handler;
}

View File

@@ -0,0 +1,122 @@
/********************************************
* @Date: 2024 08 12
* @Description: 日志拦截器
*********************************************/
#include "logging/logging-interceptor.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static log_Interceptor *G_interceptor = NULL;
static char **G_keywords = NULL;
static void get_next(char *str, int *next) {
next[1] = 0;
int i = 1;
int j = 0;
while (i < strlen(str)) {
if (j == 0 || str[i] == str[j]) {
next[++i] = ++j;
} else {
j = next[j];
}
}
}
static bool kmp_search(char *substr, char *master) {
int i = 0;
int j = 0;
int substrlen = strlen(substr);
int masterlen = strlen(master);
int *next = (int *)malloc(sizeof(int) * substrlen + 1);
get_next(substr, next);
while (i < masterlen && j < substrlen) {
if (master[i] == substr[j]) {
i++;
j++;
} else {
if (j == 0) {
i++;
} else {
j = next[j];
}
}
}
free(next);
if (j == substrlen)
return true;
else
return false;
}
/**
* @description 处理
* @param
* @return
*/
static bool _disposeSubstring(char *level, const char *message, ...) {
int count = 0;
if (G_keywords == NULL) {
return false;
}
while (G_keywords[count] != NULL) {
if (kmp_search(G_keywords[count], (char *)message)) {
return true;
}
count++;
}
return false;
}
/**
* @description : 完成拦截器自我释放内存
*/
static void _freeSubstring(log_Interceptor *interceptor) {
int sum = 0;
while (G_keywords[sum] != NULL) {
free(G_keywords[sum]);
sum++;
}
free(G_keywords);
G_keywords = NULL;
if (interceptor->handler != NULL) {
interceptor->handler->_free(interceptor->handler);
}
free(interceptor);
}
/**
* @description : 子字符串拦截器
*/
log_Interceptor *substringInterceptor(char *keywords[],
int count,
log_level level,
log_Handler *handler) {
log_Interceptor *interceptor =
(log_Interceptor *)malloc(sizeof(log_Interceptor));
interceptor->_dispose = _disposeSubstring;
interceptor->handler = handler;
interceptor->level = level;
interceptor->_free = _freeSubstring;
G_keywords = (char **)malloc((sizeof(G_keywords) * count) + 1);
for (int i = 0; i < count; i++) {
G_keywords[i] = (char *)malloc(strlen(keywords[i]) + 1);
strcpy(G_keywords[i], keywords[i]);
}
G_keywords[count] = NULL;
G_interceptor = interceptor;
return G_interceptor;
}

View File

@@ -1,62 +0,0 @@
/********************************************
* @Date: 2024 08 12
* @Description: 日志处理器
********************************************/
#include "logging.h"
/**
* @description :释放文件日志处理器相关资源
* @param
* @return
*/
static void __freeFileHandler(log_Handler* handler){
fclose(handler->stream);
free(handler);
}
static void outputFileHandler(log_Handler *handler, const char * message){
fputs(message,handler->stream);
}
/**
* @description :文件日志处理器
* @param
* @return
*/
log_Handler* fileHandler(const char* name){
char new_file_name[100];
sprintf(new_file_name, "%s.log", name);
FILE* fp = fopen(new_file_name, "at");
log_Handler* handler = (log_Handler*)malloc(sizeof(log_Handler));
handler->stream = fp;
handler->apply_color = false;
handler->_free = __freeFileHandler;
handler->output = outputFileHandler;
return handler;
}
static void __freeConsoleHandler(log_Handler* handler){
free(handler);
}
static void outputConsoleHandler(log_Handler* handler,const char * message){
fputs(message,handler->stream);
}
/**
* @description :控制台日志处理器
* @param
* @return
*/
log_Handler* consoleHandler(const char* name){
log_Handler* handler = (log_Handler*)malloc(sizeof(log_Handler));
handler->stream = stdout;
handler->apply_color = true;
handler->_free = __freeConsoleHandler;
handler->output = outputConsoleHandler;
return handler;
}

View File

@@ -1,119 +0,0 @@
/********************************************
* @Date: 2024 08 12
* @Description: 日志拦截器
*********************************************/
#include "logging.h"
static log_Interceptor* G_interceptor = NULL;
static char **G_keywords = NULL;
static void get_next(char *str, int *next) {
next[1] = 0;
int i=1;
int j=0;
while (i < strlen(str)) {
if (j==0|| str[i] == str[j]) {
next[++i] = ++j;
}
else {
j = next[j];
}
}
}
static bool kmp_search(char *substr, char *master) {
int i = 0;
int j = 0;
int substrlen = strlen(substr);
int masterlen = strlen(master);
int *next = (int *)malloc(sizeof(int) * substrlen + 1);
get_next(substr, next);
while (i < masterlen && j < substrlen) {
if (master[i] == substr[j]) {
i++;
j++;
} else {
if(j == 0) {
i++;
} else {
j = next[j];
}
}
}
free(next);
if (j == substrlen)return true;
else return false;
}
/**
* @description 处理
* @param
* @return
*/
static bool _disposeSubstring(char* level,const char *message, ...){
int count = 0;
if (G_keywords == NULL) {
return false;
}
while (G_keywords[count] != NULL)
{
if (kmp_search(G_keywords[count],(char*)message)) {
return true;
}
count++;
}
return false;
}
/**
* @description : 完成拦截器自我释放内存
*/
static void _freeSubstring(log_Interceptor* interceptor) {
int sum = 0;
while (G_keywords[sum] != NULL) {
free(G_keywords[sum]);
sum++;
}
free(G_keywords);
G_keywords = NULL;
if(interceptor->handler != NULL){
interceptor->handler->_free(interceptor->handler);
}
free(interceptor);
}
/**
* @description : 子字符串拦截器
*/
log_Interceptor* substringInterceptor(char *keywords[], int count, log_level level, log_Handler* handler) {
log_Interceptor* interceptor = (log_Interceptor*)malloc(sizeof(log_Interceptor));
interceptor->_dispose = _disposeSubstring;
interceptor->handler = handler;
interceptor->level = level;
interceptor->_free = _freeSubstring;
G_keywords = (char**)malloc( (sizeof(G_keywords)*count) + 1);
for (int i = 0; i < count; i++) {
G_keywords[i] = (char*)malloc(strlen(keywords[i])+1);
strcpy(G_keywords[i], keywords[i]);
}
G_keywords[count] = NULL;
G_interceptor = interceptor;
return G_interceptor;
}

View File

@@ -1,55 +1,64 @@
/********************************************
* @Date: 2024 08 12
* @Description: 日志模块
********************************************/
* @Date: 2024 08 12
* @Description: 日志模块
********************************************/
#include "logging.h"
#include "logging/logging-handler.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
Logger* G_LOGGER = NULL;
Logger *G_LOGGER = NULL;
#define RED "\033[0;31m"
#define GREEN "\033[0;32m"
#define YELLOW "\033[0;33m"
#define BLUE "\033[0;34m"
#define RESET "\033[0m"
#define CYAN "\033[0;36m"
#define RED "\033[0;31m"
#define GREEN "\033[0;32m"
#define YELLOW "\033[0;33m"
#define BLUE "\033[0;34m"
#define RESET "\033[0m"
#define CYAN "\033[0;36m"
#define MAGENTA "\033[0;35m"
#define WHITE "\033[0;37m"
#define BLACK "\033[0;30m"
#define WHITE "\033[0;37m"
#define BLACK "\033[0;30m"
#define LOG_BUFFER_SIZE 1024
static void getTimeStr(char * timeStr){
time_t t = time(NULL);
struct tm* p = localtime(&t);
char _timeStr[20];
static void getTimeStr(char *timeStr) {
time_t t = time(NULL);
struct tm *p = localtime(&t);
char _timeStr[20];
strftime(_timeStr, sizeof(_timeStr), "%Y-%m-%d %H:%M:%S", p);
strcpy(timeStr, _timeStr);
}
/**
* @description : 添加日志处理器
*/
static void addHandler(log_Handler* handler){
if (G_LOGGER == NULL){
* @description : 添加日志处理器
*/
static void addHandler(log_Handler *handler) {
if (G_LOGGER == NULL) {
return;
}
if (G_LOGGER->handler == NULL){
if (G_LOGGER->handler == NULL) {
G_LOGGER->handler = handler;
return;
}
G_LOGGER->handler->_free(G_LOGGER->handler);
G_LOGGER->handler = handler;
}
void addInterceptor(log_Interceptor* Interceptor){
if (G_LOGGER == NULL){
/**
* @description : 添加日志拦截器
* @param
* @return
*/
void addInterceptor(log_Interceptor *Interceptor) {
if (G_LOGGER == NULL) {
return;
}
if (G_LOGGER->interceptor == NULL){
if (G_LOGGER->interceptor == NULL) {
G_LOGGER->interceptor = Interceptor;
return;
}
@@ -60,149 +69,150 @@ void addInterceptor(log_Interceptor* Interceptor){
}
/**
* @description : 内置日志记录函数
*/
static void _builtin_log(char* level, const char *color, const char* message, ...){
if (G_LOGGER == NULL){
* @description : 内置日志记录函数
*/
static void
_builtin_log(char *level, const char *color, const char *message, ...) {
if (G_LOGGER == NULL) {
return;
}
if (G_LOGGER->handler == NULL){
if (G_LOGGER->handler == NULL) {
return;
}
char timeStr[20];
getTimeStr(timeStr);
char logStr[LOG_BUFFER_SIZE];
log_Handler * handler = G_LOGGER->handler;
log_Handler *handler = G_LOGGER->handler;
//通过拦截器
if (G_LOGGER->interceptor != NULL){
if(G_LOGGER->interceptor->_dispose(level,message)){
if(G_LOGGER->interceptor->handler != NULL){
// 通过拦截器
if (G_LOGGER->interceptor != NULL) {
if (G_LOGGER->interceptor->_dispose(level, message)) {
if (G_LOGGER->interceptor->handler != NULL) {
handler = G_LOGGER->interceptor->handler;
}
}
}
//判断处理器是否应用颜色
if (handler->apply_color) sprintf(logStr, "%s %s%s%s %s\n", timeStr, color,level,RESET, message);
else sprintf(logStr, "%s %s %s\n", timeStr, level, message);
// 判断处理器是否应用颜色
if (handler->apply_color)
sprintf(
logStr, "%s %s%s%s %s\n", timeStr, color, level, RESET, message);
else
sprintf(logStr, "%s %s %s\n", timeStr, level, message);
handler->output(handler,logStr);
handler->output(handler, logStr);
}
//*************************记录日志******************************* */
static void fatal(const char* message, ...){
if (G_LOGGER->level >= LOG_ERROR){
char logStr[LOG_BUFFER_SIZE];
static void fatal(const char *message, ...) {
if (G_LOGGER->level >= LOG_ERROR) {
char logStr[LOG_BUFFER_SIZE];
va_list args;
va_start(args, message);
vsprintf(logStr, message, args);
va_end(args);
_builtin_log("Fatal",RED, logStr, args);
_builtin_log("Fatal", RED, logStr, args);
}
}
static void error(const char* message, ...){
if (G_LOGGER->level >= LOG_ERROR){
char logStr[LOG_BUFFER_SIZE];
static void error(const char *message, ...) {
if (G_LOGGER->level >= LOG_ERROR) {
char logStr[LOG_BUFFER_SIZE];
va_list args;
va_start(args, message);
vsprintf(logStr, message, args);
va_end(args);
_builtin_log("Error",RED, logStr, args);
_builtin_log("Error", RED, logStr, args);
}
}
static void warning(const char* message, ...){
if (G_LOGGER->level >= LOG_WARNING){
char logStr[LOG_BUFFER_SIZE];
static void warning(const char *message, ...) {
if (G_LOGGER->level >= LOG_WARNING) {
char logStr[LOG_BUFFER_SIZE];
va_list args;
va_start(args, message);
vsprintf(logStr, message, args);
va_end(args);
_builtin_log("Warning",YELLOW, logStr, args);
_builtin_log("Warning", YELLOW, logStr, args);
}
}
static void info(const char* message, ...){
if (G_LOGGER->level >= LOG_INFO){
char logStr[LOG_BUFFER_SIZE];
static void info(const char *message, ...) {
if (G_LOGGER->level >= LOG_INFO) {
char logStr[LOG_BUFFER_SIZE];
va_list args;
va_start(args, message);
vsprintf(logStr, message, args);
va_end(args);
_builtin_log("Info",GREEN, logStr, args);
_builtin_log("Info", GREEN, logStr, args);
}
}
static void debug(const char* message, ...){
if (G_LOGGER->level >= LOG_DEBUG){
char logStr[LOG_BUFFER_SIZE];
static void debug(const char *message, ...) {
if (G_LOGGER->level >= LOG_DEBUG) {
char logStr[LOG_BUFFER_SIZE];
va_list args;
va_start(args, message);
vsprintf(logStr, message, args);
va_end(args);
_builtin_log("Debug",CYAN, logStr, args);
_builtin_log("Debug", CYAN, logStr, args);
}
}
//*************************记录日志******************************* */
/**
* @description :获取一个日志操作对象
* @param
* @return
*/
static Logger* getLogger(const char* name, log_level level){
if (G_LOGGER != NULL){
* @description :获取一个日志操作对象
* @param
* @return
*/
static Logger *getLogger(const char *name, log_level level) {
if (G_LOGGER != NULL) {
return G_LOGGER;
}
Logger* logger = (Logger*)malloc(sizeof(Logger));
logger->fatal = fatal;
logger->error = error;
logger->warning = warning;
logger->info = info;
logger->debug = debug;
Logger *logger = (Logger *)malloc(sizeof(Logger));
logger->fatal = fatal;
logger->error = error;
logger->warning = warning;
logger->info = info;
logger->debug = debug;
logger->addHandler = addHandler;
logger->addHandler = addHandler;
logger->addInterceptor = addInterceptor;
logger->level = level;
logger->handler = NULL;
logger->name = name;
logger->interceptor = NULL;
logger->level = level;
logger->handler = consoleHandler(name);
logger->name = name;
logger->interceptor = NULL;
G_LOGGER = logger;
G_LOGGER = logger;
return G_LOGGER;
}
/**
* @description :创建一个日志对象
* @return :Logging* 返回一个日志对象
*/
Logging* createLogging(){
Logging* logging = (Logging*)malloc(sizeof(Logging));
* @description :创建一个日志对象
* @return :Logging* 返回一个日志对象
*/
Logging *createLogging() {
Logging *logging = (Logging *)malloc(sizeof(Logging));
logging->getLogger = getLogger;
return logging;
}
/**
* @description :销毁日志对象
*/
log_status destroyLogging(Logging* logging){
if (logging == NULL){
* @description :销毁日志对象
*/
log_status destroyLogging(Logging *logging) {
if (logging == NULL) {
return L_ERROR;
}
if (G_LOGGER != NULL){
if (G_LOGGER->handler != NULL){
if (G_LOGGER != NULL) {
if (G_LOGGER->handler != NULL) {
G_LOGGER->handler->_free(G_LOGGER->handler);
}
if (G_LOGGER->interceptor != NULL){
if (G_LOGGER->interceptor != NULL) {
G_LOGGER->interceptor->_free(G_LOGGER->interceptor);
}
@@ -213,16 +223,13 @@ log_status destroyLogging(Logging* logging){
return L_OK;
}
/**
* @description :获取当前日志操作对象
* @return 当前唯一的日志操作对象
*/
Logger* getCurrentLogger(void){
if (G_LOGGER == NULL){
* @description :获取当前日志操作对象
* @return 当前唯一的日志操作对象
*/
Logger *getCurrentLogger(void) {
if (G_LOGGER == NULL) {
return NULL;
}
return G_LOGGER;
}

8
tests/CMakeLists.txt Normal file
View File

@@ -0,0 +1,8 @@
project(test)
add_executable(${PROJECT_NAME}simple test_simple.c)
target_link_libraries(${PROJECT_NAME}simple Logging)
add_executable(${PROJECT_NAME}interceptor test_interceptor.c)
target_link_libraries(${PROJECT_NAME}interceptor Logging)

View File

@@ -1,9 +1,9 @@
#include "logging.h"
#include <stdio.h>
int main() {
Logging *log = createLogging();
Logger *logger = log->getLogger("testLogger",LOG_DEBUG);
logger->addHandler(consoleHandler("test"));
Logging *log = createLogging();
Logger *logger = log->getLogger("testLogger", LOG_DEBUG);
logger->info("This is an info message");
logger->error("你好,这是一个错误消息%s", "123");
@@ -11,16 +11,16 @@ int main() {
logger->debug("This is a debug message");
logger->warning("This is a warning message%s", "123");
char *test1[] = {"123", "你好"};//要拦截的字符串
//添加拦截器,将拦截到的日志重定向到拦截器的专属处理器中
log_Interceptor * tint = substringInterceptor(test1,2,LOG_DEBUG,fileHandler("被拦截"));
char *test1[] = {"123", "你好"}; // 要拦截的字符串
// 添加拦截器,将拦截到的日志重定向到拦截器的专属处理器中
log_Interceptor *tint =
substringInterceptor(test1, 2, LOG_DEBUG, fileHandler("被拦截"));
logger->addInterceptor(tint);
printf("Interceptor added\n");
logger->info("This is an info message");
logger->error("你好,这是一个错误消息%s", "123");
logger->fatal("This is an fatal message");
logger->debug("This is a debug message");
logger->warning("This is a warning message%s", "123");

View File

@@ -4,13 +4,13 @@
int main() {
Logging *log = createLogging();
Logger *logger = log->getLogger("testLogger",LOG_DEBUG);
logger->addHandler(consoleHandler("test"));
logger->info("This is an info message");
logger->error("你好,这是一个错误消息%s", "123");
logger->fatal("This is an fatal message");
logger->debug("This is a debug message");
logger->warning("This is a warning message%s", "123");
destroyLogging(log);
return 0;