0

I'm currently trying to define log macro for a program which runs as a deamon.

As it's a deamon, I redirect both stdout and stderr to a specific file. This step is okay and I have two macro for logging which write in the same file.

define LOG(fmt, args...)        fprintf(stdout, fmt, ## args); \
                                fflush(stdout)

#define LOG_ERR(fmt, args...)   fprintf(stderr, fmt, ## args);

My point is I would like to have a "perror-like" trace :

<Message with arguments> : <errno associated message>

So I searched a little and if I modified LOG_ERR to :

#define LOG_ERR(fmt, args...)   fprintf(stderr, fmt, ## args); \
                                perror("")

It works but the errno associated message is sent after a \n caracter (I think because stderr is buffered) So I obtain :

<Message with arguments>
<errno associated message>

Another solution could be to use strerror function as last parameter but I really don't know if it's possible to do so. It would look like :

#define LOG_ERR(fmt, args...)   fprintf(stderr, fmt, ## args, strerror(errno));

But this solution also fail as errno signification is not inserted and even the end of line caracter is not written.

Does someone know how I could achieve it without using a function?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Arkaik
  • 852
  • 2
  • 19
  • 39
  • Just a comment: In general, daemon processes should not use stdout and stderr. Maybe syslog() or vsyslog() is a better choice? – Bjorn A. Jul 10 '17 at 16:24
  • 1
    Why function is wrong? You call printf anyway. Make the function inline and you will have the same performance. – 0___________ Jul 10 '17 at 16:24
  • Will the `fmt` argument always be a string literal? Then you can use either string concatenation with `#` or just with a space. E.g. `fmt ": %s\n"` – Some programmer dude Jul 10 '17 at 16:25
  • You can use `strerror()`, subject to the usual caveats (mainly making sure you capture the correct value of `errno` before it changes). See also [C `#define` macro for debug printing](https://stackoverflow.com/questions/1644868/c-define-macro-for-debug-printing/). – Jonathan Leffler Jul 10 '17 at 16:28

1 Answers1

0

Thanks to your advises I suceeded to do what I wanted to.

Following Bjorn advice, I changed to use syslog instead of stderr and stdout. Bjorn do you have more information about why a daemon should not use stderr and stdout? I'm curious to know the reasons.

I give my solution in case it could be useful to someone.

#define SYSLOG(fmt, args...)        syslog(LOG_NOTICE, fmt, ## args);
#define SYSLOG_ERR(fmt, args...)    syslog(LOG_ERR, fmt " : %s", ## args , strerror(errno));

Don't forget previous

openlog("<program_name>", LOG_PID, LOG_DAEMON);

Thanks again ;)

Arkaik
  • 852
  • 2
  • 19
  • 39