Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program | Log with File Name and Line Number

$
0
0

Logging is an essential part of programming. Logging helps tracking various events, errors, troubleshooting. It helps the developers to great extent troubleshooting a problem if the file name and line number are also added with the log messages.

In this article, we discussed how we can add file name and line number with a message. We can add __FILE__ and __LINE__ in every message. It is a bit cumbersome and error prone also.

But we can think of a function that will print the input message along with the file name and line number. Here the problem is that the file name or line number will be of the logging function – not of the message we want to log.

But we can help of macros.

#include <stdio.h>

#define LOG_MSG(msg) { \
  printf("%s [%s:%d]\n", msg, __FILE__, __LINE__); \
}

This macro, LOG_MSG, prints the input message along with the file name and line number. It will get expanded in the place of usage. So, it will print the information of the file where it will be used.

I intentionally wrote this macro in a separate file. log.h. If I use this macro from another file (test.c), the file name and line number will be of the test.c file.

#include "log.h"

int main(){
  LOG_MSG ("log message 1.");
  LOG_MSG ("log message 2.");
}
$ cc test.c -o test
$ ./test
log message 1. [test.c:4]
log message 2. [test.c:5]

This output clearly shows that the macro, LOG_MSG, adds the file name and line number of the test.c file.

The post C Program | Log with File Name and Line Number appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>