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

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

#1 add author (vfire) for log

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