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

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

#1 fix preprocessor definition for windows

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