5

I'm using perror() to print error messages, like:

pid = fork();
if (pid < 0) {
    perror("couldn't fork");
    exit(EXIT_FAILURE);
}

Is it possible to use errno/perror() facilities but direct the produced messages to the system log (/var/log/syslog)?

I ask this in the context of a program which can be run in both daemon and non-daemon modes. In daemon mode, perror() messages won't appear on syslog.

João M. S. Silva
  • 1,078
  • 2
  • 11
  • 24
  • 1
    check early in the code as to the current mode. Then write a small function that takes a string as a parameter and either calls perror() or calls syslog() depending on the current mode, as set earlier in the program – user3629249 Dec 12 '15 at 11:02

3 Answers3

11

Use strerror to get the error message based on an error code, without printing it. Then pass it to syslog like any other log message:

syslog(LOG_ERR, "Couldn't fork: %s", strerror(errno));
user253751
  • 57,427
  • 7
  • 48
  • 90
2

The easiest way is to redirect stderr (and possibly stdout) when you call your program. For example: ./myprog 2>&1 | logger.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Thanks, but I'd like to this this the right way, i.e. using code specific to daemons (fork, etc.) and `syslog()`. – João M. S. Silva Dec 11 '15 at 00:31
  • Using redirection, for example in a shell script or cron entry, *IS* the "right way" in the vast majority of circumstances. If you want to log programmatically, then refer to "[man syslog](http://linux.die.net/man/3/syslog)". And if you want to redirect (stderr, file #2), then use dup2: http://stackoverflow.com/questions/14543443/in-c-how-do-you-redirect-stdin-stdout-stderr-to-files-when-making-an-execvp-or. And if you want the error text independent of calling perror(), then [man strerror](http://linux.die.net/man/3/strerror). – paulsm4 Dec 11 '15 at 00:32
  • I'm using `syslog()`. What I'd like to do is to conjugate `syslog()` with `errno/perror()`. – João M. S. Silva Dec 11 '15 at 00:36
  • 2
    Then it sounds like strerror() might be your guy :) – paulsm4 Dec 11 '15 at 00:37
2

Assuming you have the right permissions to write to syslog, I don't see why you couldn't pipe your output to that file. You could also use fprintf with stderr to output the error result to a file you create.

user_ABCD
  • 347
  • 2
  • 15
  • The requirements are that I'd like to use `errno` and `perror()` functionalities. `errno` is set to an appropriate error number when a system call fails and `perror()` prints the associated error message. – João M. S. Silva Dec 11 '15 at 00:33
  • 2
    Unless he's running as root, he won't have permission to write directly to syslog. Everything should be sent through the `syslog()` function. – Barmar Dec 11 '15 at 01:06