Skip to content

Trace your logs in an output file

florianLopitaux edited this page May 17, 2023 · 4 revisions

Welcome in the CppLogger documentation !
In this section, we will see how to print logs in an output file.

Sample code using the feature

Here is a sample code that illustrates the use of this feature

#include "DebugLogger.h"

int main() {
  nsCppLogger::DebugLogger logger("./outFolder/myReportFile.txt", 1);

  logger.error(1, "Type of error", "This is the message that explain the error.");
  logger.warning(1, "This is the content of the warning message.");
  logger.inform(1, "This is the content of the information message.");

  return 0;
}

output file content
image of the output file content after the program execution


Code explanation

Preambule : All code of the CppLogger library is contained in the nsCppLogger namespace.

First of all, we include the DebugLogger.h header file that contains the DebugLogger class that we want to use.
This class represent the logger object that we going to use to print our logs.

Next, we instantiate a DebugLogger object.
The DebugLogger class has 2 constructors, one for the console mode and the second for the output file mode.
Here we use the second constructor to enable the output file mode. Here is its method signature :

DebugLogger(const std::string & logFilePath, const unsigned level = 0);

The first argument is the path of our output file.
Special case : if your give an empty string, the logger will activate the console mode.

The second argument is the level of debug which is by default equal to 0.

If you want to understand the system of debug level go to this section of the wiki.
But we advise you to watch how this feature works last and close your eyes for the moment.


Then, we can print our message in the output file using the different appropriate methods depending on the log context.
The 3 methods signature to print our log

void error(const unsigned logLevel, const std::string & typeError, const std::string & msg);
void warning(const unsigned logLevel, const std::string & msg);
void inform(const unsigned logLevel, const std::string & msg);