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

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

#1 add bitwise util from ARIA of chevalier

File size: 13.2 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 (gLogArray.ctxPool == NULL || \
40 gLogArray.ctxSize <= 0 ) \
41 return CF_ERROR_LOG_NOT_INITIALIZE
42
43#define ASSERT_MAPID(__mapid) \
44 if (gLogArray.ctxSize <= __mapid) \
45 return CF_ERROR_LOG_INVALID_MAPID
46
47#define ASSERT_MAPPED_CTX(__mapid) \
48 if (gLogArray.ctxPool[__mapid] != NULL) \
49 return CF_ERROR_LOG_ALREADY_MAPPED_ID
50
51#define ASSERT_NOT_MAPPED_CTX(__mapid) \
52 if (gLogArray.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 ctxSize;
90} CF_LOG_ARRAY;
91
92static CF_LOG_ARRAY gLogArray;
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 ... 가변 인자
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#define BUF_LEN 16 * 1024
306 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
307// va_list valist;
308 char buffer[BUF_LEN + 1] = {0x00,};
309 char datetime[LOG_DATETIME_LENGTH + 1] = {0x00,};
310 int length = 0;
311
312 ASSERT_CTX (ctx);
313
314 CF_Mutex_Lock (context->mutex);
315// va_start (valist, fmt);
316
317 CF_Log_Local_GetTimeString (datetime);
318 length = snprintf (buffer, BUF_LEN, "[%s][%s] ", datetime, prefix);
319 vsnprintf (&buffer[length], BUF_LEN - (size_t)length, fmt, valist);
320
321 CF_Log_Local_Push (context, buffer, strlen (buffer));
322
323// va_end (valist);
324 CF_Mutex_Unlock (context->mutex);
325
326 return CF_OK;
327}
328
329/**
330 * 로그 버퍼의 데이터를 즉시 로그 파일에 쓰기
331 *
332 * \return 성공 시, CF_OK; 실패 시, 오류 코드
333 *
334 * \param ctx 로그 컨텍스트
335 */
336static int
337CF_Log_FlushCtx (CF_Log_Ctx ctx)
338{
339 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
340
341 ASSERT_CTX (ctx);
342
343 CF_Mutex_Lock (context->mutex);
344 CF_Log_Local_Flush (context);
345 CF_Mutex_Unlock (context->mutex);
346
347 return CF_OK;
348}
349
350/**
351 * 로그 컨텍스트 해제
352 *
353 * \return 성공 시, CF_OK; 실패 시, 오류 코드
354 *
355 * \param ctx 로그 컨텍스트
356 */
357static int
358CF_Log_DestroyCtx (CF_Log_Ctx ctx)
359{
360 CF_LOG_CTX * context = (CF_LOG_CTX *) ctx;
361
362 ASSERT_CTX (ctx);
363
364 if (context->size > 0)
365 {
366 CF_Log_FlushCtx (ctx);
367 free (context->buffer);
368 context->buffer = NULL;
369 context->size = 0;
370 }
371
372 CF_File_Close (context->fd);
373
374 CF_Mutex_DestoryCtx (context->mutex);
375 context->mutex = NULL;
376
377 return CF_OK;
378}
379
380/**
381 * 로그 컨텍스트 생성
382 *
383 * \return 성공 시, 로그 컨텍스트; 실패 시, NULL
384 *
385 * \param ctx 로그 컨텍스트 주소
386 * \param path 로그 파일 경로
387 * \param memsize 로그 버퍼 크기
388 *
389 * \see CF_LOG_DEFAULT_BUFFER, CF_LOG_NO_BUFFER
390 */
391static int
392CF_Log_CreateCtx (CF_Log_Ctx * ctx,
393 const char * path,
394 const int memsize)
395{
396 int result = 0;
397 int fileFlag = CF_FILE_CREATE|CF_FILE_WRITE|CF_FILE_APPEND;
398 int size = (memsize == CF_LOG_DEFAULT_BUFFER)
399 ? LOG_BUFFER_DEFAULT_SIZE
400 : memsize;
401
402 CF_LOG_CTX * context = NULL;
403
404 if (path == NULL)
405 return CF_ERROR_LOG_INVALID_ARGS;
406
407 TRY
408 {
409 context = (CF_LOG_CTX *) calloc (sizeof (CF_LOG_CTX), 1);
410 if (context == NULL)
411 {
412 result = CF_ERROR_LOG_CREATE_CTX;
413 TRY_BREAK;
414 }
415
416 context->fd = CF_File_Open (path, fileFlag);
417 if (context->fd < 0)
418 {
419 result = CF_ERROR_LOG_CREATE_FILE;
420 TRY_BREAK;
421 }
422 snprintf (context->path, sizeof (context->path) -1, "%s", path);
423
424 if (size > 0)
425 {
426 context->buffer = (char *) calloc ((size_t) size + 1, 1);
427 if (context->buffer == NULL)
428 {
429 result = CF_ERROR_LOG_ALLOCATE_BUFFER;
430 TRY_BREAK;
431 }
432 context->size = (size_t) size;
433 }
434
435 *ctx = (CF_Log_Ctx) context;
436 }
437 CATCH_IF (result < 0)
438 {
439 CF_Log_DestroyCtx ((CF_Log_Ctx) context);
440 }
441
442 return result;
443}
444
445/**
446 * 로그 컨텍스트에 아이디 넘버 할당<br />
447 * 로그 기록 시, 아이디 넘버를 사용하면 해당 로그로 기록할 수 있음
448 *
449 * \return 성공 시, CF_OK; 실패 시, 오류 코드
450 *
451 * \param mapid 부여할 아이디 넘버
452 * \param ctx 로그 컨텍스트
453 *
454 * \remarks 반드시 먼저 초기화 해야하며, 초기화 시에 주어진 번호보다 작은 아이디 넘버를 사용
455 *
456 * \see CF_LOG_OPEN, CF_Log_CreateCtx
457 */
458static int
459CF_Log_MapCtxID (const int mapid,
460 const CF_Log_Ctx ctx)
461{
462 ASSERT_INIT ();
463 ASSERT_MAPID (mapid);
464 ASSERT_MAPPED_CTX (mapid);
465
466 gLogArray.ctxPool[mapid] = ctx;
467
468 return CF_OK;
469}
470
471/**
472 * 아이디 넘버에 해당하는 로그를 닫고 해당하는 컨텍스트를 해제
473 *
474 * \return 성공 시, CF_OK; 실패 시, 오류 코드
475 *
476 * \param mapid 로그의 아이디 넘버
477 *
478 * \remarks 아이디 넘버에 해당하는 컨텍스트가 해제되므로 주의
479 *
480 * \see CF_LOG_CLOSE, CF_Log_DestroyCtx
481 */
482static int
483CF_Log_UnmapCtxID (const int mapid)
484{
485 ASSERT_INIT ();
486 ASSERT_MAPID (mapid);
487 ASSERT_NOT_MAPPED_CTX (mapid);
488
489 CF_Log_DestroyCtx (gLogArray.ctxPool[mapid]);
490
491 free (gLogArray.ctxPool[mapid]);
492 gLogArray.ctxPool[mapid] = NULL;
493
494 return CF_OK;
495}
496
497/**
498 * 아이디 넘버에 해당하는 로그 컨텍스트를 얻기
499 *
500 * \return 성공 시, CF_OK; 실패 시, 오류 코드
501 *
502 * \param mapid 로그의 아이디 넘버
503 * \param ctx 로그 컨텍스트 받을 주소
504 */
505static int
506CF_Log_GetMappedCtx (const int mapid,
507 CF_Log_Ctx * ctx)
508{
509 ASSERT_INIT ();
510 ASSERT_MAPID (mapid);
511 ASSERT_NOT_MAPPED_CTX (mapid);
512
513 *ctx = gLogArray.ctxPool[mapid];
514
515 return CF_OK;
516}
517
518/**
519 * 로그를 사용하기 위해 초기화
520 *
521 * \return 성공 시, CF_OK; 실패 시, 오류 코드
522 *
523 * \param poolSize 로그 풀 크기로, 로그 아이디 넘버의 최대 값
524 */
525int
526CF_Log_Initialize (const int poolSize)
527{
528 memset (&gLogArray, 0x00, sizeof (CF_LOG_ARRAY));
529
530 if (poolSize > 0)
531 {
532 gLogArray.ctxPool =
533 (CF_Log_Ctx *) calloc ((size_t) poolSize, sizeof (CF_Log_Ctx));
534 if (gLogArray.ctxPool == NULL)
535 return CF_ERROR_LOG_INITIALIZE;
536 gLogArray.ctxSize = poolSize;
537 }
538
539 return CF_OK;
540}
541
542/**
543 * 로그가 모두 사용된 후 자원 해제
544 *
545 * \return CF_OK 반환
546 */
547int
548CF_Log_Finalize (void)
549{
550 int mapid = 0;
551
552 for (mapid = 0 ; mapid < gLogArray.ctxSize ; mapid++)
553 {
554 CF_Log_UnmapCtxID (mapid);
555 }
556
557 if (gLogArray.ctxPool != NULL)
558 free (gLogArray.ctxPool);
559
560 memset (&gLogArray, 0x00, sizeof (CF_LOG_ARRAY));
561
562 return CF_OK;
563}
564
565/**
566 * 로그 열기
567 *
568 * \return 성공 시, CF_OK; 실패 시, 오류 코드
569 *
570 * \param mapid 로그의 아이디 넘버
571 * \param path 로그 파일 경로
572 * \param memsize 로그 버퍼 크기
573 *
574 * \see CF_LOG_DEFAULT_BUFFER, CF_LOG_NO_BUFFER
575 */
576int
577CF_Log_Open (const int mapid,
578 const char * path,
579 const int memsize)
580{
581 int result = 0;
582 CF_Log_Ctx ctx = NULL;
583
584 result = CF_Log_CreateCtx (&ctx, path, memsize);
585 if (result < 0)
586 return result;
587
588 result = CF_Log_MapCtxID (mapid, ctx);
589 if (result < 0)
590 CF_Log_DestroyCtx (ctx);
591
592 return result;
593}
594
595/**
596 * 로그 닫기
597 *
598 * \return 성공 시, CF_OK; 실패 시, 오류 코드
599 *
600 * \param mapid 로그의 아이디 넘버
601 */
602int
603CF_Log_Close (const int mapid)
604{
605 return CF_Log_UnmapCtxID (mapid);
606}
607
608/**
609 * 로그 버퍼의 데이터를 즉시 로그 파일에 쓰기
610 *
611 * \return 성공 시, CF_OK; 실패 시, 오류 코드
612 *
613 * \param mapid 로그의 아이디 넘버
614 */
615int
616CF_Log_Flush (const int mapid)
617{
618 int result = 0;
619 CF_Log_Ctx ctx = NULL;
620
621 result = CF_Log_GetMappedCtx (mapid, &ctx);
622 if (result < 0)
623 return result;
624
625 result = CF_Log_FlushCtx (ctx);
626
627 return result;
628}
629
630/**
631 * 로그 컨텍스트에 멀티쓰레드 모드 설정
632 *
633 * \return 성공 시, CF_OK; 실패 시, 오류 코드
634 *
635 * \param mapid 로그의 아이디 넘버
636 * \param flag 설정/해제 bool 플래그
637 *
638 * \see CF_BOOL
639 */
640int
641CF_Log_SetMT (const int mapid,
642 const CF_BOOL flag)
643{
644 int result = 0;
645 CF_Log_Ctx ctx = NULL;
646
647 result = CF_Log_GetMappedCtx (mapid, &ctx);
648 if (result < 0)
649 return result;
650
651 result = (flag) ? CF_Log_SetMultiThread (ctx) :
652 CF_Log_UnsetMultiThread (ctx);
653
654 return result;
655}
656
657/**
658 * 로그 쓰기
659 *
660 * \return 성공 시, CF_OK; 실패 시, 오류 코드
661 *
662 * \param mapid 로그의 아이디 넘버
663 * \param prefix 로그의 프리픽스 문자열
664 * \param fmt 포맷 스트링
665 * \param ... 가변 인자
666 */
667int
668CF_Log_Write (const int mapid,
669 const char * prefix,
670 const char * fmt, ...)
671{
672 int result = 0;
673 CF_Log_Ctx ctx = NULL;
674 va_list valist;
675
676 result = CF_Log_GetMappedCtx (mapid, &ctx);
677 if (result < 0)
678 return result;
679
680 va_start (valist, fmt);
681 result = CF_Log_WriteCtx (ctx, prefix, fmt, valist);
682 va_end (valist);
683
684 return result;
685}
Note: See TracBrowser for help on using the repository browser.