source: libcf/trunk/src/cf_log.c@ 99

Last change on this file since 99 was 99, checked in by cheese, 11 years ago

#1 fix doxygen for r98

File size: 13.9 KB
Line 
1/**
2 * @file cf_log.c
3 * @author myusgun <myusgun@gmail.com>
4 */
5#if defined(_WIN32) || defined(_WIN64)
6# define _USE_32BIT_TIME_T
7# if (_MSC_VER >= 1400)
8# define localtime _localtime32
9# endif
10#endif
11
12#include "cf_log.h"
13#include "cf_file.h"
14#include "cf_thread.h"
15#include "cf_local.h"
16#include "cf_error.h"
17
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21#include <stdarg.h>
22#include <time.h>
23
24#if defined(_WIN32) || defined(_WIN64)
25# include <Windows.h>
26#else
27# include <sys/time.h>
28#endif
29
30#define ASSERT_CTX(__ctx) \
31 if (__ctx == NULL) \
32 return CF_ERROR_LOG_INVALID_CTX
33
34#define ASSERT_INIT() \
35 if (gLogArray.ctxPool == NULL || \
36 gLogArray.ctxSize <= 0 ) \
37 return CF_ERROR_LOG_NOT_INITIALIZE
38
39#define ASSERT_MAPID(__mapid) \
40 if (gLogArray.ctxSize <= __mapid) \
41 return CF_ERROR_LOG_INVALID_MAPID
42
43#define ASSERT_MAPPED_CTX(__mapid) \
44 if (gLogArray.ctxPool[__mapid] != NULL) \
45 return CF_ERROR_LOG_ALREADY_MAPPED_ID
46
47#define ASSERT_NOT_MAPPED_CTX(__mapid) \
48 if (gLogArray.ctxPool[__mapid] == NULL) \
49 return CF_ERROR_LOG_NOT_MAPPED_ID
50
51#define LOCK_LOG_CTX(__ctx) CF_Mutex_Lock (&__ctx->mutex)
52#define UNLOCK_LOG_CTX(__ctx) CF_Mutex_Unlock (&__ctx->mutex)
53
54#define LOG_BUFFER_DEFAULT_SIZE 128 * 1024
55
56#define LOG_DATETIME_LENGTH sizeof ("0000-00-00 00:00:00.000") - 1
57
58/**
59 * 로그 컨텍스트
60 *
61 * @remark change from public to private
62 */
63typedef void * CF_Log_Ctx;
64
65typedef struct __cf_util_datetime__
66{
67 int year;
68 int month;
69 int day;
70 int week; /* SUN:0 ~ SAT:6 */
71
72 int hour;
73 int min;
74 int sec;
75 int usec;
76} S_CF_LOG_DATETIME, CF_LOG_DATETIME;
77
78typedef struct __cf_log_ctx__ {
79 char path[NAME_LENGTH + 1];
80 int fd;
81 char * buffer;
82 size_t size; /* entire size of buffer */
83 size_t length; /* data length in current */
84 CF_Mutex mutex;
85} S_CF_LOG_CTX, CF_LOG_CTX;
86
87typedef struct __cf_log_array__ {
88 CF_Log_Ctx * ctxPool;
89 int ctxSize;
90 int level;
91} S_CF_LOG_ARRAY, CF_LOG_ARRAY;
92
93static CF_LOG_ARRAY gLogArray;
94
95#if defined(_WIN32) || defined(_WIN64)
96/* {{{ */
97struct timezone
98{
99 int tz_minuteswest; /* minutes W of Greenwich */
100 int tz_dsttime; /* type of dst correction */
101};
102
103int gettimeofday (struct timeval *tv, struct timezone *tz)
104{
105 FILETIME ft;
106 unsigned __int64 buf =0;
107 //static int tzflag = 0;
108
109 if (NULL != tv)
110 {
111 GetSystemTimeAsFileTime (&ft);
112
113 buf |= ft.dwHighDateTime;
114 buf <<= 32;
115 buf |= ft.dwLowDateTime;
116
117 if (buf)
118 {
119 buf /= 10;
120 buf -= ((369 * 365 + 89) * (unsigned __int64) 86400) * 1000000;
121 }
122
123 tv->tv_sec = (long)(buf / 1000000UL);
124 tv->tv_usec = (long)(buf % 1000000UL);
125 }
126
127 /*
128 if (NULL != tz)
129 {
130 if (!tzflag)
131 {
132 _tzset();
133 tzflag++;
134 }
135
136 // Adjust for the timezone west of Greenwich
137 tz->tz_minuteswest = _timezone / 60;
138 tz->tz_dsttime = _daylight;
139 }
140 */
141
142 return 0;
143}
144/* }}} */
145#endif
146
147static int
148CF_Log_Local_GetTime (CF_LOG_DATETIME * dt)
149{
150 struct timeval timeVal;
151 struct tm * timeSt;
152
153 gettimeofday (&timeVal, NULL);
154 timeSt = localtime ((const time_t *)&timeVal.tv_sec);
155
156 dt->year = timeSt->tm_year + 1900;
157 dt->month = timeSt->tm_mon + 1;
158 dt->day = timeSt->tm_mday;
159 dt->week = timeSt->tm_wday;
160
161 dt->hour = timeSt->tm_hour;
162 dt->min = timeSt->tm_min;
163 dt->sec = timeSt->tm_sec;
164
165 dt->usec = (int) timeVal.tv_usec;
166
167 return CF_OK;
168}
169
170static int
171CF_Log_Local_GetTimeString (char * buffer)
172{
173 CF_LOG_DATETIME dt;
174 CF_Log_Local_GetTime (&dt);
175
176 snprintf (buffer, LOG_DATETIME_LENGTH,
177 "%02d-%02d-%02d %02d:%02d:%02d.%03d",
178 dt.year, dt.month, dt.day,
179 dt.hour, dt.min, dt.sec, dt.usec);
180
181 return CF_OK;
182}
183
184static int
185CF_Log_Local_Flush (CF_LOG_CTX * ctx)
186{
187 if (CF_File_Write (ctx->fd, ctx->buffer, ctx->length) < 0)
188 return CF_ERROR_LOG_FLUSH;
189
190 ctx->length = 0;
191
192 return CF_OK;
193}
194
195/**
196 * 로그 데이터 처리
197 *
198 * @return 성공 시, CF_OK; 실패 시, 오류 코드
199 *
200 * @param ctx 로그 컨텍스트
201 * @param buffer 로그 데이터
202 * @param demandSize 로그 데이터 길이
203 *
204 * @author vfire
205 */
206/* static */int
207CF_Log_Local_Push (CF_LOG_CTX * ctx,
208 const char * buffer,
209 const size_t demandSize)
210{
211 int result = CF_OK;
212
213 if (ctx->size > 0) /* 버퍼단위 버퍼링.... */
214 {
215 size_t writeSize;
216 size_t remainSize;
217
218 remainSize = demandSize;
219 while (remainSize)
220 {
221 writeSize = (ctx->size - ctx->length) < remainSize ? (ctx->size - ctx->length) : remainSize;
222
223 memcpy (ctx->buffer + ctx->length, buffer + demandSize - remainSize, writeSize);
224 ctx->length += writeSize;
225
226 if (ctx->length == ctx->size)
227 CF_Log_Local_Flush (ctx);
228
229 remainSize -= writeSize;
230 }
231 }
232 else /* flush되어야 함. */
233 {
234 ctx->buffer = (char *)buffer;
235 ctx->length = demandSize;
236
237 result = CF_Log_Local_Flush (ctx);
238 }
239
240 return result;
241}
242
243/**
244 * 로그 컨텍스트에 멀티쓰레드 모드 설정
245 *
246 * @return 성공 시, CF_OK; 실패 시, 오류 코드
247 *
248 * @param ctx 로그 컨텍스트
249 *
250 * @see CF_Log_UnsetMultiThread
251 */
252static int
253CF_Log_SetMultiThread (CF_Log_Ctx ctx)
254{
255 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
256
257 ASSERT_CTX (ctx);
258
259 if (CF_Mutex_Create (&context->mutex) < 0)
260 return CF_ERROR_LOG_SET_MULTITHREAD;
261
262 return CF_OK;
263}
264
265/**
266 * 로그 컨텍스트에 멀티쓰레드 모드 설정 해제
267 *
268 * @return 성공 시, CF_OK; 실패 시, 오류 코드
269 *
270 * @param ctx 로그 컨텍스트
271 *
272 * @see CF_Log_SetMultiThread
273 */
274static int
275CF_Log_UnsetMultiThread (CF_Log_Ctx ctx)
276{
277 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
278
279 ASSERT_CTX (ctx);
280
281 if (CF_Mutex_Destory (&context->mutex) < 0)
282 return CF_ERROR_LOG_UNSET_MULTITHREAD;
283
284 return CF_OK;
285}
286
287/**
288 * 로그 컨텍스트에 따라 로그 쓰기
289 *
290 * @return 성공 시, CF_OK; 실패 시, 오류 코드
291 *
292 * @param ctx 로그 컨텍스트
293 * @param prefix 로그의 프리픽스 문자열
294 * @param fmt 포맷 스트링
295 * @param ... 가변 인자
296 */
297static int
298CF_Log_WriteCtx (CF_Log_Ctx ctx,
299 const char * prefix,
300 const char * fmt,
301// ...)
302 va_list valist)
303{
304 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
305// va_list valist;
306 char buffer[16 * 1024] = {0x00,};
307 char datetime[LOG_DATETIME_LENGTH + 1] = {0x00,};
308
309 ASSERT_CTX (ctx);
310
311 LOCK_LOG_CTX (context);
312// va_start (valist, fmt);
313
314 CF_Log_Local_GetTimeString (datetime);
315 snprintf (buffer, sizeof (buffer) - 1, "[%s][%s] ", datetime, prefix);
316 vsprintf (buffer + strlen (buffer), fmt, valist);
317
318 CF_Log_Local_Push (context, buffer, strlen (buffer));
319
320// va_end (valist);
321 UNLOCK_LOG_CTX (context);
322
323 return CF_OK;
324}
325
326/**
327 * 로그 버퍼의 데이터를 즉시 로그 파일에 쓰기
328 *
329 * @return 성공 시, CF_OK; 실패 시, 오류 코드
330 *
331 * @param ctx 로그 컨텍스트
332 */
333static int
334CF_Log_FlushCtx (CF_Log_Ctx ctx)
335{
336 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
337
338 ASSERT_CTX (ctx);
339
340 LOCK_LOG_CTX (context);
341 CF_Log_Local_Flush (context);
342 UNLOCK_LOG_CTX (context);
343
344 return CF_OK;
345}
346
347/**
348 * 로그 컨텍스트 해제
349 *
350 * @return 성공 시, CF_OK; 실패 시, 오류 코드
351 *
352 * @param ctx 로그 컨텍스트
353 */
354static int
355CF_Log_DestroyCtx (CF_Log_Ctx ctx)
356{
357 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
358
359 ASSERT_CTX (ctx);
360
361 if (context->size > 0)
362 {
363 CF_Log_FlushCtx (ctx);
364 free (context->buffer);
365 context->buffer = NULL;
366 context->size = 0;
367 }
368
369 CF_File_Close (context->fd);
370
371 CF_Mutex_Destory (&context->mutex);
372 context->mutex = NULL;
373
374 return CF_OK;
375}
376
377/**
378 * 로그 컨텍스트 생성
379 *
380 * @return 성공 시, 로그 컨텍스트; 실패 시, NULL
381 *
382 * @param path 로그 파일 경로
383 * @param memsize 로그 버퍼 크기
384 * @param ctx 로그 컨텍스트 받을 주소
385 *
386 * @see CF_LOG_BUFFER_DEFAULT, CF_LOG_BUFFER_NO
387 */
388static int
389CF_Log_CreateCtx (const char * path,
390 const int memsize,
391 CF_Log_Ctx * ctx)
392{
393 int result = 0;
394 int fileFlag = CF_FILE_CREATE|CF_FILE_WRITE|CF_FILE_APPEND;
395 int size = (memsize == CF_LOG_BUFFER_DEFAULT)
396 ? LOG_BUFFER_DEFAULT_SIZE
397 : memsize;
398
399 CF_LOG_CTX * context = NULL;
400
401 if (path == NULL)
402 return CF_ERROR_LOG_INVALID_ARGS;
403
404 TRY
405 {
406 context = (CF_LOG_CTX *) calloc (sizeof (CF_LOG_CTX), 1);
407 if (context == NULL)
408 {
409 result = CF_ERROR_LOG_ALLOCATE_CTX;
410 TRY_BREAK;
411 }
412
413 context->fd = CF_File_Open (path, fileFlag);
414 if (context->fd < 0)
415 {
416 result = CF_ERROR_LOG_CREATE_FILE;
417 TRY_BREAK;
418 }
419 snprintf (context->path, sizeof (context->path) -1, "%s", path);
420
421 if (size > 0)
422 {
423 context->buffer = (char *) calloc ((size_t) size + 1, 1);
424 if (context->buffer == NULL)
425 {
426 result = CF_ERROR_LOG_ALLOCATE_BUFFER;
427 TRY_BREAK;
428 }
429 context->size = (size_t) size;
430 }
431
432 *ctx = (CF_Log_Ctx) context;
433 }
434 CATCH_IF (result < 0)
435 {
436 CF_Log_DestroyCtx ((CF_Log_Ctx) context);
437 }
438
439 return result;
440}
441
442/**
443 * 로그 컨텍스트에 아이디 넘버 할당<br />
444 * 로그 기록 시, 아이디 넘버를 사용하면 해당 로그로 기록할 수 있음
445 *
446 * @return 성공 시, CF_OK; 실패 시, 오류 코드
447 *
448 * @param mapid 부여할 아이디 넘버
449 * @param ctx 로그 컨텍스트
450 *
451 * @remark 반드시 먼저 초기화 해야하며, 초기화 시에 주어진 번호보다 작은 아이디 넘버를 사용
452 *
453 * @see CF_LOG_OPEN, CF_Log_CreateCtx
454 */
455static int
456CF_Log_MapCtxID (const int mapid,
457 const CF_Log_Ctx ctx)
458{
459 ASSERT_INIT ();
460 ASSERT_MAPID (mapid);
461 ASSERT_MAPPED_CTX (mapid);
462
463 gLogArray.ctxPool[mapid] = ctx;
464
465 return CF_OK;
466}
467
468/**
469 * 아이디 넘버에 해당하는 로그를 닫고 해당하는 컨텍스트를 해제
470 *
471 * @return 성공 시, CF_OK; 실패 시, 오류 코드
472 *
473 * @param mapid 로그의 아이디 넘버
474 *
475 * @remark 아이디 넘버에 해당하는 컨텍스트가 해제되므로 주의
476 *
477 * @see CF_LOG_CLOSE, CF_Log_DestroyCtx
478 */
479static int
480CF_Log_UnmapCtxID (const int mapid)
481{
482 ASSERT_INIT ();
483 ASSERT_MAPID (mapid);
484 ASSERT_NOT_MAPPED_CTX (mapid);
485
486 CF_Log_DestroyCtx (gLogArray.ctxPool[mapid]);
487
488 free (gLogArray.ctxPool[mapid]);
489 gLogArray.ctxPool[mapid] = NULL;
490
491 return CF_OK;
492}
493
494/**
495 * 아이디 넘버에 해당하는 로그 컨텍스트를 얻기
496 *
497 * @return 성공 시, CF_OK; 실패 시, 오류 코드
498 *
499 * @param mapid 로그의 아이디 넘버
500 * @param ctx 로그 컨텍스트 받을 주소
501 */
502static int
503CF_Log_GetMappedCtx (const int mapid,
504 CF_Log_Ctx * ctx)
505{
506 ASSERT_INIT ();
507 ASSERT_MAPID (mapid);
508 ASSERT_NOT_MAPPED_CTX (mapid);
509
510 *ctx = gLogArray.ctxPool[mapid];
511
512 return CF_OK;
513}
514
515/**
516 * 로그를 사용하기 위해 초기화
517 *
518 * @return 성공 시, CF_OK; 실패 시, 오류 코드
519 *
520 * @param logPool 아이디 넘버 최대 값
521 */
522int
523CF_Log_Initialize (const int logPool)
524{
525 memset (&gLogArray, 0x00, sizeof (CF_LOG_ARRAY));
526
527 if (logPool > 0)
528 {
529 gLogArray.ctxPool =
530 (CF_Log_Ctx *) calloc ((size_t) logPool, sizeof (CF_Log_Ctx));
531 if (gLogArray.ctxPool == NULL)
532 return CF_ERROR_LOG_INITIALIZE;
533 gLogArray.ctxSize = logPool;
534 gLogArray.level = CF_LOG_NO_LEVEL;
535 }
536
537 return CF_OK;
538}
539
540/**
541 * 로그가 모두 사용된 후 자원 해제
542 *
543 * @return CF_OK 반환
544 */
545int
546CF_Log_Finalize (void)
547{
548 int mapid = 0;
549
550 for (mapid = 0 ; mapid < gLogArray.ctxSize ; mapid++)
551 {
552 CF_Log_UnmapCtxID (mapid);
553 }
554
555 if (gLogArray.ctxPool != NULL)
556 free (gLogArray.ctxPool);
557
558 memset (&gLogArray, 0x00, sizeof (CF_LOG_ARRAY));
559
560 return CF_OK;
561}
562
563/**
564 * 로그 열기
565 *
566 * @return 성공 시, CF_OK; 실패 시, 오류 코드
567 *
568 * @param mapid 로그의 아이디 넘버
569 * @param path 로그 파일 경로
570 * @param memsize 로그 버퍼 크기
571 *
572 * @see CF_LOG_BUFFER_DEFAULT, CF_LOG_BUFFER_NO
573 */
574int
575CF_Log_Open (const int mapid,
576 const char * path,
577 const int memsize)
578{
579 int result = 0;
580 CF_Log_Ctx ctx = NULL;
581
582 result = CF_Log_CreateCtx (path, memsize, &ctx);
583 if (result < 0)
584 return result;
585
586 result = CF_Log_MapCtxID (mapid, ctx);
587 if (result < 0)
588 CF_Log_DestroyCtx (ctx);
589
590 return result;
591}
592
593/**
594 * 로그 닫기
595 *
596 * @return 성공 시, CF_OK; 실패 시, 오류 코드
597 *
598 * @param mapid 로그의 아이디 넘버
599 */
600int
601CF_Log_Close (const int mapid)
602{
603 return CF_Log_UnmapCtxID (mapid);
604}
605
606/**
607 * 로그 버퍼의 데이터를 즉시 로그 파일에 쓰기
608 *
609 * @return 성공 시, CF_OK; 실패 시, 오류 코드
610 *
611 * @param mapid 로그의 아이디 넘버
612 */
613int
614CF_Log_Flush (const int mapid)
615{
616 int result = 0;
617 CF_Log_Ctx ctx = NULL;
618
619 result = CF_Log_GetMappedCtx (mapid, &ctx);
620 if (result < 0)
621 return result;
622
623 result = CF_Log_FlushCtx (ctx);
624
625 return result;
626}
627
628/**
629 * 로그 컨텍스트에 멀티쓰레드 모드 설정
630 *
631 * @return 성공 시, CF_OK; 실패 시, 오류 코드
632 *
633 * @param mapid 로그의 아이디 넘버
634 * @param flag 설정/해제 bool 플래그
635 *
636 * @see CF_BOOL
637 */
638int
639CF_Log_SetMT (const int mapid,
640 const CF_BOOL flag)
641{
642 int result = 0;
643 CF_Log_Ctx ctx = NULL;
644
645 result = CF_Log_GetMappedCtx (mapid, &ctx);
646 if (result < 0)
647 return result;
648
649 result = (flag) ? CF_Log_SetMultiThread (ctx) :
650 CF_Log_UnsetMultiThread (ctx);
651
652 return result;
653}
654
655/**
656 * 현재 설정된 로그 레벨을 가져옴
657 *
658 * @return 로그 레벨이 설정된 경우, 로그 풀 크기; 그 외에, 설정된 로그 레벨
659 */
660static int
661CF_Log_GetLevel (void)
662{
663 return (gLogArray.level == CF_LOG_NO_LEVEL) ? gLogArray.ctxSize
664 : gLogArray.level;
665}
666
667/**
668 * 로그 레벨을 설정
669 * 지정된 로그 레벨 이하의 아이디 넘버만 로그로 기록하도록 설정
670 *
671 * @return 성공 시, CF_OK; 실패 시, 오류 코드
672 *
673 * @param level 설정할 로그 레벨
674 *
675 * @see CF_LOG_NO_LEVEL
676 */
677int
678CF_Log_SetLevel (const int level)
679{
680 gLogArray.level = level;
681
682 return CF_OK;
683}
684
685/**
686 * 로그 쓰기
687 *
688 * @return 성공 시, CF_OK; 실패 시, 오류 코드
689 *
690 * @param mapid 로그의 아이디 넘버
691 * @param prefix 로그의 프리픽스 문자열
692 * @param fmt 포맷 스트링
693 * @param ... 가변 인자
694 */
695int
696CF_Log_Write (const int mapid,
697 const char * prefix,
698 const char * fmt, ...)
699{
700 int result = 0;
701 CF_Log_Ctx ctx = NULL;
702 va_list valist;
703
704 result = CF_Log_GetLevel ();
705 if (result < mapid)
706 return CF_OK;
707
708 result = CF_Log_GetMappedCtx (mapid, &ctx);
709 if (result < 0)
710 return result;
711
712 va_start (valist, fmt);
713 result = CF_Log_WriteCtx (ctx, prefix, fmt, valist);
714 va_end (valist);
715
716 return result;
717}
Note: See TracBrowser for help on using the repository browser.