Eclipse SUMO - Simulation of Urban MObility
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
MsgHandler.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2025 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
20// Retrieves messages about the process and gives them further to output
21/****************************************************************************/
22#include <config.h>
23
24#include <string>
25#include <cassert>
26#include <vector>
27#include <algorithm>
28#include <iostream>
29#include <chrono>
30#ifdef WIN32
31#define NOMINMAX
32#include <windows.h>
33#undef NOMINMAX
34#else
35#include <unistd.h>
36#endif
40#include "MsgHandler.h"
41
42
43// ===========================================================================
44// static member variables
45// ===========================================================================
55std::string MsgHandler::myErrorPrefix = "Error: ";
56std::string MsgHandler::myWarningPrefix = "Warning: ";
57
58
59// ===========================================================================
60// method definitions
61// ===========================================================================
62
74
75
87
88
96
97
98void
100 myWriteDebugMessages = enable;
101}
102
103void
107
108
109std::string
110MsgHandler::insertLineBreaks(std::string msg, int lineWidth) {
111 // TODO: check what FXFont::getTextWidth can do
112 //int textWidth = getApp()->getNormalFont()->getTextWidth
113 if ((int)msg.size() <= lineWidth) {
114 return msg;
115 }
116 size_t pos = 0;
117 size_t nextLineBreak = msg.find('\n');
118 size_t spaceAfterLine = msg.find(' ', lineWidth);
119 while (spaceAfterLine != std::string::npos) {
120 if (nextLineBreak == std::string::npos || nextLineBreak > spaceAfterLine) {
121 msg = msg.replace(spaceAfterLine, 1, "\n");
122 pos = spaceAfterLine + 1;
123 } else {
124 pos = nextLineBreak + 1;
125 }
126 spaceAfterLine = msg.find(' ', pos + lineWidth);
127 nextLineBreak = msg.find('\n', pos);
128 }
129 return msg;
130}
131
132
133void
134MsgHandler::inform(std::string msg, bool addType) {
135 if (addType && !myInitialMessages.empty() && myInitialMessages.size() < 5) {
136 myInitialMessages.push_back(msg);
137 }
138 // beautify progress output
140 myAmProcessingProcess = false;
142 }
143 msg = build(msg, addType);
144 // inform all receivers
145 for (auto i : myRetrievers) {
146 i->inform(msg);
147 }
148 // set the information that something occurred
149 myWasInformed = true;
150}
151
152
153void
154MsgHandler::beginProcessMsg(std::string msg, bool addType) {
155 msg = build(msg, addType);
156 // inform all other receivers
157 for (auto i : myRetrievers) {
158 i->inform(msg, true);
160 }
161 // set the information that something occurred
162 myWasInformed = true;
163}
164
165
166void
167MsgHandler::endProcessMsg2(bool success, long duration) {
168 if (success) {
169 if (duration > -1) {
170 endProcessMsg(TLF(" done (%ms).", toString(duration)));
171 } else {
172 endProcessMsg(TL(" done."));
173 }
174 } else {
175 endProcessMsg(TL(" failed."));
176 }
177}
178
179
180void
182 // inform all other receivers
183 for (auto i : myRetrievers) {
184 i->inform(msg);
185 }
186 // set the information that something occurred
187 myWasInformed = true;
188 myAmProcessingProcess = false;
189}
190
191
192void
193MsgHandler::clear(bool resetInformed) {
194 if (myAggregationThreshold >= 0) {
195 for (const auto& i : myAggregationCount) {
196 if (i.second > myAggregationThreshold) {
197 inform(toString(i.second) + " total messages of type: " + i.first);
198 }
199 }
200 }
201 myAggregationCount.clear();
202 if (!resetInformed && myInitialMessages.size() > 1) {
203 const bool wasInformed = myWasInformed;
204 for (const std::string& msg : myInitialMessages) {
205 inform(msg, false);
206 }
207 myInitialMessages.clear();
209 }
210 if (resetInformed) {
211 myWasInformed = false;
212 }
213}
214
215
216void
218 if (!isRetriever(retriever)) {
219 myRetrievers.push_back(retriever);
220 }
221}
222
223
224void
226 std::vector<OutputDevice*>::iterator i = find(myRetrievers.begin(), myRetrievers.end(), retriever);
227 if (i != myRetrievers.end()) {
228 myRetrievers.erase(i);
229 }
230}
231
232
233bool
235 return std::find(myRetrievers.begin(), myRetrievers.end(), retriever) != myRetrievers.end();
236}
237
238
239void
241 if (myErrorInstance != nullptr) {
243 }
244 if (myWarningInstance != nullptr) {
246 }
247 if (myMessageInstance != nullptr) {
249 }
250}
251
252
253void
254MsgHandler::setupI18n(const std::string& locale) {
255#ifdef HAVE_INTL
256 if (locale != "") {
257#ifdef WIN32
258 _putenv_s("LANGUAGE", locale.data());
259#else
260 setenv("LANGUAGE", locale.data(), true);
261#endif
262 }
263 if (!setlocale(LC_MESSAGES, "")) {
264 WRITE_WARNINGF(TL("Could not set locale to '%'."), locale);
265 }
266 const char* sumoPath = getenv("SUMO_HOME");
267 if (sumoPath == nullptr) {
268 if (!bindtextdomain("sumo", nullptr)) {
269 WRITE_WARNING(TL("Environment variable SUMO_HOME is not set, could not find localized messages."));
270 return;
271 }
272 } else {
273 const std::string path = sumoPath + std::string("/data/locale/");
274 if (!bindtextdomain("sumo", path.data())) {
275 WRITE_WARNING(TL("Could not find localized messages."));
276 return;
277 }
278 }
279 bind_textdomain_codeset("sumo", "UTF-8");
280 textdomain("sumo");
281#else
282 UNUSED_PARAMETER(locale);
283#endif
284 myWarningPrefix = TL("Warning: ");
285 myErrorPrefix = TL("Error: ");
286}
287
288
289void
291 // initialize console properly
292 OutputDevice::getDevice("stdout");
293 OutputDevice::getDevice("stderr");
295 getWarningInstance()->setAggregationThreshold(oc.getInt("aggregate-warnings"));
296 getErrorInstance()->setAggregationThreshold(oc.getInt("aggregate-warnings"));
297 if (oc.getBool("no-warnings")) {
299 }
300 // build the logger if possible
301 if (oc.isSet("log", false)) {
302 OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("log"));
303 getErrorInstance()->addRetriever(logFile);
304 if (!oc.getBool("no-warnings")) {
306 }
308 if (oc.getBool("log.timestamps")) {
309 myWriteTimestamps = true;
310 }
311 if (oc.getBool("log.processid")) {
312 myWriteProcessId = true;
313 }
314 }
315 if (oc.isSet("message-log", false)) {
316 OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("message-log"));
318 }
319 if (oc.isSet("error-log", false)) {
320 OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("error-log"));
321 getErrorInstance()->addRetriever(logFile);
323 }
324 if (oc.getBool("verbose")) {
325 getErrorInstance()->myInitialMessages.push_back("Repeating initial error messages:");
326 } else {
328 }
329}
330
331
332void
334 delete myMessageInstance;
335 myMessageInstance = nullptr;
336 delete myWarningInstance;
337 myWarningInstance = nullptr;
338 delete myErrorInstance;
339 myErrorInstance = nullptr;
340}
341
342
343std::string
345 std::stringstream prefix;
346 const std::chrono::system_clock::time_point now_timestamp = std::chrono::system_clock::now();
347 const auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now_timestamp.time_since_epoch()) % 1000;
348 const std::time_t now_time_t = std::chrono::system_clock::to_time_t(now_timestamp);
349
350 char timeString[21];
351 std::strftime(timeString, 21, "[%F %T", std::localtime(&now_time_t));
352 prefix << timeString << '.' << std::setfill('0') << std::setw(3) << milliseconds.count() << "] ";
353 return prefix.str();
354}
355
356
357std::string
359 std::stringstream prefix;
360 prefix << "[PID: ";
361#ifdef WIN32
362 prefix << GetCurrentProcessId();
363#else
364 prefix << getpid();
365#endif
366 prefix << "] ";
367 return prefix.str();
368}
369
370
372 myType(type), myWasInformed(false), myAggregationThreshold(-1) {
373 if (type == MsgType::MT_MESSAGE) {
375 } else {
377 }
378}
379
380
383
384
385bool
387 return myWasInformed;
388}
389
390
391/****************************************************************************/
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:288
#define WRITE_WARNING(msg)
Definition MsgHandler.h:287
#define TL(string)
Definition MsgHandler.h:305
#define TLF(string,...)
Definition MsgHandler.h:307
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:46
virtual void addRetriever(OutputDevice *retriever)
Adds a further retriever to the instance responsible for a certain msg type.
std::vector< std::string > myInitialMessages
storage for initial messages
Definition MsgHandler.h:252
bool wasInformed() const
Returns the information whether any messages were added.
std::string buildProcessIdPrefix(void) const
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
virtual void inform(std::string msg, bool addType=true)
adds a new error to the list
std::string buildTimestampPrefix(void) const
static void enableDebugGLMessages(bool enable)
enable/disable gl-debug messages
static std::string insertLineBreaks(std::string msg, int lineWidth)
reformats a long string to contain newline after a certain line length in px (depending on the curren...
virtual void endProcessMsg(std::string msg)
Ends a process information.
std::string build(const std::string &msg, bool addType)
Builds the string which includes the mml-message type.
Definition MsgHandler.h:178
static Factory myFactory
The function to call for new MsgHandlers, nullptr means use default constructor.
Definition MsgHandler.h:221
bool myWasInformed
information whether an output occurred at all
Definition MsgHandler.h:240
static bool myWriteTimestamps
Whether to prefix every message with a time stamp.
Definition MsgHandler.h:264
static void setupI18n(const std::string &locale="")
set up gettext stuff
static void initOutputOptions()
init output options
static MsgHandler * myErrorInstance
The instance to handle errors.
Definition MsgHandler.h:224
static MsgHandler * myMessageInstance
The instance to handle normal messages.
Definition MsgHandler.h:230
bool isRetriever(OutputDevice *retriever) const
Returns whether the given output device retrieves messages from the handler.
static MsgHandler * getWarningInstance()
Returns the instance to add warnings to.
std::map< const std::string, int > myAggregationCount
count for messages of the same type
Definition MsgHandler.h:246
static void enableDebugMessages(bool enable)
enable/disable debug messages
static bool myAmProcessingProcess
Information whether a process information is printed to cout.
Definition MsgHandler.h:233
std::vector< OutputDevice * > myRetrievers
The list of retrievers that shall be informed about new messages or errors.
Definition MsgHandler.h:249
MsgHandler *(* Factory)(MsgType)
Definition MsgHandler.h:60
virtual ~MsgHandler()
destructor
virtual void clear(bool resetInformed=true)
Clears information whether an error occurred previously and print aggregated message summary.
void setAggregationThreshold(const int thresh)
Definition MsgHandler.h:164
static MsgHandler * myWarningInstance
The instance to handle warnings.
Definition MsgHandler.h:227
virtual void endProcessMsg2(bool success, long duration=-1)
Ends a process information with predefined messages.
virtual void beginProcessMsg(std::string msg, bool addType=true)
Begins a process information.
static bool myWriteDebugMessages
Flag to enable or disable debug output.
Definition MsgHandler.h:258
static bool myWriteDebugGLMessages
Flag to enable or disable GL specific debug output.
Definition MsgHandler.h:261
static std::string myWarningPrefix
The possibly translated warning prefix (mainly for speedup)
Definition MsgHandler.h:273
static bool myWriteProcessId
Whether to prefix every message with the process id.
Definition MsgHandler.h:267
static void cleanupOnEnd()
Removes pending handler.
static std::string myErrorPrefix
The possibly translated error prefix (mainly for speedup)
Definition MsgHandler.h:270
static void removeRetrieverFromAllInstances(OutputDevice *out)
ensure that that given output device is no longer used as retriever by any instance
virtual void removeRetriever(OutputDevice *retriever)
Removes the retriever from the handler.
int myAggregationThreshold
do not output more messages of the same type if the count exceeds this threshold
Definition MsgHandler.h:243
@ MT_MESSAGE
The message is only something to show.
@ MT_ERROR
The message is an error.
@ MT_WARNING
The message is a warning.
MsgHandler(MsgType type)
standard constructor
static MsgHandler * getMessageInstance()
Returns the instance to add normal messages to.
A storage for options typed value containers)
Definition OptionsCont.h:89
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
static OptionsCont & getOptions()
Retrieves the options.
Static storage of an output device and its base (abstract) implementation.
static OutputDevice & getDevice(const std::string &name, bool usePrefix=true)
Returns the described OutputDevice.
#define UNUSED_PARAMETER(x)