C Program | Log with File Name and Line Number

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.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
2
2
0