Commit c0428ba5 authored by Pavel Vainerman's avatar Pavel Vainerman

(DebugStram): добавил showMicroseconds(), showMilliseconds(),

переписал фунции print[Date,DateTime,Time] на использование std::put_time, а так же небольшой рефакторинг. Добавил вспомогательный класс IosFlagSaver.
parent 9f437a81
...@@ -198,11 +198,21 @@ class DebugStream : public std::ostream ...@@ -198,11 +198,21 @@ class DebugStream : public std::ostream
*/ */
std::ostream& operator()(Debug::type t) noexcept; std::ostream& operator()(Debug::type t) noexcept;
inline void showDateTime(bool s) inline void showDateTime(bool s) noexcept
{ {
show_datetime = s; show_datetime = s;
} }
inline void showMilliseconds( bool s ) noexcept
{
show_msec = s;
}
inline void showMicroseconds( bool s ) noexcept
{
show_usec = s;
}
inline void showLogType(bool s) noexcept inline void showLogType(bool s) noexcept
{ {
show_logtype = s; show_logtype = s;
...@@ -265,6 +275,29 @@ class DebugStream : public std::ostream ...@@ -265,6 +275,29 @@ class DebugStream : public std::ostream
return logname; return logname;
} }
// ------------------------------------------------------------------------------------------------
// RAII
// https://stackoverflow.com/questions/2273330/restore-the-state-of-stdcout-after-manipulating-it
class IosFlagSaver
{
public:
explicit IosFlagSaver(std::ostream& _ios):
ios(_ios),
f(_ios.flags()) {
}
~IosFlagSaver() {
ios.flags(f);
}
IosFlagSaver(const IosFlagSaver &rhs) = delete;
IosFlagSaver& operator= (const IosFlagSaver& rhs) = delete;
private:
std::ostream& ios;
std::ios::fmtflags f;
};
// ------------------------------------------------------------------------------------------------
protected: protected:
void sbuf_overflow( const std::string& s ) noexcept; void sbuf_overflow( const std::string& s ) noexcept;
...@@ -279,6 +312,8 @@ class DebugStream : public std::ostream ...@@ -279,6 +312,8 @@ class DebugStream : public std::ostream
debugstream_internal* internal = { 0 }; debugstream_internal* internal = { 0 };
bool show_datetime = { true }; bool show_datetime = { true };
bool show_logtype = { true }; bool show_logtype = { true };
bool show_msec = { false };
bool show_usec = { false };
std::string fname = { "" }; std::string fname = { "" };
StreamEvent_Signal s_stream; StreamEvent_Signal s_stream;
...@@ -286,5 +321,5 @@ class DebugStream : public std::ostream ...@@ -286,5 +321,5 @@ class DebugStream : public std::ostream
bool isWriteLogFile = { false }; bool isWriteLogFile = { false };
}; };
// ------------------------------------------------------------------------------------------------
#endif #endif
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
#include <iomanip> #include <iomanip>
#include "modbus/ModbusTypes.h" #include "modbus/ModbusTypes.h"
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "DebugStream.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
using namespace ModbusRTU; using namespace ModbusRTU;
using namespace std; using namespace std;
...@@ -208,19 +209,17 @@ bool ModbusRTU::isReadFunction( SlaveFunctionCode c ) ...@@ -208,19 +209,17 @@ bool ModbusRTU::isReadFunction( SlaveFunctionCode c )
std::ostream& ModbusRTU::mbPrintMessage( std::ostream& os, ModbusByte* m, size_t len ) std::ostream& ModbusRTU::mbPrintMessage( std::ostream& os, ModbusByte* m, size_t len )
{ {
// Чтобы не менять настройки 'os' DebugStream::IosFlagSaver ifs(os);
// сперва создаём свой поток вывода...
ostringstream s;
// << setiosflags(ios::showbase) // для вывода в формате 0xNN // << setiosflags(ios::showbase) // для вывода в формате 0xNN
s << hex << showbase << setfill('0'); // << showbase; os << hex << showbase << setfill('0'); // << showbase;
for( size_t i = 0; i < len; i++ ) for( size_t i = 0; i < len; i++ )
s << setw(2) << (short)(m[i]) << " "; os << setw(2) << (short)(m[i]) << " ";
// s << "<" << setw(2) << (int)(m[i]) << ">"; // s << "<" << setw(2) << (int)(m[i]) << ">";
return os << s.str(); return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& ModbusRTU::operator<<(std::ostream& os, const ModbusHeader& m ) std::ostream& ModbusRTU::operator<<(std::ostream& os, const ModbusHeader& m )
...@@ -2961,10 +2960,6 @@ std::string ModbusRTU::addr2str( const ModbusAddr addr ) ...@@ -2961,10 +2960,6 @@ std::string ModbusRTU::addr2str( const ModbusAddr addr )
ostringstream s; ostringstream s;
s << "0x" << hex << setfill('0') << setw(2) << (unsigned short)addr; s << "0x" << hex << setfill('0') << setw(2) << (unsigned short)addr;
return s.str(); return s.str();
// ostringstream s;
// s << hex << setfill('0') << showbase << (int)addr;
// return s.str();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::string ModbusRTU::b2str( const ModbusByte b ) std::string ModbusRTU::b2str( const ModbusByte b )
...@@ -3049,8 +3044,9 @@ SetDateTimeMessage::SetDateTimeMessage() ...@@ -3049,8 +3044,9 @@ SetDateTimeMessage::SetDateTimeMessage()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m ) std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m )
{ {
ostringstream s; DebugStream::IosFlagSaver ifs(os);
s << setfill('0')
os << setfill('0')
<< setw(2) << (int)m.day << "-" << setw(2) << (int)m.day << "-"
<< setw(2) << (int)m.mon << "-" << setw(2) << (int)m.mon << "-"
<< setw(2) << (int)m.century << setw(2) << (int)m.century
...@@ -3059,7 +3055,7 @@ std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m ) ...@@ -3059,7 +3055,7 @@ std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m )
<< setw(2) << (int)m.min << ":" << setw(2) << (int)m.min << ":"
<< setw(2) << (int)m.sec; << setw(2) << (int)m.sec;
return os << s.str(); return os;
} }
std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage* m ) std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage* m )
......
...@@ -30,7 +30,10 @@ ...@@ -30,7 +30,10 @@
#include <iomanip> #include <iomanip>
#include <time.h> #include <time.h>
#include <iomanip> #include <iomanip>
#include <ctime>
#include "DebugExtBuf.h" #include "DebugExtBuf.h"
#include "UniSetTypes.h"
using std::ostream; using std::ostream;
using std::streambuf; using std::streambuf;
...@@ -40,7 +43,6 @@ using std::stringbuf; ...@@ -40,7 +43,6 @@ using std::stringbuf;
using std::cerr; using std::cerr;
using std::ios; using std::ios;
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/// Constructor, sets the debug level to t. /// Constructor, sets the debug level to t.
DebugStream::DebugStream(Debug::type t) DebugStream::DebugStream(Debug::type t)
: /* ostream(new debugbuf(cerr.rdbuf())),*/ : /* ostream(new debugbuf(cerr.rdbuf())),*/
...@@ -97,6 +99,9 @@ const DebugStream& DebugStream::operator=( const DebugStream& r ) ...@@ -97,6 +99,9 @@ const DebugStream& DebugStream::operator=( const DebugStream& r )
dt = r.dt; dt = r.dt;
show_datetime = r.show_datetime; show_datetime = r.show_datetime;
show_logtype = r.show_logtype;
show_msec = r.show_msec;
show_usec = r.show_usec;
fname = r.fname; fname = r.fname;
if( !r.fname.empty() ) if( !r.fname.empty() )
...@@ -140,6 +145,8 @@ std::ostream& DebugStream::debug(Debug::type t) noexcept ...@@ -140,6 +145,8 @@ std::ostream& DebugStream::debug(Debug::type t) noexcept
{ {
if(dt & t) if(dt & t)
{ {
IosFlagSaver ifs(*this);
if( show_datetime ) if( show_datetime )
printDateTime(t); printDateTime(t);
...@@ -164,11 +171,12 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept ...@@ -164,11 +171,12 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
{ {
if(dt && t) if(dt && t)
{ {
time_t GMTime = time(NULL); std::time_t tv = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm* tms = localtime(&GMTime); std::tm tms = *std::localtime(&tv);
return *this << std::setw(2) << std::setfill('0') << tms->tm_mday << brk
<< std::setw(2) << std::setfill('0') << tms->tm_mon + 1 << brk std::ostringstream fmt;
<< std::setw(4) << std::setfill('0') << tms->tm_year + 1900; fmt << "%Od" << brk << "%Om" << brk << "%Y";
return *this << std::put_time(&tms,fmt.str().c_str());
} }
return nullstream; return nullstream;
...@@ -178,11 +186,21 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept ...@@ -178,11 +186,21 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
{ {
if(dt && t) if(dt && t)
{ {
time_t GMTime = time(NULL); IosFlagSaver ifs(*this);
struct tm* tms = localtime(&GMTime);
return *this << std::setw(2) << std::setfill('0') << tms->tm_hour << brk timespec tv = UniSetTypes::now_to_timespec(); // gettimeofday(tv,0);
<< std::setw(2) << std::setfill('0') << tms->tm_min << brk std::tm tms = *std::localtime(&tv.tv_sec);
<< std::setw(2) << std::setfill('0') << tms->tm_sec;
std::ostringstream fmt;
fmt << "%OH" << brk << "%OM" << brk << "%OS";
*this << std::put_time(&tms,fmt.str().c_str());
if( show_usec )
(*this) << "." << std::setw(6) << (tv.tv_nsec/1000);
else if( show_msec )
(*this) << "." << std::setw(3) << (tv.tv_nsec/1000000);
return *this;
} }
return nullstream; return nullstream;
...@@ -192,14 +210,18 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept ...@@ -192,14 +210,18 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
{ {
if(dt & t) if(dt & t)
{ {
time_t GMTime = time(NULL); IosFlagSaver ifs(*this);
struct tm* tms = localtime(&GMTime);
return *this << std::setw(2) << std::setfill('0') << tms->tm_mday << "/" timespec tv = UniSetTypes::now_to_timespec(); // gettimeofday(tv,0);
<< std::setw(2) << std::setfill('0') << tms->tm_mon + 1 << "/" std::tm tms = *std::localtime(&tv.tv_sec);
<< std::setw(4) << std::setfill('0') << tms->tm_year + 1900 << " " *this << std::put_time(&tms,"%Od/%Om/%Y %OH:%OM:%OS");
<< std::setw(2) << std::setfill('0') << tms->tm_hour << ":"
<< std::setw(2) << std::setfill('0') << tms->tm_min << ":" if( show_usec )
<< std::setw(2) << std::setfill('0') << tms->tm_sec; (*this) << "." << std::setw(6) << std::setfill('0') << (tv.tv_nsec/1000);
else if( show_msec )
(*this) << "." << std::setw(3) << std::setfill('0') << (tv.tv_nsec/1000000);
return *this;
} }
return nullstream; return nullstream;
......
...@@ -61,6 +61,8 @@ ostream& UniSetTypes::Configuration::help(ostream& os) ...@@ -61,6 +61,8 @@ ostream& UniSetTypes::Configuration::help(ostream& os)
print_help(os, 25, "--[debname]-logfile", "перенаправление лога в файл\n"); print_help(os, 25, "--[debname]-logfile", "перенаправление лога в файл\n");
print_help(os, 25, "--[debname]-add-levels", "добавить уровень вывода логов\n"); print_help(os, 25, "--[debname]-add-levels", "добавить уровень вывода логов\n");
print_help(os, 25, "--[debname]-del-levels", "удалить уровень вывода логов\n"); print_help(os, 25, "--[debname]-del-levels", "удалить уровень вывода логов\n");
print_help(os, 25, "--[debname]-show-microseconds", "Выводить время с микросекундами\n");
print_help(os, 25, "--[debname]-show-milliseconds", "Выводить время с миллисекундами\n");
print_help(os, 25, "--uniport num", "использовать заданный порт (переопеределяет 'defaultport' заданный в конф. файле в разделе <nodes>)\n"); print_help(os, 25, "--uniport num", "использовать заданный порт (переопеределяет 'defaultport' заданный в конф. файле в разделе <nodes>)\n");
print_help(os, 25, "--localIOR {1,0}", "использовать локальные файлы для получения IOR (т.е. не использовать omniNames). Переопределяет параметр в конфигурационном файле.\n"); print_help(os, 25, "--localIOR {1,0}", "использовать локальные файлы для получения IOR (т.е. не использовать omniNames). Переопределяет параметр в конфигурационном файле.\n");
print_help(os, 25, "--transientIOR {1,0}", "использовать генерируемые IOR(не постоянные). Переопределяет параметр в конфигурационном файле. Default=1\n"); print_help(os, 25, "--transientIOR {1,0}", "использовать генерируемые IOR(не постоянные). Переопределяет параметр в конфигурационном файле. Default=1\n");
...@@ -929,6 +931,8 @@ namespace UniSetTypes ...@@ -929,6 +931,8 @@ namespace UniSetTypes
string logfile("--" + debname + "-logfile"); string logfile("--" + debname + "-logfile");
string add_level("--" + debname + "-add-levels"); string add_level("--" + debname + "-add-levels");
string del_level("--" + debname + "-del-levels"); string del_level("--" + debname + "-del-levels");
string show_msec("--" + debname + "-show-milliseconds");
string show_usec("--" + debname + "-show-microseconds");
// смотрим командную строку // смотрим командную строку
for (int i = 1; i < (_argc - 1); i++) for (int i = 1; i < (_argc - 1); i++)
...@@ -945,6 +949,14 @@ namespace UniSetTypes ...@@ -945,6 +949,14 @@ namespace UniSetTypes
{ {
deb->delLevel(Debug::value(_argv[i + 1])); deb->delLevel(Debug::value(_argv[i + 1]));
} }
else if( show_usec == _argv[i] )
{
deb->showMicroseconds(true);
}
else if( show_msec == _argv[i] )
{
deb->showMilliseconds(true);
}
} }
if( !debug_file.empty() ) if( !debug_file.empty() )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment