Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to create a log function to output messages in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

typedef enum {
    LOG_LEVEL_ERROR = 0,
    LOG_LEVEL_WARNING = 1,
    LOG_LEVEL_INFO = 2,
} log_level;

#define SIZE 16000

void log_out(log_level levelno, const char* message, ...) {
    const char* levelstr[3] = {"[ERROR]: ", "[WARNING]: ", "[INFO]: "};

    char _message[SIZE] = "";

    __builtin_va_list arg_ptr;
    va_start(arg_ptr, message);
    vsnprintf(_message, SIZE, message, arg_ptr);
    va_end(arg_ptr);

    char out_message[SIZE * 2];
    sprintf(out_message, "%s%s\n", levelstr[levelno], _message);
    
    printf("%s", out_message);
}

int main(void)
{
    log_out(LOG_LEVEL_ERROR, "message: '%s', in file: %s, line: %d\n", "Your error message", __FILE__, __LINE__);
    log_out(LOG_LEVEL_WARNING, "message: '%s', in file: %s, line: %d\n", "Your warning message", __FILE__, __LINE__);
    log_out(LOG_LEVEL_INFO, "message: '%s', in file: %s, line: %d\n", "Your info message", __FILE__, __LINE__);
    
    return 0;
}

 
 
/*
run:

[ERROR]: message: 'Your error message', in file: main.c, line: 30

[WARNING]: message: 'Your warning message', in file: main.c, line: 31

[INFO]: message: 'Your info message', in file: main.c, line: 32

*/

 



answered May 28, 2024 by avibootz

Related questions

...