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
;
28 logger_callback_t callback
;
34 logger_t
*logger
= calloc(1, sizeof(logger_t
));
37 MUTEX_CREATE(logger
->lvl_mutex
);
38 MUTEX_CREATE(logger
->cb_mutex
);
40 logger
->level
= LOGGER_WARNING
;
41 logger
->callback
= NULL
;
46 logger_destroy(logger_t
*logger
)
48 MUTEX_DESTROY(logger
->lvl_mutex
);
49 MUTEX_DESTROY(logger
->cb_mutex
);
54 logger_set_level(logger_t
*logger
, int level
)
58 MUTEX_LOCK(logger
->lvl_mutex
);
59 logger
->level
= level
;
60 MUTEX_UNLOCK(logger
->lvl_mutex
);
64 logger_set_callback(logger_t
*logger
, logger_callback_t callback
)
68 MUTEX_LOCK(logger
->cb_mutex
);
69 logger
->callback
= callback
;
70 MUTEX_UNLOCK(logger
->cb_mutex
);
74 logger_utf8_to_local(const char *str
)
78 /* FIXME: This is only implemented on Windows for now */
79 #if defined(_WIN32) || defined(_WIN64)
84 wclen
= MultiByteToWideChar(CP_UTF8
, 0, str
, -1, NULL
, 0);
85 wcstr
= malloc(sizeof(WCHAR
) * wclen
);
86 MultiByteToWideChar(CP_UTF8
, 0, str
, -1, wcstr
, wclen
);
88 mblen
= WideCharToMultiByte(CP_ACP
, 0, wcstr
, wclen
, NULL
, 0, NULL
, &failed
);
90 /* Invalid characters in input, conversion failed */
95 ret
= malloc(sizeof(CHAR
) * mblen
);
96 WideCharToMultiByte(CP_ACP
, 0, wcstr
, wclen
, ret
, mblen
, NULL
, NULL
);
104 logger_log(logger_t
*logger
, int level
, const char *fmt
, ...)
109 MUTEX_LOCK(logger
->lvl_mutex
);
110 if (level
> logger
->level
) {
111 MUTEX_UNLOCK(logger
->lvl_mutex
);
114 MUTEX_UNLOCK(logger
->lvl_mutex
);
116 buffer
[sizeof(buffer
)-1] = '\0';
118 vsnprintf(buffer
, sizeof(buffer
)-1, fmt
, ap
);
121 MUTEX_LOCK(logger
->cb_mutex
);
122 if (logger
->callback
) {
123 logger
->callback(level
, buffer
);
124 MUTEX_UNLOCK(logger
->cb_mutex
);
127 MUTEX_UNLOCK(logger
->cb_mutex
);
128 local
= logger_utf8_to_local(buffer
);
130 fprintf(stderr
, "%s\n", local
);
133 fprintf(stderr
, "%s\n", buffer
);