Skip to content

Instantly share code, notes, and snippets.

@jonathanmarvens
Last active November 15, 2017 09:20
Show Gist options
  • Save jonathanmarvens/a31c66e2e44956bc7841 to your computer and use it in GitHub Desktop.
Save jonathanmarvens/a31c66e2e44956bc7841 to your computer and use it in GitHub Desktop.
/**
****************************************************************************
* Copyright 2015 Jonathan Barronville <[email protected]> *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
****************************************************************************
*/
#pragma once
#include <assert.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define PROGRAM_NAME "blah"
// @jonathanmarvens' very simple logger generation macro.
#define GENERATE_LOGGER(log_level) \
void \
blah_log_##log_level(char const * log_format_string, ...) { \
/* Get the current time. */ \
time_t const time_ = time(NULL); \
/* Convert the raw time into a ISO 8601 date and time-formatted string. */ \
char formatted_date[21]; /* YYYY-MM-DDThh:mm:ssZ (20 + '\0') */ \
assert(strftime(formatted_date, (sizeof formatted_date), "%Y-%m-%dT%TZ", \
gmtime(&time_)) != 0); \
/* Log! */ \
fprintf(stderr, "[%s] [%s] [%s]\n", PROGRAM_NAME, #log_level, formatted_date); \
size_t const log_format_string_length = strlen(log_format_string); \
char log_format_string_2[((int) log_format_string_length) + 2]; \
log_format_string_2[0] = '\0'; \
strncat(log_format_string_2, log_format_string, log_format_string_length); \
strncat(log_format_string_2, "\n", (size_t) 1); \
va_list extra_arguments; \
va_start(extra_arguments, log_format_string); \
vfprintf(stderr, log_format_string_2, extra_arguments); \
va_end(extra_arguments); \
}
GENERATE_LOGGER(debug) // blah_log_debug
GENERATE_LOGGER(error) // blah_log_error
GENERATE_LOGGER(info) // blah_log_info
GENERATE_LOGGER(warn) // blah_log_warn
@jonathanmarvens
Copy link
Author

E.g.:

blah_log_info("Opening up document: \"%s\".", "wat.txt");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment