Browse Source

fixed mistakes and added an example

master
Arwed Mett 4 years ago
parent
commit
bbb88257d9
Signed by: Pfeifenjoy GPG Key ID: 86943827297DA9FC
  1. 3
      CMakeLists.txt
  2. 8
      example/main.c
  3. 32
      src/logging.c

3
CMakeLists.txt

@ -7,6 +7,9 @@ target_include_directories(logging PUBLIC
$<INSTALL_INTERFACE:include>
)
add_executable(example example/main.c)
target_link_libraries(example logging)
install(TARGETS logging EXPORT LoggingTargets
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib

8
example/main.c

@ -0,0 +1,8 @@
#include "logging/logging.h"
int main(const int argc, const char **argv) {
debug(0, "42"); // -> [DEBUG] 42
error("42"); // -> [ERROR] 42
info("42"); // -> [INFO] 42
warn("42"); // -> [WARN] 42
}

32
src/logging.c

@ -11,7 +11,7 @@
#define BLUE "\x1b[34m"
#define RESET "\x1b[0m"
#define MAX_LABEL_WIDTH 8
#define MAX_LABEL_WIDTH 5
debug_level current_debug_level = 0;
@ -21,16 +21,16 @@ char *scolor(FILE *out, const char *color, const char *text) {
//check if the programs output is a file
if(isatty(fileno(out))) {
length = strlen(color) + strlen(text) + strlen(RESET) + 1;
result = malloc(length * sizeof(char));
snprintf(result, length, "%s%s%s", color, text, RESET);
length = strlen(color) + strlen(text) + strlen(RESET);
result = malloc((length + 1) * sizeof(char));
snprintf(result, length + 1, "%s%s%s", color, text, RESET);
} else {
length = strlen(text) + 1;
result = malloc(length * sizeof(char));
snprintf(result, length, "%s", text);
length = strlen(text);
result = malloc((length + 1) * sizeof(char));
strcpy(result, text);
}
result[length - 1] = 0;
result[length] = 0;
return result;
}
@ -49,10 +49,10 @@ char *make_label(FILE *out, const char *color, const char *name) {
char *colored_name = scolor(out, color, name);
char *space = printr(' ', MAX_LABEL_WIDTH - strlen(name));
size_t length = MAX_LABEL_WIDTH + strlen("[") + strlen("] ") + 1;
char *result = (char *) malloc(length * sizeof(char));
snprintf(result, length, "[%s]%s ", colored_name, space);
result[length - 1] = 0;
size_t length = strlen(colored_name) + strlen("[") + strlen("] ") + strlen(space);
char *result = (char *) malloc((length + 1) * sizeof(char));
snprintf(result, length + 1, "[%s]%s ", colored_name, space);
result[length] = 0;
free(colored_name);
free(space);
@ -72,10 +72,10 @@ void vlog(
char *label = make_label(out, color, label_text);
//create format
size_t format_length = strlen(label) + strlen(text) + 2;
char *format = (char *) malloc(format_length * sizeof(char));
snprintf(format, format_length, "%s%s\n", label, text);
format[format_length - 1] = 0;
size_t format_length = strlen(label) + strlen(text) + strlen("\n");
char *format = (char *) malloc((format_length + 1) * sizeof(char));
snprintf(format, format_length + 1, "%s%s\n", label, text);
format[format_length] = 0;
//print
vfprintf(out, format, args);

Loading…
Cancel
Save