2 * Copyright (C) 2011-2012 Juho Vähä-Herttua
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
24 mutex_handle_t lvl_mutex
;
25 mutex_handle_t cb_mutex
;
29 logger_callback_t callback
;
35 logger_t
*logger
= calloc(1, sizeof(logger_t
));
38 MUTEX_CREATE(logger
->lvl_mutex
);
39 MUTEX_CREATE(logger
->cb_mutex
);
41 logger
->level
= LOGGER_WARNING
;
42 logger
->callback
= NULL
;
47 logger_destroy(logger_t
*logger
)
49 MUTEX_DESTROY(logger
->lvl_mutex
);
50 MUTEX_DESTROY(logger
->cb_mutex
);
55 logger_set_level(logger_t
*logger
, int level
)
59 MUTEX_LOCK(logger
->lvl_mutex
);
60 logger
->level
= level
;
61 MUTEX_UNLOCK(logger
->lvl_mutex
);
65 logger_set_callback(logger_t
*logger
, logger_callback_t callback
, void *cls
)
69 MUTEX_LOCK(logger
->cb_mutex
);
71 logger
->callback
= callback
;
72 MUTEX_UNLOCK(logger
->cb_mutex
);
76 logger_utf8_to_local(const char *str
)
80 /* FIXME: This is only implemented on Windows for now */
81 #if defined(_WIN32) || defined(_WIN64)
86 wclen
= MultiByteToWideChar(CP_UTF8
, 0, str
, -1, NULL
, 0);
87 wcstr
= malloc(sizeof(WCHAR
) * wclen
);
88 MultiByteToWideChar(CP_UTF8
, 0, str
, -1, wcstr
, wclen
);
90 mblen
= WideCharToMultiByte(CP_ACP
, 0, wcstr
, wclen
, NULL
, 0, NULL
, &failed
);
92 /* Invalid characters in input, conversion failed */
97 ret
= malloc(sizeof(CHAR
) * mblen
);
98 WideCharToMultiByte(CP_ACP
, 0, wcstr
, wclen
, ret
, mblen
, NULL
, NULL
);
106 logger_log(logger_t
*logger
, int level
, const char *fmt
, ...)
111 MUTEX_LOCK(logger
->lvl_mutex
);
112 if (level
> logger
->level
) {
113 MUTEX_UNLOCK(logger
->lvl_mutex
);
116 MUTEX_UNLOCK(logger
->lvl_mutex
);
118 buffer
[sizeof(buffer
)-1] = '\0';
120 vsnprintf(buffer
, sizeof(buffer
)-1, fmt
, ap
);
123 MUTEX_LOCK(logger
->cb_mutex
);
124 if (logger
->callback
) {
125 logger
->callback(logger
->cls
, level
, buffer
);
126 MUTEX_UNLOCK(logger
->cb_mutex
);
129 MUTEX_UNLOCK(logger
->cb_mutex
);
130 local
= logger_utf8_to_local(buffer
);
132 fprintf(stderr
, "%s\n", local
);
135 fprintf(stderr
, "%s\n", buffer
);