Is there any way to make a log file for maintaining some data in /var/log/ with the help of some library function or system call in c language in linux. And I also want to know the standards that we should follow to write and process log.
Thanks
Linux – make a log file
clinuxlogssyslog
Best Answer
The standard way to log from a C program is
syslog
.Start by including the header file:
Then early in your program, you should configure syslog by calling
openlog
:The first argument is the identification or the tag, which is automatically added at the start of each message. Put your program's name here.
The second argument is the options you want to use, or
0
for the normal behavior. The full list of options is inman 3 syslog
. One you might find useful isLOG_PID
, which makes syslog also record the process id in the log message.Then, each time you want to write a log message, you call
syslog
:The first argument is the priority. The priority ranges from
DEBUG
(least important) toEMERG
(only for emergencies) withDEBUG
,INFO
, andERR
being the most commonly used. Seeman 3 syslog
for your options.The second and third arguments are a format and a message, just like printf.
Which log file this appears in depends on your syslog settings.
With a default setup, it probably goes into
/var/log/messages
.You can set up a custom log file by using one of the facilities in the range
LOG_LOCAL0
toLOG_LOCAL7
.You use them by changing:
to
or
etc.
and adding a corresponding entry to
/etc/syslog.conf
, e.g.and restarting the syslog server, e.g.
The
.info
part oflocal1.info
above means that all messages that areINFO
or more important will be logged, includingINFO
,NOTICE
,ERR
(error),CRIT
(critical), etc., but notDEBUG
.Or, if you have
rsyslog
, you could try a property-based filter, e.g.The syslogtag should contain a ":".
Or, if you are planning on distributing your software to other people, it's probably not a good idea to rely on using
LOG_LOCAL
or anrsyslog
filter.In that case, you should use
LOG_USER
(if it's a normal program) orLOG_DAEMON
(if it's a server), write your startup messages and error messages usingsyslog
, but write all of your log messages to a file outside ofsyslog
. For example, Apache HTTPd logs to/var/log/apache2/*
or/var/log/httpd/*
, I assume using regularopen
/fopen
andwrite
/printf
calls.