Full Code of 0xmalloc/c-log for AI

master 29349a67d5ad cached
14 files
24.1 KB
6.8k tokens
20 symbols
1 requests
Download .txt
Repository: 0xmalloc/c-log
Branch: master
Commit: 29349a67d5ad
Files: 14
Total size: 24.1 KB

Directory structure:
gitextract_2z6_6gxs/

├── LICENSE
├── README.md
├── src/
│   ├── log.c
│   ├── log.h
│   └── macro_define.h
├── test/
│   ├── bench_test
│   ├── bench_test.c
│   ├── build.sh
│   ├── test.c
│   ├── test_log
│   ├── test_pthread_log
│   ├── thread_test.c
│   └── ultimate_test.c
└── 开源c-log日志库

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                                 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.


================================================
FILE: README.md
================================================
## C-LOG
[![Release Version](https://img.shields.io/badge/release-1.0.0-red.svg)](https://github.com/0xmalloc/c-log/releases) 

## What is c-log
a fast ,stable and thread-safe log lib(logger) for C/C++ language

## How to Use 
you can use  "sh build.sh" to build the testing application and also i suggest you to `run "./bench_test" (single_thread)to see the performance`

you can use this log module by the follow  guiding:
```cpp
    log_init(LL_TRACE, "mysql", "./log/");
	LOG_NOTICE("%s [time:%d]", "test calling log", time(NULL));
	LOG_DEBUG("debug msg,only write to log when the loglevel bigger than or equal to debug [time:%d]", time(NULL));
	LOG_WARN("warnning msg will be writing to the error files [time:%d]", time(NULL));
	LOG_ERROR("you also can change  number of output files by rewrite the macro_define.h");
```
and also you don't need to call close befor your application exit
if you insist to calling close,please use WARN_W.log_close() INFO_W.log_close() and so so.

this module also provide some convenient macro, you can use it in the following scene
```cpp
    int function()
	{
		int ret;
		if()
		{
			ret = function_call();
			MACRO_RET(ret != 0, -1);
			MACRO_WARN(ret != 0, "function call failed  [ret:%d]", ret);
			MACRO_WARN_RET(ret != 0, -1, "function call failed  [ret:%d]", ret)
			
		}
	}
```
The performance of this log module is really depend on how fast your disk is.
here is test result:

    case 1
        Record Size: 280kb
    	Cost Time: 42 seconds
    	Data File Size: 20GB
    	yes. we write 20GB file in 102s,that's means we write 200MB per second.and
    	also this is the limitation of SATA.

    case 2 
        Record Size: 56byte
    	Record Write per Senconds:200,000
    	yes,in it's general useage,you can gain high qps from this log module

what will be the next?


## About Author

```javascript
  var 0xmalloc = {
    nickName  : "zealot yin",
    email : '0xmalloc@gmail.com',
    site : "http://www.cnblogs.com/Creator/"
    weibo : "http://www.weibo.com/zealotyin"
  }
```


================================================
FILE: src/log.c
================================================
#include "log.h"
#include <sys/file.h>
#include <stdarg.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

Log_Writer WARN_W;
Log_Writer INFO_W;
__thread char Log_Writer::m_buffer[_LOG_BUFFSIZE];

bool log_init(LogLevel l, const char* p_modulename, const char* p_logdir)
{
	//如果路径存在文件夹,则判断是否存在
	if (access (p_logdir, 0) == -1)
	{
		if (mkdir (p_logdir, S_IREAD | S_IWRITE ) < 0)
			fprintf(stderr, "create folder failed\n");
	}
	char _location_str[_LOG_PATH_LEN];
	snprintf(_location_str, _LOG_PATH_LEN, "%s/%s.access", p_logdir, p_modulename);	
	INFO_W.loginit(l, _location_str);
	snprintf(_location_str, _LOG_PATH_LEN, "%s/%s.error", p_logdir, p_modulename);
	//warning级别以上日志去WARN_W  去向由宏决定的 请见macro_define.h
	if(l > LL_WARNING)
		WARN_W.loginit(l, _location_str);
	else
		WARN_W.loginit(LL_WARNING, _location_str);
	return true;
}

const char* Log_Writer::logLevelToString(LogLevel l) {
        switch ( l ) {
			case LL_DEBUG:
				return "DEBUG";
			case LL_TRACE:
				return "TRACE";
			case LL_NOTICE:
				return "NOTICE";
			case LL_WARNING:
				return "WARN" ;
			case LL_ERROR:
				return "ERROR";
			default:
				return "UNKNOWN";
        }
}
	
bool Log_Writer::checklevel(LogLevel l)
{
	if(l >= m_system_level)
		return true;
	else
		return false;
}

bool Log_Writer::loginit(LogLevel l, const  char *filelocation, bool append, bool issync)
{
	MACRO_RET(NULL != fp, false);
    m_system_level = l;
    m_isappend = append; 
    m_issync = issync; 
	if(strlen(filelocation) >= (sizeof(m_filelocation) -1))
	{
		fprintf(stderr, "the path of log file is too long:%d limit:%d\n", strlen(filelocation), sizeof(m_filelocation) -1);
		exit(0);
	}
	//本地存储filelocation  以防止在栈上的非法调用调用
	strncpy(m_filelocation, filelocation, sizeof(m_filelocation));
	m_filelocation[sizeof(m_filelocation) -1] = '\0';
	
	if('\0' == m_filelocation[0])
	{
		fp = stdout;
		fprintf(stderr, "now all the running-information are going to put to stderr\n");
		return true;
	}
	
	fp = fopen(m_filelocation, append ? "a":"w");
	if(fp == NULL)
	{
		fprintf(stderr, "cannot open log file,file location is %s\n", m_filelocation);
		exit(0);
	}
	//setvbuf (fp, io_cached_buf, _IOLBF, sizeof(io_cached_buf)); //buf set _IONBF  _IOLBF  _IOFBF
	setvbuf (fp,  (char *)NULL, _IOLBF, 0);
	fprintf(stderr, "now all the running-information are going to the file %s\n", m_filelocation);
	return true;
}

int Log_Writer::premakestr(char* m_buffer, LogLevel l)
{
    time_t now;
	now = time(&now);;
	struct tm vtm; 
    localtime_r(&now, &vtm);
    return snprintf(m_buffer, _LOG_BUFFSIZE, "%s: %02d-%02d %02d:%02d:%02d ", logLevelToString(l),
            vtm.tm_mon + 1, vtm.tm_mday, vtm.tm_hour, vtm.tm_min, vtm.tm_sec);
}

bool Log_Writer::log(LogLevel l, char* logformat,...)
{
	MACRO_RET(!checklevel(l), false);
	int _size;
	int prestrlen = 0;
	
	char * star = m_buffer;
	prestrlen = premakestr(star, l);
	star += prestrlen;
	
	va_list args;
	va_start(args, logformat);
	_size = vsnprintf(star, _LOG_BUFFSIZE - prestrlen, logformat, args);
	va_end(args);
	
	if(NULL == fp)
		fprintf(stderr, "%s", m_buffer);
	else
		_write(m_buffer, prestrlen + _size);
	return true;
}

bool Log_Writer::_write(char *_pbuffer, int len)
{
	if(0 != access(m_filelocation, W_OK))
	{	
		pthread_mutex_lock(&m_mutex);
		//锁内校验 access 看是否在等待锁过程中被其他线程loginit了  避免多线程多次close 和init
		if(0 != access(m_filelocation, W_OK))
		{
			logclose();
			loginit(m_system_level, m_filelocation, m_isappend, m_issync);
		}
		pthread_mutex_unlock(&m_mutex);
	}

	if(1 == fwrite(_pbuffer, len, 1, fp)) //only write 1 item
	{
		if(m_issync)
          	fflush(fp);
		*_pbuffer='\0';
    }
    else 
	{
        int x = errno;
	    fprintf(stderr, "Failed to write to logfile. errno:%s    message:%s", strerror(x), _pbuffer);
	    return false;
	}
	return true;
}

LogLevel Log_Writer::get_level()
{
	return m_system_level; 
}

bool Log_Writer::logclose()
{
	if(fp == NULL)
		return false;
	fflush(fp);
	fclose(fp);
	fp = NULL;
	return true;
}





================================================
FILE: src/log.h
================================================
#ifndef   _MACRO_LogModule
#define   _MACRO_LogModule
#include <stdio.h>
#include <pthread.h>
#include "macro_define.h"

/* ÿ̵߳buffer size*/
#define   _LOG_BUFFSIZE  1024*1024*4
/* ǰ̵ Stream IO buffer size*/
#define   _SYS_BUFFSIZE  1024*1024*8
/* log ļַ·󳤶*/
#define	  _LOG_PATH_LEN  250
/* ־Ӧģ*/
#define   _LOG_MODULE_LEN 32

typedef  enum LogLevel {  
	LL_DEBUG = 1,
	LL_TRACE = 2,
	LL_NOTICE = 3, 
	LL_WARNING = 4, 
	LL_ERROR = 5,
}LogLevel;

/**
*	Log_Writer  ־
*/
class Log_Writer
{
	public:
		Log_Writer()
		{
			m_system_level = LL_NOTICE;
			//fp = stderr;
			fp = NULL;
			m_issync = false;
			m_isappend = true;
			m_filelocation[0] ='\0'; 
			pthread_mutex_init(&m_mutex, NULL);
		}
		~Log_Writer(){
			logclose();
		}
		bool loginit(LogLevel l, const  char *filelocation, bool append = true, bool issync = false);
		bool log(LogLevel l,char *logformat,...);
		LogLevel get_level();
		bool logclose();
	private:
		const char* logLevelToString(LogLevel l);
		bool checklevel(LogLevel l);
		int premakestr(char* m_buffer, LogLevel l);
		bool _write(char *_pbuffer, int len);
	private:
		enum LogLevel m_system_level;
		FILE* fp;
		bool m_issync;
		bool m_isappend;
		char m_filelocation[_LOG_PATH_LEN];
		pthread_mutex_t m_mutex;
		static __thread char m_buffer[_LOG_BUFFSIZE];
		//The __thread specifier may be applied to any global, file-scoped static, function-scoped static, 
		//or static data member of a class. It may not be applied to block-scoped automatic or non-static data member
		//in the log  scence,It's safe!!!!
		//һԱ֮˳õ__threadԴleak,ͬʱҲõĶLog_Writerţ
		//Ϊһ߳ͬһʱֻһLog_Writerڸɻ֮m_bufferreset
		//Լһ߳ûLog_Write(Ϊһ߳ڵֻ̬д) Ҳ̰߳ȫģ
};

extern Log_Writer WARN_W;
extern Log_Writer INFO_W;

/**
 * LogLevel ־
 * p_modulename ģ mysql
 * p_logdir  ־Ŀ¼
 * */
bool log_init(LogLevel l, const char* p_modulename, const char* p_logdir);
#endif


================================================
FILE: src/macro_define.h
================================================
#ifndef  _MACRO_DEFINE
#define  _MACRO_DEFINE
//============basic===================

#define LOG_ERROR(log_fmt, log_arg...) \
    do{ \
        WARN_W.log(LL_ERROR,   "[%s:%d][%s] " log_fmt "\n", \
                     __FILE__, __LINE__, __FUNCTION__, ##log_arg); \
    } while (0) 

#define LOG_WARN(log_fmt, log_arg...) \
    do{ \
        WARN_W.log(LL_WARNING,   "[%s:%d][%s] " log_fmt "\n", \
                     __FILE__, __LINE__, __FUNCTION__, ##log_arg); \
    } while (0) 

#define LOG_NOTICE(log_fmt, log_arg...) \
    do{ \
        INFO_W.log(LL_NOTICE,   "[%s:%d][%s] " log_fmt "\n", \
                     __FILE__, __LINE__, __FUNCTION__, ##log_arg); \
    } while (0) 

#define LOG_TRACE(log_fmt, log_arg...) \
    do{ \
        INFO_W.log(LL_TRACE,   "[%s:%d][%s] " log_fmt "\n", \
                     __FILE__, __LINE__, __FUNCTION__, ##log_arg); \
    } while (0) 

#define LOG_DEBUG(log_fmt, log_arg...) \
    do{ \
        INFO_W.log(LL_DEBUG,   "[%s:%d][%s] " log_fmt "\n", \
                     __FILE__, __LINE__, __FUNCTION__, ##log_arg); \
    } while (0) 

//============extend===================
#define MACRO_RET(condition, return_val) {\
    if (condition) {\
        return return_val;\
    }\
}

#define MACRO_WARN(condition, log_fmt, log_arg...) {\
    if (condition) {\
        LOG_WARN( log_fmt, ##log_arg);\
    }\
}

#define MACRO_WARN_RET(condition, return_val, log_fmt, log_arg...) {\
    if ((condition)) {\
        LOG_WARN( log_fmt, ##log_arg);\
		return return_val;\
    }\
}
#endif


================================================
FILE: test/bench_test.c
================================================
#include "log.h"
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

/*
 * 单线程压力测试
 * */
int common_test()
{
	LOG_DEBUG("testing write log befor log_init: %s", "haha");
}

void test01()
{
    //init  log
	//log_init(LL_TRACE, "mysql", "./log");
	log_init(LL_TRACE, "bench", "./");
    
	int i;
	char _strbuf[1024*1024*4];

	char *_log_str = "You got something wrong here";	
	for(i = 0; i < 10000; i++)
	{
		strncat(_strbuf, _log_str, strlen(_log_str));
	}
	printf("Log size of each log:%d", strlen(_strbuf));	
	for(i = 0; i < 1000000000; i++)
	{
		LOG_NOTICE("%s [value:%d]", _strbuf, i);
    }
}

int main()
{
    test01();
}


================================================
FILE: test/build.sh
================================================
#!/bin/bash
SRCPATH="../src/"
rm -f test_log test_pthread_log ultimate_test
g++ -o test_log  "$SRCPATH"log.c    test.c  -lpthread  -I "$SRCPATH"
g++ -o bench_test  "$SRCPATH"log.c    bench_test.c  -lpthread  -I "$SRCPATH"
g++ -o test_pthread_log  "$SRCPATH"log.c    thread_test.c -lpthread -I "$SRCPATH"
g++ -o ultimate_test  "$SRCPATH"log.c    ultimate_test.c  -I "$SRCPATH"

if ls *.access >/dev/null 2>/dev/null  
then
	rm *.access
fi
if ls *.error >/dev/null 2>/dev/null  
then 
	rm *.error
fi


================================================
FILE: test/test.c
================================================
#include "log.h"
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
/*
 * 基本功能测试
 */
int common_test()
{
	LOG_DEBUG("testing write log befor log_init: %s", "haha");
}

void test01()
{
	//测试init 之前调用log_wwarn的结果
	common_test();
    //init  log
	//log_init(LL_TRACE, "mysql", "./log");
	log_init(LL_DEBUG, "mysql", "./");
    
	int i;
	char _strbuf[200*1024];

	char *_log_str = "You got something wrong here";	
	for(i = 0; i < 1; i++)
	{
		strncat(_strbuf, _log_str, strlen(_log_str));
	}
	common_test(); 
	
	for(i = 0; i < 10; i++)
	{
		//sleep(1);
		if(0 == (i% 5))
			LOG_NOTICE("%s [value:%d] [xx:%d]", _strbuf, i, 10);
		else if(1 == i % 5)
			LOG_DEBUG("%s [value:%d]", _strbuf, i); 
		else if (2 == i % 5)
			LOG_TRACE("%s [value:%d]", _strbuf, i);
		else if (3 == i % 5)
			LOG_WARN("%s [value:%d]", _strbuf, i);
		else 
			LOG_ERROR("%s [value:%d]", _strbuf, i);
    }
}

int main()
{
    test01();
		
}


================================================
FILE: test/thread_test.c
================================================
#include "log.h"
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
/*
 * 测试是否多线程安全
 * */
bool quit = false;
void signal_handler(int sig){
	switch(sig){
		case SIGTERM:
		case SIGINT:
			quit = true;
			break;
	}
	printf("bingo sig\n");
}

void* test01(void *)
{
    int i;
	char _strbuf[200*1024];

	char *_log_str = "You got something wrong here";	
	for(i = 0; i < 1; i++)
	{
		strncat(_strbuf, _log_str, strlen(_log_str));
	}

    for(i=0;i<1000000000;i++)
	{
		//测试日志是否立即写入到文件
		sleep(1);
		if(0 == (i% 5)) 
            LOG_NOTICE("%s [value:%d]", _strbuf, i);
        else if(1 == i % 5)
            LOG_DEBUG("%s [value:%d]", _strbuf, i); 
        else if (2 == i % 5)
            LOG_TRACE("%s [value:%d]", _strbuf, i);
        else if (3 == i % 5)
            LOG_WARN("%s [value:%d]", _strbuf, i);
        else    
            LOG_ERROR("%s [value:%d]", _strbuf, i);	
		if(quit)
			break;
    }
}

int main()
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
	log_init(LL_TRACE, "session", "./");
	
	pthread_t pid[20];
	int i = 0;
	int ret = 0;
	for(; i < 20; i++)
	{
		ret = pthread_create(&pid[i], NULL, test01, NULL);
		MACRO_WARN_RET(0 != ret, -1, "pthread_create error[ret:%d]", ret)
	}
	for(i = 0; i < 20; i++)
	{
		pthread_join(pid[i], NULL);
	}
		
}


================================================
FILE: test/ultimate_test.c
================================================
#include "log.h"
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void sig_alarm (int signo)
{
	exit (0);
}
int main()
{
	alarm (10);
	if (signal (SIGALRM, sig_alarm) == SIG_ERR)
	{
		printf("%s\n", "signal error");
	}
	log_init (LL_DEBUG, "ultimate_test", "./");
	while (1)
	{
		LOG_TRACE("This is a test message!!!");
	}
	return 0;
}


================================================
FILE: 开源c-log日志库
================================================
开源的c-log日志库,支持c/c++
Download .txt
gitextract_2z6_6gxs/

├── LICENSE
├── README.md
├── src/
│   ├── log.c
│   ├── log.h
│   └── macro_define.h
├── test/
│   ├── bench_test
│   ├── bench_test.c
│   ├── build.sh
│   ├── test.c
│   ├── test_log
│   ├── test_pthread_log
│   ├── thread_test.c
│   └── ultimate_test.c
└── 开源c-log日志库
Download .txt
SYMBOL INDEX (20 symbols across 6 files)

FILE: src/log.c
  function log_init (line 15) | bool log_init(LogLevel l, const char* p_modulename, const char* p_logdir)
  function checklevel (line 52) | bool Log_Writer::checklevel(LogLevel l)
  function loginit (line 60) | bool Log_Writer::loginit(LogLevel l, const  char *filelocation, bool app...
  function premakestr (line 94) | int Log_Writer::premakestr(char* m_buffer, LogLevel l)
  function log (line 104) | bool Log_Writer::log(LogLevel l, char* logformat,...)
  function _write (line 126) | bool Log_Writer::_write(char *_pbuffer, int len)
  function LogLevel (line 155) | LogLevel Log_Writer::get_level()
  function logclose (line 160) | bool Log_Writer::logclose()

FILE: src/log.h
  type LogLevel (line 16) | typedef  enum LogLevel {
  function class (line 27) | class Log_Writer

FILE: test/bench_test.c
  function common_test (line 10) | int common_test()
  function test01 (line 15) | void test01()
  function main (line 36) | int main()

FILE: test/test.c
  function common_test (line 9) | int common_test()
  function test01 (line 14) | void test01()
  function main (line 48) | int main()

FILE: test/thread_test.c
  function signal_handler (line 11) | void signal_handler(int sig){
  function main (line 51) | int main()

FILE: test/ultimate_test.c
  function sig_alarm (line 6) | void sig_alarm (int signo)
  function main (line 10) | int main()
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (27K chars).
[
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 2094,
    "preview": "## C-LOG\r\n[![Release Version](https://img.shields.io/badge/release-1.0.0-red.svg)](https://github.com/0xmalloc/c-log/rel"
  },
  {
    "path": "src/log.c",
    "chars": 4040,
    "preview": "#include \"log.h\"\n#include <sys/file.h>\n#include <stdarg.h>\n#include <time.h>\n#include <stdlib.h>\n#include <string.h>\n#in"
  },
  {
    "path": "src/log.h",
    "chars": 1855,
    "preview": "#ifndef   _MACRO_LogModule\n#define   _MACRO_LogModule\n#include <stdio.h>\n#include <pthread.h>\n#include \"macro_define.h\"\n"
  },
  {
    "path": "src/macro_define.h",
    "chars": 1531,
    "preview": "#ifndef  _MACRO_DEFINE\n#define  _MACRO_DEFINE\n//============basic===================\n\n#define LOG_ERROR(log_fmt, log_arg"
  },
  {
    "path": "test/bench_test.c",
    "chars": 655,
    "preview": "#include \"log.h\"\n#include <string.h>\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n\n/*\n * 单线程压力测试\n * */\nint"
  },
  {
    "path": "test/build.sh",
    "chars": 498,
    "preview": "#!/bin/bash\nSRCPATH=\"../src/\"\nrm -f test_log test_pthread_log ultimate_test\ng++ -o test_log  \"$SRCPATH\"log.c    test.c  "
  },
  {
    "path": "test/test.c",
    "chars": 940,
    "preview": "#include \"log.h\"\n#include <string.h>\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n/*\n * 基本功能测试\n */\nint com"
  },
  {
    "path": "test/thread_test.c",
    "chars": 1371,
    "preview": "#include \"log.h\"\n#include <string.h>\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n#include <pthread.h>\n/*\n"
  },
  {
    "path": "test/ultimate_test.c",
    "chars": 348,
    "preview": "#include \"log.h\"\n#include <unistd.h>\n#include <stdlib.h>\n#include <signal.h>\n\nvoid sig_alarm (int signo)\n{\n\texit (0);\n}\n"
  },
  {
    "path": "开源c-log日志库",
    "chars": 20,
    "preview": "开源的c-log日志库,支持c/c++\n"
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the 0xmalloc/c-log GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (24.1 KB), approximately 6.8k tokens, and a symbol index with 20 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!