Using rsyslog to log

I’m a great fan of logging; it helps you find out what’s happening in a program even if you can’t debug it. Linux, well Ubuntu has a service (sorry Daemon!) called rsyslog that logs messages from all sorts of processes and it’s quite easy to use in our programs as well.
If we don’t do the next steps all the log messages will go into a file called syslog in /var/log and as this gets a lot of stuff it can grow reasonably quickly. But if you do the following steps, all logged output will instead go into
/var/log/asteroids.log.
From a terminal type the following command:
sudo gedit /etc/rsyslog.d/30-debugging.conf
Type this in and then save it (click the Save button) and close gedit.
if $programname == 'asteroids' then /var/log/asteroids.log & ~
Now run this command:
sudo service rsyslog restart
It should return immediately and means that any logging to syslog from a program called asteroids will from now on be redirected to /var/log/asteroids.log.
Using rsyslog in a C program
Here’s a short C Program that puts a message in the asteroids file.
#include <syslog.h>
#include <stdio.h>
int main() {
openlog("asteroids",LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER);
syslog(LOG_INFO,"Test Message %d",1);
closelog();
}
In a typical program you’d put the openlog statement in main() near the start and the closelog() near the end of main, and uses as many syslog() calls throughout your program as you need.
Now what I suggest you do is open another terminal and run this command before you run your main program. This will just sit there printing out each message line as it appears in asteroids.log. You can stop tail by hitting ctrl-c.
tail -f /var/log/asteroids.log
H/T to this StackExchange answer from almost 8 years ago and answer by giuspen.