-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloge.hpp
2654 lines (2084 loc) · 55.9 KB
/
loge.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
Copyright (c) 2024 notweerdmonk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file loge.hpp
* @author notweerdmonk
* @brief Log to stdout, stderr, file, file descriptor, syslog, TCP socket
*/
#ifndef _LOGE_HPP_
#define _LOGE_HPP_
#if defined(__linux) || defined(__linux__)
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 1 /* For fdopen */
/* linux */
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#elif defined(_WIN64)
/* win32 */
#include <io.h>
#include <fcntl.h>
#define _WINSOCKAPI_
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef ERROR
#undef ERROR
#endif
#endif
/* libc */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
/* glibc and BSD libc only */
#if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#include <syslog.h>
#endif
/***************************** Common code starts *****************************/
/* ANSI escape codes */
#define ANSI_FG_BLACK "\x1b[30m"
#define ANSI_FG_RED "\x1b[31m"
#define ANSI_FG_GREEN "\x1b[32m"
#define ANSI_FG_YELLOW "\x1b[33m"
#define ANSI_FG_BLUE "\x1b[34m"
#define ANSI_FG_MAGENTA "\x1b[35m"
#define ANSI_FG_CYAN "\x1b[36m"
#define ANSI_FG_WHITE "\x1b[37m"
#define ANSI_BG_BLACK "\x1b[40m"
#define ANSI_BG_RED "\x1b[41m"
#define ANSI_BG_GREEN "\x1b[42m"
#define ANSI_BG_YELLOW "\x1b[43m"
#define ANSI_BG_BLUE "\x1b[44m"
#define ANSI_BG_MAGENTA "\x1b[45m"
#define ANSI_BG_CYAN "\x1b[46m"
#define ANSI_BG_WHITE "\x1b[47m"
#define ANSI_BOLD "\x1b[1m"
#define ANSI_UNDERLINE "\x1b[4m"
#define ANSI_STRIKE "\x1b[9m"
#define ANSI_SLOW_BLINK "\x1b[5m"
#define ANSI_RESET "\x1b[0m"
#define ANSI_BG_RESET "\x1b[49m"
/* Error reporting macros */
#ifndef __cplusplus
#ifdef lgperror
#warning lgperror previoulsy defined
#undef lgperror
#endif
#define lgperror(msg) \
do { \
fprintf(stderr, "%s: " msg ": %s\n", \
__func__, \
strerror(errno) \
); \
} while (0)
#ifdef lgerror
#warning lgerror previoulsy defined
#undef lgerror
#endif
#include <stdio.h>
#define lgerror(msg, ...) \
do { \
fprintf(stderr, "%s: " msg "\n", \
__func__, \
__VA_ARGS__ \
); \
} while (0)
#else /* !__cplusplus */
#ifdef lgperror
#warning lgperror previoulsy defined
#undef lgperror
#endif
#include <iostream>
#include <cstdio>
#define lgperror(msg) \
do { \
std::cerr << __func__ << ": " << msg << ": " << strerror(errno) << '\n'; \
} while (0)
#ifdef lgerror
#warning lgerror previoulsy defined
#undef lgerror
#endif
#define lgerror(msg, ...) \
do { \
std::array<char, loge::constants::BUFFER_SIZE> buffer; \
snprintf(buffer.data(), loge::constants::BUFFER_SIZE, \
msg, __VA_ARGS__); \
buffer[loge::constants::BUFFER_SIZE - 1] = '\0'; \
std::cerr << __func__ << ": " << buffer.data() << '\n'; \
} while (0)
#endif /* !__cplusplus */
/* Stringification macros */
#define __xstr(s) __tostr(s)
#define __tostr(s) #s
/* Adjustment for fdopen */
#if defined(_MSC_VER)
#ifdef dup
#undef dup
#endif
#define dup _dup
#ifdef fdopen
#undef fdopen
#endif
#define fdopen _fdopen
#ifdef close
#undef close
#endif
#define close _close
#elif !defined(_POSIX_C_SOURCE) && !defined(_MSC_VER)
/* Declare fdopen anyway */
extern FILE *fdopen(int fd, const char *mode);
#endif
#define dup_str __xstr(dup)
#define fdopen_str __xstr(fdopen)
#define close_str __xstr(close)
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__linux) || defined(__linux__)
typedef int native_handle;
/**
* @brief Opaque type representing a network socket
*/
typedef int socket_type;
enum { LOGE_SOCK_ERR = -1 };
static
inline
native_handle socket_to_native(socket_type sock) {
return (native_handle)sock;
}
static
inline
socket_type native_to_socket(native_handle sock) {
return (socket_type)sock;
}
static
inline
void shutdown_socket(socket_type sock) {
shutdown(socket_to_native(sock), SHUT_RDWR);
}
static
inline
void destroy_socket(socket_type sock) {
close(socket_to_native(sock));
}
#else /* defined(__linux) || defined(__linux__) */
#pragma comment(lib, "ws2_32.lib")
typedef int native_handle;
typedef SOCKET socket_type;
enum { LOGE_SOCK_ERR = SOCKET_ERROR };
static
inline
native_handle socket_to_native(socket_type sock) {
return _open_osfhandle((intptr_t)sock, _O_RDONLY | _O_BINARY);
}
static
inline
socket_type native_to_socket(native_handle sock) {
return _get_osfhandle(sock);
}
static
inline
void shutdown_socket(socket_type sock) {
shutdown(sock, SD_BOTH);
}
static
inline
void destroy_socket(socket_type sock) {
closesocket(sock);
}
#endif
/**
* @brief Replace all occurences of a substring with anohter string. On success
* a new dynamically allocated string is returned that should be freed after
* use.
*
* https://stackoverflow.com/a/779960
*
* @param str The string in which the replacement happens
* @param pat The substring that will get replaced
* @param rep The string that will replace the substring
* @return NULL on failure, pointer to a dynamically allocated string on
* success
*/
static
char* strreplace(const char *str, const char *pat, const char *rep) {
const char *start;
char *p;
char *result;
size_t patlen;
size_t replen;
size_t reslen;
size_t offset;
size_t count;
if (!str || !pat) {
return NULL;
}
patlen = strlen(pat);
if (!patlen) {
return NULL;
}
if (!rep) {
rep = "";
}
replen = strlen(rep);
start = str;
for (count = 0; (p = strstr((char*)start, pat)); count++) {
start = p + patlen;
}
reslen = strlen(str) + (replen - patlen) * count;
if (!reslen) {
return NULL;
}
p = result = (char*)malloc(reslen + 1);
if (!result) {
return NULL;
}
while (count--) {
start = strstr(str, pat);
offset = start - str;
p = strncpy(p, str, offset) + offset;
p = strncpy(p, rep, replen) + replen;
str += offset + patlen;
reslen -= offset + replen;
}
strncpy(p, str, reslen);
p[reslen] = '\0';
return result;
}
#if defined(_MSC_VER) || !defined(__GLIBC__)
static
int dprintf(int d, const char *fmt, ...) {
enum { BUFFER_SIZE_DPRINTF = 4096 };
va_list ap;
int done;
int at = 0, nwrite = 0;
char *buf;
buf = (char*)malloc(sizeof(char) * BUFFER_SIZE_DPRINTF);
if (!buf) {
return 0;
}
va_start(ap, fmt);
done = vsnprintf(buf, BUFFER_SIZE_DPRINTF, fmt, ap);
va_end(ap);
do {
nwrite = _write(d, buf + at, done);
at += nwrite;
done -= nwrite;
} while (done > 0);
free(buf);
return at;
}
#endif
/**
* @brief Connect to a TCP server and associate an output stream with the
* socket. This stream will be set as the output stream for the logger. The log
* callback function will be overriden by the default. IPv4 and IPv6 addresses
* are supported.
* @param ploge Pointer to struct loge
* @param ip IPv4 or IPv6 address
* @param port Port number
* @param ipv6 Uses IPv6 if set to non-zero value, else uses IPv4
*
* @see loge_disconnect()
*/
static
socket_type sock_connect(const char *host, unsigned short port, int type, int ipv6) {
socket_type sock = LOGE_SOCK_ERR;
if (!host) {
return sock;
}
#if defined(__linux) || defined(__linux__)
struct sockaddr_in server_addr;
struct sockaddr_in6 server_addr6;
int domain = ipv6 ? AF_INET6 : AF_INET;
if ((sock = socket(domain, type > 0 ? SOCK_STREAM : SOCK_DGRAM, 0)) < 0) {
lgperror("socket failed");
return sock;
}
if (ipv6) {
memset(&server_addr6, 0, sizeof(struct sockaddr_in6));
server_addr6.sin6_family = AF_INET6;
server_addr6.sin6_port = htons(port);
} else {
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
}
struct sockaddr *addr = ipv6 ?
(struct sockaddr *)&server_addr6 :
(struct sockaddr *)&server_addr;
size_t addr_size = ipv6 ?
sizeof(struct sockaddr_in6) :
sizeof(struct sockaddr_in);
int ret;
/* Convert IPv4/IPv6 address from text to binary form */
if (ipv6) {
ret = inet_pton(AF_INET6, host, &server_addr6.sin6_addr);
} else {
ret = inet_pton(AF_INET, host, &server_addr.sin_addr);
}
if (ret <= 0) {
lgperror("inet_pton failed");
goto error;
}
if (connect(sock, addr, addr_size) == 0) {
return sock;
} else {
lgperror("connect failed");
}
error:
close(sock);
sock = LOGE_SOCK_ERR;
#elif defined(_WIN64)
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
struct sockaddr_in server_addr;
struct sockaddr_in6 server_addr6;
int domain = ipv6 ? AF_INET6 : AF_INET;
if ((sock = socket(domain, type > 0 ? SOCK_STREAM : SOCK_DGRAM, 0)) < 0) {
lgperror("socket failed");
return sock;
}
if (ipv6) {
memset(&server_addr6, 0, sizeof(struct sockaddr_in6));
server_addr6.sin6_family = AF_INET6;
server_addr6.sin6_port = htons(port);
} else {
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
}
struct sockaddr *addr = ipv6 ?
(struct sockaddr *)&server_addr6 :
(struct sockaddr *)&server_addr;
socklen_t addr_size = ipv6 ?
sizeof(struct sockaddr_in6) :
sizeof(struct sockaddr_in);
/* Convert IPv4/IPv6 address from text to binary form */
if (ipv6) {
ret = inet_pton(AF_INET6, host, &server_addr6.sin6_addr);
} else {
ret = inet_pton(AF_INET, host, &server_addr.sin_addr);
}
if (ret <= 0) {
lgperror("inet_pton failed");
goto error;
}
if (connect(sock, addr, addr_size) != SOCKET_ERROR) {
return sock;
} else {
lgperror("connect failed");
}
error:
closesocket(sock);
WSACleanup();
sock = LOGE_SOCK_ERR;
#endif
return sock;
}
static
const char *loglevel_strtbl[] = {
"",
"DEBUG",
"INFO",
"WARNING",
"ERROR",
"CRITICAL"
};
static
const char *loglevel_strtbl_color[] = {
"",
ANSI_FG_BLUE ANSI_BG_RESET "DEBUG" ANSI_RESET,
ANSI_FG_GREEN ANSI_BG_RESET "INFO" ANSI_RESET,
ANSI_FG_YELLOW ANSI_BG_RESET "WARNING" ANSI_RESET,
ANSI_FG_RED ANSI_BG_RESET "ERROR" ANSI_RESET,
ANSI_FG_WHITE ANSI_BG_RED "CRITICAL" ANSI_RESET
};
/****************************** Common code ends ******************************/
/******************************* C code starts ********************************/
#ifndef __cplusplus
/**
* @brief Macro to be used for logging information.
* @param ploge Pointer to struct loge.
* @param level Log type/level. Messages below this level will not be logged.
* @param ... Message format string and associated arguments.
*/
#define LOGE(ploge, level, ...) \
do { \
if ((ploge) != NULL) \
loge_log( \
(struct loge*)(ploge), \
(level) & ~LOGCOLOR, \
__LINE__, \
__FILE__, \
__VA_ARGS__ \
); \
} while (0)
#define LOGE_COLOR(ploge, level, ...) \
do { \
if ((ploge) != NULL) \
loge_log( \
(struct loge*)(ploge), \
(level) | LOGCOLOR, \
__LINE__, \
__FILE__, \
__VA_ARGS__ \
); \
} while (0)
#define LOGE_TYPE(entime, level) \
(int)( ( (!!(entime)) << LOGTIMESTAMPSHIFT ) | (level) )
#define LOGE_ENTIME(type) \
(int)(!!(type & LOGTIMESTAMP))
#define LOGE_LEVEL(type) \
(enum loge_level)(type & ~LOGTIMESTAMP)
#define LOGE_LOGTYPE(encolor, level) \
(int)( ( (!!(encolor)) << LOGCOLORSHIFT ) | (level) )
#define LOGE_ENCOLOR(type) \
(int)(!!(type & LOGCOLOR))
#define LOGE_LOGLEVEL(type) \
(enum loge_level)(type & ~LOGCOLOR)
enum loge_constants {
LINENUMBER_WIDTH = 6,
NUMBER_WIDTH = 8,
BUFFER_SIZE = 1024,
LOGTIMESTAMPSHIFT = 31,
LOGCOLORSHIFT = 31,
LOGTIMESTAMP = 1 << LOGTIMESTAMPSHIFT,
LOGCOLOR = 1 << LOGCOLORSHIFT
};
/**
* @brief Enum type for levels of logging. Each level can represent a class of
* information that is to be logged
*
* The log level can be used to filter messages. All messages that have log
* type/level less that the specified type/level will not get logged.
*/
enum loge_level {
LOGE_ALL = 0, /**< Everything */
LOGE_DEBUG, /**< Debug information */
LOGE_INFO, /**< Run time information like statuses, user output, etc */
LOGE_WARNING, /**< Warnings */
LOGE_ERROR, /**< Errors */
LOGE_CRITICAL, /**< Critical errors */
LOGE_MAX
};
/* Forward declaration */
struct loge;
/**
* @brief Defines the type for function used as log callback function.
* @param ploge Pointer to struct loge
*
* @see loge_set_fn()
* @see loge_log()
*/
typedef void (*log_fn)(const struct loge *ploge);
/**
* @brief Defines type for function used as raw data callback function.
* @param ploge,Pointer to struct loge
* @param file Output stream of the logger
* @param timestamp Number of seconds since Epoch
* @param filename Name of the source file
* @param linenum Line number of the source file from where logging happened
* @param level Type/level of log
* @param msg User message. This is the result of applying arguments to the
* format string passed to loge_log()
*
* @see loge_set_data_fn()
* @see loge_log()
*/
typedef void (*log_data_fn)(
FILE *file,
time_t timestamp,
const char *filename,
int linenum,
enum loge_level level,
const char *msg
);
struct loge {
char *bufptr;
char buffer[BUFFER_SIZE];
size_t bufcap;
size_t buflen;
log_fn plogfn, pprevlogfn;
log_data_fn pdatafn;
FILE *file;
socket_type sockfd;
int log_type;
int linenumwidth;
int width;
int precision;
int syslog_priority;
};
/**
* @brief Get pointer to a string containing the name of the log type/level
* @param level Enum mentioning the log type/level
* @return Pointer to a string
*
* @see enum loge_level
*/
static
const char* loge_get_level(enum loge_level level) {
return level > LOGE_ALL && level < LOGE_MAX ?
loglevel_strtbl[level] :
NULL;
}
/**
* @brief Get pointer to a string containing the name of the log type/level
* along with ANSI escape codes for colored output
* @param level Enum mentioning the log type/level
* @return Pointer to a string
*
* @see enum loge_level
*/
static
const char* loge_get_level_color(enum loge_level level) {
return level > LOGE_ALL && level < LOGE_MAX ?
loglevel_strtbl_color[level] :
NULL;
}
static
const char* loge_bufptr(const struct loge *ploge) {
return !ploge ? (const char*)ploge : ploge->bufptr;
}
static
FILE* loge_fileptr(const struct loge *ploge) {
return !ploge ? (FILE*)ploge : ploge->file;
}
/**
* @brief Write a string followed by a newline character to a stream. This is
* the default callback function.
* @param ploge Pointer to struct loge
*/
static
void log_internal(const struct loge *ploge) {
if (!ploge) {
return;
}
FILE *file = loge_fileptr(ploge);
if (!file) {
return;
}
fputs(loge_bufptr(ploge), file);
fputc('\n', file);
fflush(file);
}
/* glibc and BSD libc only */
#if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__)
static
void log_syslog(const struct loge *ploge) {
if (!ploge) {
return;
}
const char *msg = loge_bufptr(ploge);
syslog(ploge->syslog_priority, "%s\n", msg);
}
#endif
/**
* @brief Set the log type/level to be filtered by the logger. Messages below
* this level will not be logged.
* @param ploge Pointer to struct loge
* @param level Enum mentioning the log type/level
*
* @see enum loge_level
*/
static
void loge_set_level(struct loge *ploge, enum loge_level level) {
if (!ploge) {
return;
}
int en_timestamp = LOGE_ENTIME(ploge->log_type);
if (level < LOGE_MAX) {
ploge->log_type = LOGE_TYPE(en_timestamp, level);
}
}
/**
* @brief Set the callback function to be used for writing the log message to
* a stream. This will override previous callback function if a non-NULL
* address is passed.
*
* The output stream and log message are passed on to this callback function.
* Log string provided to this function will be formatted as:
* m-dd-yyyy : HH-mm-ss : filename:linenum : loglevel : user_message
*
* User message will be the result of applying arguments to a format string.
*
* @param ploge Pointer to struct loge
* @param fn Pointer to the callback function
*
* @see log_fn
* @see loge_log()
*/
static
void loge_set_fn(struct loge *ploge, log_fn fn) {
if (!ploge || !fn) {
return;
}
ploge->pprevlogfn = ploge->plogfn;
ploge->plogfn = fn;
}
/**
* @brief Set the callback function that can be used alternatively for writing
* the the log message to a stream. This will override previous callback
* function even when a NULL address is passed. Additional arguments are passed
* to this callback function.
* @param ploge Pointer to struct loge
* @param fn Pointer to the callback function
*
* @see log_data_fn
* @see loge_log()
*/
static
void loge_set_data_fn(struct loge *ploge, log_data_fn fn) {
if (!ploge) {
return;
}
ploge->pdatafn = fn;
}
static
FILE* loge_set_fd(struct loge *ploge, int fd) {
if (!ploge) {
return NULL;;
}
FILE *prev = ploge->file;
if (fd < 0) {
return prev;
}
int newfd = dup(fd);
if (newfd < 0) {
lgperror(dup_str" failed");
return prev;
}
FILE *file = fdopen(newfd, "w");
if (!file) {
lgperror(fdopen_str" failed");
close(newfd);
return prev;
}
ploge->file = file;
ploge->pprevlogfn = ploge->plogfn;
ploge->plogfn = &log_internal;
return prev;
}
static
void loge_unset_fd(struct loge *ploge) {
if (!ploge) {
return;
}
if (ploge->file != stdout && ploge->file != stderr) {
fclose(ploge->file);
}
ploge->file = NULL;
ploge->plogfn = ploge->pprevlogfn;
}
/**
* @brief Set the stream to which log messages will be written.
* @param ploge Pointer to struct loge
* @param file Pointer to the stream
*/
static
FILE* loge_set_fileptr(struct loge *ploge, FILE *file) {
if (!ploge) {
return NULL;
}
FILE *prev = ploge->file;
if (file) {
ploge->file = file;
}
return prev;
}
static
FILE* loge_unset_fileptr(struct loge *ploge) {
if (!ploge) {
return NULL;
}
FILE *prev = ploge->file;
ploge->file = NULL;
return prev;
}
/**
* @brief Set the stdout stream as the output stream. The default callback
* function will also be set. User may override it.
* @param ploge Pointer to struct loge
*/
static
FILE* loge_set_stdout(struct loge *ploge) {
if (!ploge) {
return NULL;
}
ploge->pprevlogfn = ploge->plogfn;
ploge->plogfn = &log_internal;
FILE *prev = ploge->file;
ploge->file = stdout;
return prev;
}
/**
* @brief Set the stderr stream as the output stream. The default callback
* function will also be set. User may override it.
* @param ploge Pointer to struct loge
*/
static
FILE* loge_set_stderr(struct loge *ploge) {
if (!ploge) {
return NULL;
}
ploge->pprevlogfn = ploge->plogfn;
ploge->plogfn = &log_internal;
FILE *prev = ploge->file;
ploge->file = stderr;
return prev;
}
/* glibc and BSD libc only */
#if defined(__GLIBC__) || defined(__FreeBSD__) || defined(__OpenBSD__)
static
FILE* loge_set_syslog(struct loge *ploge, int priority) {
if (!ploge) {
return NULL;
}
FILE *prev = ploge->file;
/* Clear FILE pointer and pdatafn */
ploge->file = NULL;
ploge->pdatafn = NULL;
ploge->syslog_priority = priority;
ploge->pprevlogfn = ploge->plogfn;
ploge->plogfn = &log_syslog;
return prev;
}
#endif
/**
* @brief Set file which will be created or appended to, for writing log
* messages. The file will be opened and a stream will be associated with it.
* This stream will be set as the output stream for the logger. The default
* callback function will also be set. User may override it.
* @param ploge pointer to struct loge
* @param filepath Relative or absolute path of the output file
*/
static
FILE* loge_set_file(struct loge *ploge, const char *filepath) {
if (!ploge) {
return NULL;
}
FILE *prev = ploge->file;
if (!filepath) {
return prev;
}
int fd = -1;
FILE *file = NULL;
#if defined(__linux) || defined(__linux__)
fd = open(filepath,
O_WRONLY|O_CREAT|O_APPEND|O_SYNC,
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
if (!fd) {
lgperror("open failed");
return prev;
}
file = fdopen(fd, "w");
if (!file) {
lgperror("fdopen failed");
if (fd > -1) {
close(fd);