[solved] Logging methods VSCode

Hello everyone,

Is there a default logging 'rule' for Arduino projects? In Java for example there are logging functions and regulation to debug code efficiently. There is also the possibility to define logging depths.

In my Arduino projects I usually use "Serial.print(xxx)" wherever I want. This is convenient for a few files, but a pain to uncomment everything when the project is done.

I wrote a simple "Logging" class. The print functions can be deactivated setting the "Debuglog=0". This method needs unnecessary memory and is in my opinion only a quick and dirty solution.

Is there a better way on excluding certain parts of the functions? Similar to

#if defined(DEBUGLOG)
// code
#endif

This is only allowed in header-files and yields no effect in functions (I tried).

My Testcode replaced the function "void Logger::log(char* c)". Also the variable "DEBUGLOG" would be in the "main.cpp" and can be commented/ uncommented if needed.

void Logger::log(char* c) {
  #if defined(DEBUGLOG)
     Serial.println(c);
  #endif
}

Logger.cpp (202 Bytes)

Logger.h (206 Bytes)

This is only allowed in header-files and yields no effect in functions (I tried).

How hard did you try ?

#define debug

void setup()
{
  Serial.begin(115200);
  while (!Serial);
#ifdef debug
  Serial.println("debugging is enabled");
#else
  Serial.println("debugging is not enabled");
#endif
}

void loop()
{
}

Then it is not an error in the syntax. This works when the code is in "main.cpp".

When I try calling it over my library it looks like:

#include <Arduino.h>

#define DEBUGLOG
#include <Loggger.h>

void setup() {
 Serial.begin(9600);
 Logger::log("test");
}

void loop() {}

With Logger.h

#ifndef logger_h
#define logger_h

#include <Arduino.h>

class Logger {

public:
    Logger();

    static void log(char* c);

};

#endif

and Logger.cpp

#include "Logger.h"

Logger::Logger() {    
}

static void Logger::log(char* c) {
    #ifdef DEBUGLOG
        Serial.println(c);
    #endif
}

Does the called "Logger.h" not detect the variable "DEBUGLOG"?

DEBUGLOG is not a variable

Try this sketch

#include <Arduino.h>

#include "Logger.h"
boolean DEBUGLOG = true;  //change to false to turn off debug prints

void setup()
{
  Serial.begin(115200);
  Logger::log("test");
}

void loop() {}

this .h file

#ifndef logger_h
#define logger_h
#include <Arduino.h>

extern bool DEBUGLOG;  //note the extern specifier

class Logger
{

  public:
    Logger::Logger();
    static void Logger::log(char* c);

};

#endif

and this .cpp file

#include "Logger.h"

Logger::Logger()
{
}

static void Logger::log(char* c)
{
  if (DEBUGLOG)
    Serial.println(c);
}

Note the use of the extern specifier in the .h file

My old nemesis: correct definitions

Your code works! Setting the variable to "False" excludes the code from compiling and reduces memory.

Thank you

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.