How can I create a fuction with a macro for printing? - page 2

 

Here's a solution that utilizes templates. I wrapped it all into a single class. If you need more than 2 arguments, just expand the function templates. I don't know about the maximum number of arguments allowed by a template, but up to 10 should work.

//+------------------------------------------------------------------+
//| Log4mql simple                                                   |
//+------------------------------------------------------------------+
#define LOG(level) if(level<=L4m.Level()) L4m.ForLevel(level,__FUNCTION__,__FILE__,__LINE__).Log
#define ERROR LOG(0)
#define PRINT LOG(1)
#define DEBUG LOG(2)
//
class Log4mql
  {
   int               m_maxlevel;
   int               m_level;
   string            m_func;
   string            m_file;
   int               m_line;
public:
                     Log4mql(int level=0) : m_maxlevel(level) {}
   Log4mql           *ForLevel(int level,string func,string file,int line)
     {
      m_level=level;
      m_func=func;
      m_file=file;
      m_line=line;
      return &this;
     }
   int               Level() { return m_maxlevel; }
   void              SetLevel(int level) { m_maxlevel=level; }
   void              Log(string mesg)
     {
      if(m_level<=m_maxlevel)
         Print(m_func,"(",m_file,":",m_line,"): ",mesg);
     }
   template<typename T>
   void              Log(string format,T p) { Log(StringFormat(format,p)); }
   template<typename T1,typename T2>
   void              Log(string format,T1 p1,T2 p2) { Log(StringFormat(format,p1,p2)); }
  };

sinput int InpLogLevel=1; // Log Level (0=off,1=normal,2=debug)
Log4mql L4m(InpLogLevel);

void SomeFunction(double bid,double ask,double stoploss)
  {
   PRINT("bid=%f ask=%f",bid,ask); // 2021.01.09 05:25:32  log4mqlsimple EURUSD,M15: SomeFunction(log4mqlsimple.mq4:44): bid=1.221920 ask=1.222400
   DEBUG("sl=%f",stoploss);
   if(MathAbs(bid-stoploss)<10*_Point) ERROR("stoploss too tight");
   ...
  }

The deficiency of this solution is that it does not support an arbitrarily large amount of arguments, but that's fairly theoretic I guess, because you can expand the templates for as much as you need.

Note it works both for MQL4 and 5. I'm going to publish a cleaned up header with this class in the near future, if time allows.

Reason: