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

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

#1 refactoring log writing functions

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