Bhargav Bhargav - 1 year ago 77
Linux Question

Custom logging for execution in DEBUG mode for C application on linux

I want to understand how to develop an application (Only C) on linux such that I can get log file(s) generated for it in debug mode execution.
Syslog is a daemon and the log messages logged to it by our application are mixed up with other messages. I want a custom log file though (just not the same log as system log but specific to this application and can be same file every time or a different one for every execution).

I am asking specifically for DEBUG mode to narrow down the question but ideally I want to implement3 modes of execution:LOG mode enabled(not debug), LOG mode disabled(not debug mode), DEBUG mode (log will be created in this mode by default).

Answer Source

There's no library interface for this, if that's what you're looking for.

Your app will need to open the log file itself, then you can define a set of functions to log as "error", "warn", "info", "debug", etc.

You'll also want to have some method to periodically roll your log files.

If you want to use size based rolling, you can use fprintf to print to the log, then capture the return value to get the number of bytes written. You can then add that value to a counter and see if you've reached your size threshold. If instead you want date based rolling, you can set the time of the next roll then check if the current time is after that time.

When you reach your criteria for rolling, you then close the current log file, rename that file (along with older files if need be), then open a new log file.

To keep a certain number of files, let's say n log files, first delete logfile.n, then rename logfile.n-1 to logfile.n, logfile.n-2 to logfile.n-1, etc. until you get to the most recent file which you rename from logfile to logfile.1.

For date based rolling, you only need to rename the most recent log file from logfile to logfile.YYYYMMDD if you want daily rolling, logfile.YYYYMMDD_HH if you want hourly rolling, and so forth.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download