linux c/c++ 后台开发常用组件之:c++日志模块

日志是服务端开发必不可少的模块,工作过几个公司,基本每个公司或者项目组都有自己的日志模块,有使用开源的,也有自己写的,这是自己写的一个日志模块,经过线上大并发的测试,性能良好,使用也较方便。该日志采用的是单例模式,支持自动按天分文件,按日志行数自动分文件,是多线程安全的单例模式,没有外部依赖,linux操作系统均可以使用。在日志安全级别高的情况,不能丢失日志的情况,可以使用同步模式, 在要求应用程序性能高对日志安全级别不高的情况可以使用异步模式,异步模式就是在程序异常奔溃或者是重启服务的情况可能有日志丢失。

  1. /******************************************** 
  2. function: thread safe blocking queue. 
  3. author: liuyi 
  4. date: 2014.11.13 
  5. version: 2.0 
  6. ********************************************/  
  7.   
  8. #ifndef BLOCK_QUEUE_H  
  9. #define BLOCK_QUEUE_H  
  10.   
  11. #include <iostream>  
  12. #include <stdlib.h>  
  13. #include <pthread.h>  
  14. #include <sys/time.h>  
  15. using namespace std;  
  16.   
  17. template<class T>  
  18. class block_queue  
  19. {  
  20.     public:  
  21.         block_queue(int max_size = 1000)  
  22.         {  
  23.             if(max_size <= 0)  
  24.             {  
  25.                 exit(-1);  
  26.             }  
  27.               
  28.             m_max_size = max_size;  
  29.             m_array = new T[max_size];  
  30.             m_size = 0;  
  31.             m_front = -1;  
  32.             m_back = -1;  
  33.   
  34.             m_mutex = new pthread_mutex_t;  
  35.             m_cond = new pthread_cond_t;  
  36.             pthread_mutex_init(m_mutex, NULL);  
  37.             pthread_cond_init(m_cond, NULL);  
  38.         }  
  39.   
  40.         void clear()  
  41.         {  
  42.             pthread_mutex_lock(m_mutex);  
  43.             m_size = 0;  
  44.             m_front = -1;  
  45.             m_back = -1;  
  46.             pthread_mutex_unlock(m_mutex);  
  47.         }  
  48.   
  49.         ~block_queue()  
  50.         {  
  51.             pthread_mutex_lock(m_mutex);  
  52.             if(m_array != NULL)  
  53.                 delete  m_array;  
  54.             pthread_mutex_unlock(m_mutex);  
  55.   
  56.             pthread_mutex_destroy(m_mutex);  
  57.             pthread_cond_destroy(m_cond);  
  58.   
  59.             delete m_mutex;  
  60.             delete m_cond;  
  61.         }  
  62.   
  63.         bool full()const  
  64.         {  
  65.             pthread_mutex_lock(m_mutex);  
  66.             if(m_size >= m_max_size)  
  67.             {  
  68.                 pthread_mutex_unlock(m_mutex);  
  69.                 return true;  
  70.             }  
  71.             pthread_mutex_unlock(m_mutex);  
  72.             return false;  
  73.         }  
  74.   
  75.         bool empty()const  
  76.         {  
  77.             pthread_mutex_lock(m_mutex);  
  78.             if(0 == m_size)  
  79.             {  
  80.                 pthread_mutex_unlock(m_mutex);  
  81.                 return true;  
  82.             }  
  83.             pthread_mutex_unlock(m_mutex);  
  84.             return false;  
  85.         }  
  86.           
  87.         bool front(T& value)const  
  88.         {  
  89.             pthread_mutex_lock(m_mutex);  
  90.             if(0 == m_size)  
  91.             {  
  92.                 pthread_mutex_unlock(m_mutex);  
  93.                 return false;  
  94.             }  
  95.             value = m_array[m_front];  
  96.             pthread_mutex_unlock(m_mutex);  
  97.             return true;  
  98.         }  
  99.           
  100.         bool back(T& value)const  
  101.         {  
  102.             pthread_mutex_lock(m_mutex);  
  103.             if(0 == m_size)  
  104.             {  
  105.                 pthread_mutex_unlock(m_mutex);  
  106.                 return false;  
  107.             }  
  108.             value = m_array[m_back];  
  109.             pthread_mutex_unlock(m_mutex);  
  110.             return true;  
  111.         }  
  112.   
  113.         int size()const  
  114.         {  
  115.             int tmp = 0;  
  116.             pthread_mutex_lock(m_mutex);  
  117.             tmp = m_size;  
  118.             pthread_mutex_unlock(m_mutex);  
  119.             return tmp;  
  120.         }  
  121.   
  122.         int max_size()const  
  123.         {  
  124.             int tmp = 0;  
  125.             pthread_mutex_lock(m_mutex);  
  126.             tmp = m_max_size;  
  127.             pthread_mutex_unlock(m_mutex);  
  128.             return tmp;  
  129.         }  
  130.   
  131.         bool push(const T& item)  
  132.         {  
  133.             pthread_mutex_lock(m_mutex);  
  134.             if(m_size >= m_max_size)  
  135.             {  
  136.                 pthread_cond_broadcast(m_cond);  
  137.                 pthread_mutex_unlock(m_mutex);  
  138.                 return false;  
  139.             }  
  140.               
  141.             m_back = (m_back + 1) % m_max_size;  
  142.             m_array[m_back] = item;  
  143.   
  144.             m_size++;  
  145.             pthread_cond_broadcast(m_cond);  
  146.             pthread_mutex_unlock(m_mutex);  
  147.   
  148.             return true;  
  149.         }  
  150.   
  151.         bool pop(T& item)  
  152.         {  
  153.             pthread_mutex_lock(m_mutex);  
  154.             while(m_size <= 0)  
  155.             {  
  156.                 if(0 != pthread_cond_wait(m_cond, m_mutex))  
  157.                 {  
  158.                     pthread_mutex_unlock(m_mutex);  
  159.                     return false;  
  160.                 }  
  161.             }  
  162.   
  163.             m_front = (m_front + 1) % m_max_size;  
  164.             item = m_array[m_front];  
  165.             m_size--;  
  166.             pthread_mutex_unlock(m_mutex);  
  167.             return true;  
  168.         }  
  169.   
  170.         bool pop(T& item, int ms_timeout)  
  171.         {  
  172.             struct timespec t = {0,0};  
  173.             struct timeval now = {0,0};  
  174.             gettimeofday(&now, NULL);  
  175.             pthread_mutex_lock(m_mutex);  
  176.             if(m_size <= 0)  
  177.             {  
  178.                 t.tv_sec = now.tv_sec + ms_timeout/1000;  
  179.                 t.tv_nsec = (ms_timeout % 1000)*1000;  
  180.                 if(0 != pthread_cond_timedwait(m_cond, m_mutex, &t))  
  181.                 {  
  182.                     pthread_mutex_unlock(m_mutex);  
  183.                     return false;  
  184.                 }  
  185.             }  
  186.   
  187.             if(m_size <= 0)  
  188.             {  
  189.                 pthread_mutex_unlock(m_mutex);  
  190.                 return false;  
  191.             }  
  192.   
  193.             m_front = (m_front + 1) % m_max_size;  
  194.             item = m_array[m_front];m_size--;  
  195.             pthread_mutex_unlock(m_mutex);  
  196.             return true;  
  197.         }  
  198.   
  199. private:  
  200.         pthread_mutex_t *m_mutex;  
  201.         pthread_cond_t *m_cond;  
  202.         T *m_array;  
  203.         int m_size;  
  204.         int m_max_size;  
  205.         int m_front;  
  206.         int m_back;  
  207. };  
  208.   
  209. #endif  

  1. /******************************************************** 
  2. function:log class 
  3. version:1.0 
  4. date:2013.4.19 
  5. modify:2014.12.21 
  6. *********************************************************/  
  7.   
  8. #ifndef LOG_H  
  9. #define LOG_H  
  10.   
  11. #include <stdio.h>  
  12. #include <iostream>  
  13. #include <string>  
  14. #include <stdarg.h>  
  15. #include <pthread.h>  
  16. #include "block_queue.h"  
  17. using namespace std;  
  18.   
  19. class Log  
  20. {  
  21.     public:  
  22.         static Log* get_instance()  
  23.         {  
  24.             static Log instance;  
  25.             return &instance;  
  26.         }  
  27.           
  28.         static void *flush_log_thread(void* args)  
  29.         {  
  30.             Log::get_instance()->async_write_log();  
  31.         }  
  32.   
  33.         bool init(const char* file_name, int log_buf_size = 8192, int split_lines = 5000000, int max_queue_size = 0);  
  34.   
  35.         void write_log(int level, const char* format, ...);  
  36.   
  37.         void flush(void);  
  38.   
  39.     private:  
  40.         Log();  
  41.         virtual ~Log();  
  42.         void *async_write_log()  
  43.         {  
  44.             string single_log;  
  45.             while(m_log_queue->pop(single_log))  
  46.             {  
  47.                 pthread_mutex_lock(m_mutex);  
  48.                 fputs(single_log.c_str(), m_fp);  
  49.                 pthread_mutex_unlock(m_mutex);  
  50.             }  
  51.         }  
  52.   
  53.     private:  
  54.         pthread_mutex_t *m_mutex;  
  55.         char dir_name[128];  
  56.         char log_name[128];  
  57.         int m_split_lines;  
  58.         int m_log_buf_size;  
  59.         long long  m_count;  
  60.         int m_today;  
  61.         FILE *m_fp;  
  62.         char *m_buf;  
  63.         block_queue<string> *m_log_queue;  
  64.         bool m_is_async;  
  65. };  
  66.   
  67. #define LOG_DEBUG(format, ...) Log::get_instance()->write_log(0, format, __VA_ARGS__)  
  68. #define LOG_INFO(format, ...) Log::get_instance()->write_log(1, format, __VA_ARGS__)  
  69. #define LOG_WARN(format, ...) Log::get_instance()->write_log(2, format, __VA_ARGS__)  
  70. #define LOG_ERROR(format, ...) Log::get_instance()->write_log(3, format, __VA_ARGS__)  
  71.   
  72. #endif   

  1. /******************************************************** 
  2. function:log class 
  3. version:1.0 
  4. date:2013.4.19 
  5. modify:2014.12.21 
  6. *********************************************************/  
  7. #include <string.h>  
  8. #include <time.h>  
  9. #include <sys/time.h>  
  10. #include <stdarg.h>  
  11. #include "log.h"  
  12. #include <pthread.h>  
  13. using namespace std;  
  14.   
  15. Log::Log()  
  16. {  
  17.     m_count = 0;  
  18.     m_mutex = new pthread_mutex_t;  
  19.     m_is_async = false;  
  20.     pthread_mutex_init(m_mutex, NULL);  
  21. }  
  22.   
  23. Log::~Log()  
  24. {  
  25.     if(m_fp != NULL)  
  26.     {  
  27.         fclose(m_fp);  
  28.     }  
  29.     pthread_mutex_destroy(m_mutex);  
  30.   
  31.     if(m_mutex != NULL)  
  32.     {  
  33.         delete m_mutex;  
  34.     }  
  35. }  
  36.   
  37. bool Log::init(const char* file_name, int log_buf_size, int split_lines, int max_queue_size)  
  38. {  
  39.     if(max_queue_size >= 1)  
  40.     {  
  41.         m_is_async = true;  
  42.         m_log_queue = new block_queue<string>(max_queue_size);  
  43.         pthread_t tid;  
  44.         pthread_create(&tid, NULL, flush_log_thread, NULL);  
  45.     }  
  46.   
  47.     m_log_buf_size = log_buf_size;  
  48.     m_buf = new char[m_log_buf_size];  
  49.     memset(m_buf, '\0'sizeof(m_buf));  
  50.     m_split_lines = split_lines;  
  51.   
  52.     time_t t = time(NULL);  
  53.     struct tm* sys_tm = localtime(&t);  
  54.     struct tm my_tm = *sys_tm;  
  55.     const char *p = strrchr(file_name, '/');  
  56.     char log_full_name[256] = {0};  
  57.     if(p == NULL)  
  58.     {  
  59.         snprintf(log_full_name, 255, "%d_%02d_%02d_%s",my_tm.tm_year+1900, my_tm.tm_mon+1, my_tm.tm_mday, file_name);     
  60.     }  
  61.     else  
  62.     {  
  63.         strcpy(log_name, p+1);  
  64.         strncpy(dir_name, file_name, p - file_name + 1);  
  65.         snprintf(log_full_name, 255, "%s%d_%02d_%02d_%s",dir_name, my_tm.tm_year+1900, my_tm.tm_mon+1, my_tm.tm_mday, log_name );   
  66.     }  
  67.   
  68.     m_today = my_tm.tm_mday;  
  69.   
  70.     m_fp = fopen(log_full_name, "a");  
  71.     if(m_fp == NULL)  
  72.     {  
  73.         return false;  
  74.     }  
  75.   
  76.     return true;  
  77. }  
  78.   
  79. void Log::write_log(int level, const char* format, ...)  
  80. {  
  81.     struct timeval now = {0,0};  
  82.     gettimeofday(&now, NULL);  
  83.     time_t t = now.tv_sec;  
  84.     struct tm* sys_tm = localtime(&t);  
  85.     struct tm my_tm = *sys_tm;  
  86.     char s[16] = {0};  
  87.     switch(level)  
  88.     {  
  89.         case 0 : strcpy(s, "[debug]:"); break;  
  90.         case 1 : strcpy(s, "[info]:"); break;  
  91.         case 2 : strcpy(s, "[warn]:"); break;  
  92.         case 3 : strcpy(s, "[erro]:"); break;  
  93.         default:  
  94.                strcpy(s, "[info]:"); break;  
  95.     }  
  96.   
  97.     pthread_mutex_lock(m_mutex);  
  98.     m_count++;  
  99.     if(m_today != my_tm.tm_mday || m_count % m_split_lines == 0) //everyday log  
  100.     {  
  101.         char new_log[256] = {0};  
  102.         fflush(m_fp);  
  103.         fclose(m_fp);  
  104.         char tail[16] = {0};  
  105.         snprintf(tail, 16,  "%d_%02d_%02d_", my_tm.tm_year+1900, my_tm.tm_mon+1, my_tm.tm_mday);  
  106.         if(m_today != my_tm.tm_mday)  
  107.         {  
  108.             snprintf(new_log, 255, "%s%s%s", dir_name, tail, log_name);  
  109.             m_today = my_tm.tm_mday;  
  110.             m_count = 0;  
  111.         }  
  112.         else  
  113.         {  
  114.             snprintf(new_log, 255, "%s%s%s.%d", dir_name, tail, log_name, m_count/m_split_lines);  
  115.         }  
  116.         m_fp = fopen(new_log, "a");  
  117.     }  
  118.     pthread_mutex_unlock(m_mutex);  
  119.       
  120.     va_list valst;  
  121.     va_start(valst, format);  
  122.       
  123.     string log_str;  
  124.     pthread_mutex_lock(m_mutex);  
  125.     int n = snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06d %s ",  
  126.             my_tm.tm_year+1900, my_tm.tm_mon+1, my_tm.tm_mday,  
  127.             my_tm.tm_hour, my_tm.tm_min, my_tm.tm_sec, now.tv_usec, s);  
  128.     int m = vsnprintf(m_buf + n, m_log_buf_size-1, format, valst);  
  129.     m_buf[n + m - 1] = '\n';  
  130.     log_str = m_buf;  
  131.     pthread_mutex_unlock(m_mutex);  
  132.   
  133.     if(m_is_async && !m_log_queue->full())  
  134.     {  
  135.         m_log_queue->push(log_str);  
  136.     }  
  137.     else  
  138.     {  
  139.         pthread_mutex_lock(m_mutex);  
  140.         fputs(log_str.c_str(), m_fp);  
  141.         pthread_mutex_unlock(m_mutex);  
  142.     }  
  143.   
  144.     va_end(valst);  
  145. }  
  146.   
  147. void Log::flush(void)  
  148. {  
  149.     pthread_mutex_lock(m_mutex);  
  150.     fflush(m_fp);  
  151.     pthread_mutex_unlock(m_mutex);  
  152. }  

  1. #include "log.h"  
  2. void *f(void* args)  
  3. {  
  4.     for(int i = 0;i < 100; i++)  
  5.     {  
  6.             Log::get_instance()->write_log(1, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  7.             Log::get_instance()->write_log(2, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  8.             Log::get_instance()->write_log(3, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  9.   
  10.             LOG_INFO("%d", 123456789);  
  11.             LOG_ERROR("%d", 123456789);  
  12.             LOG_DEBUG("%d", 123456789);  
  13.             LOG_WARN("%d", 123456789);  
  14.   
  15.     }  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.     Log::get_instance()->init("./mylog.log", 100, 2000000, 10);  
  21.     //Log::get_instance()->init("./mylog.log", 100, 2000000, 0);//synchronization model  
  22.     sleep(1);  
  23.     int i = 0;  
  24.     Log::get_instance()->write_log(1, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  25.     Log::get_instance()->write_log(2, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  26.     Log::get_instance()->write_log(3, "d=%d,c=%c,s=%s,f=%f", i,'a',"log", 1.000);  
  27.   
  28.     LOG_INFO("%d", 123456789);  
  29.     LOG_ERROR("%d", 123456789);  
  30.     LOG_DEBUG("%d", 123456789);  
  31.     LOG_WARN("%d", 123456789);  
  32.   
  33.     pthread_t id;  
  34.     for(int i = 0; i < 1; i++)  
  35.     {  
  36.         pthread_create(&id, NULL, f, NULL);  
  37.         pthread_join(id,NULL);  
  38.     }  
  39.   
  40.     //for(;;)  
  41.     {  
  42.         sleep(15);  
  43.         Log::get_instance()->flush();  
  44.     }  
  45.   
  46.     return 0;  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值