From 3fbdccfc89a6cf3f0fb9cf299d6d1e1508993f6f Mon Sep 17 00:00:00 2001 From: Zijian Xu Date: Sat, 12 Apr 2025 17:54:54 +0200 Subject: [PATCH] Add option for a custom formatter --- README.md | 22 +++++++++++++++++++++- src/ulog.c | 10 +++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 85829c6..3a3d556 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Some features of uLog: * uLog is easy to incorporate into nearly any environment, comprising one header file and one source file, and is written in pure C. * uLog provides familiar severity levels (CRITICAL, ERROR, WARNING, INFO, DEBUG, TRACE). * uLog supports multiple user-defined outputs (console, log file, in-memory buffer, etc), each with its own reporting threshold level. -* uLog is "aggressively standalone" with minimal dependencies, requiring only stdio.h, string.h and stdarg.h. +* uLog is "aggressively standalone" with minimal dependencies, requiring just string.h, stdarg.h and only additionally stdio.h if you don't provide a custom formatter. * uLog gets out of your way when you're not using it: if ULOG_ENABLED is undefined at compile time, no logging code is generated. * uLog is well tested. See the accompanying ulog_test.c file for details. @@ -66,6 +66,26 @@ int main() { } ``` +## A custom formatter for uLog + +If `-DULOG_FORMATTER` is defined, uLog then tries to use `ulog_formatter()` with +the same signature as `vsnprintf()` to format the output: + +``` c +int ulog_formatter(char*, size_t, const char*, va_list); +``` + +For cases you wish to handroll the formatter yourself, or just want to use +another `vsnprintf()` implementation by simply forwarding the arguments to it: + +``` c +int ulog_formatter(char* buffer, size_t count, const char* format, va_list va) { + return vsnprintf_(buffer, count, format, va); // another vsnprintf impl. +} +``` + +Otherwise uLog falls back to `vsnprintf()` from ``. + ## Questions? Comments? Improvements? Comments and pull requests are welcome in https://github.com/rdpoor/ulog/issues diff --git a/src/ulog.c b/src/ulog.c index 2872de2..4f051d2 100644 --- a/src/ulog.c +++ b/src/ulog.c @@ -33,9 +33,13 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifdef ULOG_ENABLED // whole file... -#include #include #include +#ifdef ULOG_FORMATTER +extern int ulog_formatter(char*, size_t, const char*, va_list); +#else +#include +#endif // ============================================================================= @@ -124,7 +128,11 @@ void ulog_message(ulog_level_t severity, const char *fmt, ...) { va_list ap; int i; va_start(ap, fmt); +#ifdef ULOG_FORMATTER + ulog_formatter(s_message, ULOG_MAX_MESSAGE_LENGTH, fmt, ap); +#else vsnprintf(s_message, ULOG_MAX_MESSAGE_LENGTH, fmt, ap); +#endif va_end(ap); for (i=0; i