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

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

#1 fix and arrange doxygen comments

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