How to configure syslog so that an applications log goes to a specific file
Asked Answered
E

3

13

I have an application myapp which should send log files only to /var/log/myapp.log. myapp is written in C++. The following sample code, sends the logs to /var/log/syslog only. My os is Linux - Ubuntu 12.04 - to be specific. I also found that my machine has rsyslog than syslog installed.

#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {
    openlog("myapp", LOG_PID|LOG_CONS, LOG_USER);
    syslog(LOG_INFO, "abc 10");
    closelog();
    return 0;
}
Eudemonics answered 29/4, 2012 at 21:13 Comment(0)
C
12

According to the syslog(3) manpage, the first parameter for openlog() sets a prefix for log messages, not a filename. You can use a facility like LOG_LOCAL0 to flag your output and then configure syslogd using /etc/syslog.conf to send those logs to the file of your desire.

Contractive answered 29/4, 2012 at 22:43 Comment(2)
How to configure syslog.conf so that the log messages from my application go to a specific file ? Writing onto a simple file is not a good solution - read this link https://mcmap.net/q/277998/-daemon-logging-in-linux and the answer given by stackoverflow.com/users/7740/richardEudemonics
@Eudemonics You can directly give the link to an answer by copying the link location from the 'share' link after each answer. Like this - https://mcmap.net/q/277998/-daemon-logging-in-linuxGaullism
P
2

If your Ubuntu is working with rsyslog, you need to find the configuration file /etc/rsyslog.conf and modify it.

$ echo "if \$programname == 'myapp' then /var/log/myapp.log \n& ~" >> /etc/rsyslog.conf

Then you restart the utility:

$ sudo service rsyslog restart

And run your programm:

$ ./myapp

Check your log:

$ cat /var/log/myapp.log 
Apr  8 14:01:51 myusername myapp[21508]: abc 10
Pentahedron answered 8/4, 2022 at 17:8 Comment(0)
D
2

This worked for me: OS: Ubuntu 20.04

  1. Add to the config /etc/rsyslog.conf

:programname,contains,"myapp" /var/log/myapp.log

  1. service rsyslog restart
Dishevel answered 19/9, 2023 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.