9 #ifndef Sawyer_Message_H
10 #define Sawyer_Message_H
12 #include <Sawyer/Map.h>
13 #include <Sawyer/Optional.h>
14 #include <Sawyer/Sawyer.h>
15 #include <Sawyer/SharedPointer.h>
16 #include <Sawyer/Synchronization.h>
18 #include <boost/config.hpp>
19 #include <boost/logic/tribool.hpp>
20 #include <boost/regex.hpp>
288 #if defined(DEBUG) || defined(TRACE) || defined(WHERE) || defined(MARCH) || \
289 defined(INFO) || defined(WARN) || defined(ERROR) || defined(FATAL)
291 # pragma message("Undefining common words from the global namespace: DEBUG, TRACE, WHERE, MARCH, INFO, WARN, ERROR, FATAL")
293 # warning "Undefining common words from the global namespace: DEBUG, TRACE, WHERE, MARCH, INFO, WARN, ERROR, FATAL"
363 SAWYER_EXPORT
double now();
364 SAWYER_EXPORT std::string
escape(
const std::string&);
377 #include <Sawyer/WarningsOff.h>
379 #include <Sawyer/WarningsRestore.h>
427 #include <Sawyer/WarningsOff.h>
436 #include <Sawyer/WarningsRestore.h>
446 void print(std::ostream&)
const;
450 SAWYER_EXPORT std::ostream&
operator<<(std::ostream &o,
const MesgProps &props);
514 static unsigned nextId_;
516 #include <Sawyer/WarningsOff.h>
518 #include <Sawyer/WarningsRestore.h>
526 : id_(nextId_++), isComplete_(false), isCanceled_(false) {}
530 : id_(nextId_++), isComplete_(false), isCanceled_(false) {
537 : id_(nextId_++), isComplete_(false), isCanceled_(false), props_(props) {}
540 explicit Mesg(
const std::string &mesg)
541 : id_(nextId_++), text_(mesg), isComplete_(true), isCanceled_(false) {}
546 : id_(nextId_++), text_(mesg), isComplete_(true), isCanceled_(false) {
553 : id_(nextId_++), text_(mesg), isComplete_(true), isCanceled_(false), props_(props) {}
556 unsigned id()
const {
return id_; }
559 const std::string&
text()
const {
return text_; }
570 bool isEmpty()
const {
return text_.empty(); }
574 bool hasText()
const;
594 void insert(
const std::string&);
599 void post(
const BakedDestinations&)
const;
611 mutable SAWYER_THREAD_TRAITS::RecursiveMutex
mutex_;
650 virtual void bakeDestinations(
const MesgProps&, BakedDestinations &baked);
654 virtual void post(
const Mesg&,
const MesgProps &bakedProperties) = 0;
670 typedef std::list<DestinationPtr> Destinations;
671 #include <Sawyer/WarningsOff.h>
672 Destinations destinations_;
673 #include <Sawyer/WarningsRestore.h>
681 virtual void bakeDestinations(
const MesgProps&, BakedDestinations&) ;
692 MultiplexerPtr addDestination(
const DestinationPtr&);
699 MultiplexerPtr removeDestination(
const DestinationPtr&);
708 MultiplexerPtr to(
const DestinationPtr&);
709 MultiplexerPtr to(
const DestinationPtr&,
const DestinationPtr&);
710 MultiplexerPtr to(
const DestinationPtr&,
const DestinationPtr&,
const DestinationPtr&);
711 MultiplexerPtr to(
const DestinationPtr&,
const DestinationPtr&,
const DestinationPtr&,
const DestinationPtr&);
728 virtual void bakeDestinations(
const MesgProps&, BakedDestinations&) ;
738 virtual bool shouldForward(
const MesgProps&) = 0;
743 virtual void forwarded(
const MesgProps&) = 0;
758 : nSkip_(nskip), rate_(rate), limit_(limit), nPosted_(0) {}
765 static SequenceFilterPtr
instance(
size_t nskip,
size_t rate,
size_t limit) {
776 size_t nSkip()
const;
777 SequenceFilterPtr nSkip(
size_t n);
789 SequenceFilterPtr rate(
size_t n);
800 size_t limit()
const;
801 SequenceFilterPtr limit(
size_t n);
809 size_t nPosted()
const;
811 virtual bool shouldForward(
const MesgProps&) ;
820 double initialDelay_;
822 double prevMessageTime_;
823 double lastBakeTime_;
830 : initialDelay_(0.0), minInterval_(minInterval), prevMessageTime_(0.0), lastBakeTime_(0.0) {}
835 static TimeFilterPtr
instance(
double minInterval) {
847 double minInterval()
const;
848 TimeFilterPtr minInterval(
double d);
858 double initialDelay()
const;
859 TimeFilterPtr initialDelay(
double d);
867 size_t nPosted()
const;
869 virtual bool shouldForward(
const MesgProps&) ;
870 virtual void forwarded(
const MesgProps&) ;
887 memset(enabled_, dflt?0xff:0,
sizeof enabled_);
906 ImportanceFilterPtr enabled(
Importance imp,
bool b);
919 virtual bool shouldForward(
const MesgProps&) ;
936 mutable SAWYER_THREAD_TRAITS::RecursiveMutex mutex_;
942 SAWYER_THREAD_TRAITS::RecursiveMutex&
mutex()
const {
return mutex_; }
948 size_t ntext()
const;
966 static GangMap *gangs_;
967 static const int TTY_GANG = -1;
968 static const int NO_GANG_ID = -2;
969 static SAWYER_THREAD_TRAITS::Mutex classMutex_;
978 static GangPtr createNS(
int id);
987 #include <Sawyer/WarningsOff.h>
996 mutable SAWYER_THREAD_TRAITS::RecursiveMutex mutex_;
999 bool showProgramName_;
1002 bool showElapsedTime_;
1003 When showFacilityName_;
1004 bool showImportance_;
1005 void initFromSystem();
1006 #include <Sawyer/WarningsRestore.h>
1012 : showProgramName_(true), showThreadId_(true), showElapsedTime_(true), showFacilityName_(SOMETIMES),
1013 showImportance_(true) {
1029 static PrefixPtr silentInstance();
1053 PrefixPtr
programName(
const std::string &s) { programName_ = s;
return sharedFromThis(); }
1061 void setProgramName();
1083 PrefixPtr
showThreadId(
bool b) { showThreadId_ = b;
return sharedFromThis(); }
1096 PrefixPtr startTime(
double t);
1107 void setStartTime();
1149 virtual std::string toString(
const Mesg&,
const MesgProps&)
const;
1160 #include <Sawyer/WarningsOff.h>
1163 #include <Sawyer/WarningsRestore.h>
1166 bool partialMessagesAllowed_;
1188 GangPtr gang()
const;
1189 UnformattedSinkPtr gang(
const GangPtr &g);
1218 bool partialMessagesAllowed()
const;
1219 UnformattedSinkPtr partialMessagesAllowed(
bool);
1230 PrefixPtr prefix()
const;
1231 UnformattedSinkPtr prefix(
const PrefixPtr &p);
1241 virtual std::string maybeTerminatePrior(
const Mesg&,
const MesgProps&);
1250 virtual std::string maybePrefix(
const Mesg&,
const MesgProps&);
1260 virtual std::string maybeBody(
const Mesg&,
const MesgProps&);
1270 virtual std::string maybeFinal(
const Mesg&,
const MesgProps&);
1284 void gangInternal(
const GangPtr &g);
1325 std::ostream &stream_;
1338 #ifndef BOOST_WINDOWS
1345 SyslogSink(
const char *ident,
int option,
int facility);
1350 static SyslogSinkPtr
instance(
const char *ident,
int option,
int facility) {
1377 SProxy(): stream_(NULL) {}
1383 Stream& operator*() {
return *stream_; }
1384 Stream* operator->() {
return stream_; }
1385 Stream*
get()
const {
return stream_; }
1386 operator bool()
const;
1396 class SAWYER_EXPORT
Stream:
public std::ostream {
1397 friend class StreamBuf;
1398 mutable SAWYER_THREAD_TRAITS::Mutex mutex_;
1400 StreamBuf *streambuf_;
1404 Stream(
const std::string facilityName,
Importance imp,
const DestinationPtr &destination);
1433 Stream(
const std::ostream &other_);
1445 Stream& operator=(
const std::ostream &other_);
1450 void incrementRefCount();
1451 size_t decrementRefCount();
1465 void initFromNS(
const Stream &other);
1471 bool enabled()
const;
1506 operator void*()
const {
1507 return enabled() ?
const_cast<Stream*
>(
this) : NULL;
1509 #if __cplusplus >= 201103L
1510 explicit operator bool()
const {
1515 operator bool()
const {
1525 #define SAWYER_MESG(message_stream) (message_stream) && (message_stream)
1526 #define SAWYER_MSG(message_stream) (message_stream) && (message_stream)
1528 #define SAWYER_MESG_FIRST(...) Sawyer::Message::firstEnabled(__VA_ARGS__) && Sawyer::Message::firstEnabled(__VA_ARGS__)
1529 #define SAWYER_MESG_OR(s1, s2) SAWYER_MESG_FIRST(s1, s2)
1530 #define SAWYER_MSG_OR(s1, s2) SAWYER_MESG_FIRST(s1, s2)
1540 void enable(
bool b=
true);
1553 void completionString(
const std::string &s,
bool asDefault=
true);
1554 void interruptionString(
const std::string &s,
bool asDefault=
true);
1555 void cancelationString(
const std::string &s,
bool asDefault=
true);
1556 void facilityName(
const std::string &s,
bool asDefault=
true);
1566 DestinationPtr destination()
const;
1567 Stream& destination(
const DestinationPtr &d);
1579 SAWYER_EXPORT Stream& firstEnabled(Stream &s1);
1580 SAWYER_EXPORT Stream& firstEnabled(Stream &s1, Stream &s2);
1581 SAWYER_EXPORT Stream& firstEnabled(Stream &s1, Stream &s2, Stream &s3);
1582 SAWYER_EXPORT Stream& firstEnabled(Stream &s1, Stream &s2, Stream &s3, Stream &s4);
1583 SAWYER_EXPORT Stream& firstEnabled(Stream &s1, Stream &s2, Stream &s3, Stream &s4, Stream &s5);
1607 static const unsigned CONSTRUCTED_MAGIC = 0x73617779;
1608 unsigned constructed_;
1609 mutable SAWYER_THREAD_TRAITS::Mutex mutex_;
1610 #include <Sawyer/WarningsOff.h>
1611 std::string name_, comment_;
1612 std::vector<SProxy> streams_;
1613 #include <Sawyer/WarningsRestore.h>
1633 Facility(
const std::string &name,
const DestinationPtr &destination): constructed_(CONSTRUCTED_MAGIC), name_(name) {
1634 initStreams(destination);
1644 Facility& initialize(
const std::string &name);
1647 Facility& initialize(
const std::string &name,
const DestinationPtr &destination);
1681 static bool isValidName(
const std::string&);
1688 std::string name()
const;
1698 std::string comment()
const;
1699 Facility& comment(
const std::string&);
1708 Facility& renameStreams(
const std::string &name =
"");
1716 Facility& initStreams(
const DestinationPtr&);
1720 static std::vector<std::string> parseName(
const std::string&);
1741 mutable SAWYER_THREAD_TRAITS::Mutex mutex_;
1742 #include <Sawyer/WarningsOff.h>
1743 FacilityMap facilities_;
1744 ImportanceSet impset_;
1745 bool impsetInitialized_;
1746 #include <Sawyer/WarningsRestore.h>
1754 impset_.insert(
WARN);
1755 impset_.insert(
ERROR);
1756 impset_.insert(
FATAL);
1757 impsetInitialized_ =
false;
1771 ImportanceSet impset()
const;
1824 Facility& facility(
const std::string &name)
const;
1829 std::vector<std::string> facilityNames()
const;
1868 std::string control(
const std::string &s);
1873 std::string configuration()
const;
1912 Facilities& enable(
const std::string &switch_name,
bool b=
true);
1938 void print(std::ostream&)
const;
1942 struct ControlTerm {
1943 ControlTerm(
const boost::regex &facilityNamePattern,
bool enable)
1944 : facilityNamePattern(facilityNamePattern), lo(
DEBUG), hi(
DEBUG), enable(enable) {}
1945 std::string toString()
const;
1946 boost::regex facilityNamePattern;
1951 Facilities& insertNS(Facility&, std::string);
1955 struct ControlError {
1956 ControlError(
const std::string &mesg,
const char *position): mesg(mesg), inputPosition(position) {}
1958 const char *inputPosition;
1962 static boost::regex parseFacilityNamePattern(
const char* &input);
1963 static std::string parseEnablement(
const char* &input);
1964 static std::string parseRelation(
const char* &input);
1965 static std::string parseImportanceName(
const char* &input);
1966 static Importance importanceFromString(
const std::string&);
1967 static std::list<ControlTerm> parseImportanceList(
const boost::regex &facilityNamePattern,
const char* &input,
bool isGlobal);
1970 void eraseDestroyedNS();
1973 std::vector<Facility*> matchingFacilitiesNS(
const boost::regex &namePattern)
const;
1981 SAWYER_EXPORT
extern DestinationPtr
merr;
1984 SAWYER_EXPORT
extern Facility
mlog;
2027 : facilities_(mfacilities) {
2033 : facilities_(facilities) {
PrefixPtr showImportance(bool b)
Property: whether to show the importance property.
static TimeFilterPtr instance(double minInterval)
Allocating constructor.
Facilities()
Constructs an empty container of Facility objects.
std::string stringifyColor(AnsiColor)
Convert an AnsiColor enum to a string.
size_t ntext() const
Zero if !isValid().
static GangPtr instanceForId(int id)
The gang for the specified ID, creating a new one if necessary.
Messages intended to be useful primarily to the author of the code.
ImportanceFilter(bool dflt)
Constructor for derived classes.
static MultiplexerPtr instance()
Allocating constructor.
ANSI Color specification for text written to a terminal.
ColorSpec(AnsiColor fg)
Constructs an object that specifies only a foreground color.
void emitted(const Mesg &, const MesgProps &)
Make specified message the high water mark.
static StreamSinkPtr instance(std::ostream &stream, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
FacilitiesGuard(Facilities &facilities)
Saves and restores specified message facilities.
MesgProps & properties()
Returns a reference to message properties.
boost::tribool bold
Use ANSI "bold" attribute?
FdSink(int fd, const PrefixPtr &prefix)
Constructor for derived classes.
bool showImportance() const
Property: whether to show the importance property.
Send free-format messages to a Unix file descriptor.
const MesgProps & defaultPropertiesNS() const
Default values for message properties.
bool isCanceled() const
Returns true if the message has entered the canceled state.
boost::tribool isBuffered
Whether the output buffered and emitted on a per-message basis.
Optional< Importance > importance
The message importance level.
~FacilitiesGuard()
Restores previously saved facility settings.
Facility()
Construct an empty facility.
bool isDefault() const
Returns true if this object is in its default-constructed state.
std::vector< BakedDestination > BakedDestinations
Baked properties for multiple destinations.
Mesg(const MesgProps &props)
Creates a new, partial message that is empty.
Optional< std::string > interruptionStr
String to append when a partial message is interrupted.
MesgProps overrides_
Override properties applied to incoming message.
bool isValid() const
Returns true if high water is defined.
Collection of facilities.
SharedPointer< class Filter > FilterPtr
Smart pointer.
Mesg(const std::string &mesg)
Creates a new, completed message with the specified text.
bool isTerminal(int fd)
True if fd is a tty.
Error messages that indicate an abnormal situation from which the program was able to at least partia...
SharedPointer< class FileSink > FileSinkPtr
Smart pointer.
PrefixPtr showThreadId(bool b)
Property: whether to show the thread ID in the message prefix area.
Mesg(const std::string &facilityName, Importance imp)
Creates a new, partial message that is empty.
std::set< Importance > ImportanceSet
A set of importance levels.
FacilitiesGuard()
Saves and restores the global message facilities.
std::pair< DestinationPtr, MesgProps > BakedDestination
Baked properties for a destination.
bool isComplete() const
Returns true if the message has entered the completed state.
void clear()
Reset to initial state.
Base class for internal nodes that filter messages.
Facility mlog
Facility used by Sawyer components.
Information printed at the beginning of each free-format message.
TimeFilter(double minInterval)
Constructor for derived classes.
unsigned id() const
Exception unless isValid().
const ColorSpec & operator[](Importance imp) const
Colors for a message.
ColorSet & colorSet()
Property: colors to use for the prefix if coloring is enabled.
ColorSpec & operator[](Importance imp)
Colors for a message.
Messages that indicate an abnormal situation from which the program was unable to recover...
ColorSpec()
Constructs an object with default foreground and background colors.
bool isEmpty() const
Returns true if the message has no text.
Filters messages based on importance level.
const std::string & text() const
Return the message text.
Mesg()
Creates a new, partial message that is empty.
Stream & operator[](Importance imp)
Returns a stream for the specified importance level.
SharedPointer< class ImportanceFilter > ImportanceFilterPtr
Smart pointer.
Reference-counting intrusive smart pointer.
When showFacilityName() const
Property: whether to show the facilityName property.
Name space for the entire library.
boost::tribool useColor
Whether to use ANSI escape sequences to colorize output.
SharedPointer< class Prefix > PrefixPtr
Smart pointer.
static ImportanceFilterPtr instance(bool dflt)
Allocating constructor.
Filter()
Constructor for derived classes.
SharedPointer< class SyslogSink > SyslogSinkPtr
Smart pointer.
static ColorSet fullColor()
Returns a color set that uses various foreground colors for the different message importance levels...
Saves and restores facilities.
AnsiColor
Colors used by sinks that write to terminals.
Sawyer::SynchronizationTraits< Sawyer::SingleThreadedTag >::RecursiveMutex mutex_
Mutex protecting data members here and in subclasses.
PrefixPtr programName(const std::string &s)
Property: program name.
When
When to show something.
SharedPointer< class Destination > DestinationPtr
Smart pointer.
virtual void forwarded(const MesgProps &)
Called once by bakeDestinations if shouldForward() returned true.
static SyslogSinkPtr instance(const char *ident, int option, int facility)
Allocating constructor.
bool isConstructed() const
Returns true if called on an object that has been constructed.
Progress reports and other similar rapidly updating partial messages.
Sends messages to the syslog daemon.
unsigned id() const
Return unique message ID.
PrefixPtr showElapsedTime(bool b)
Property: whether to show time deltas.
Sends incoming messages to multiple destinations.
Optional< std::string > lineTermination
Line termination for completion, interruption, and cancelation.
Facilities mfacilities
Library-provided facility group.
Multiplexer()
Constructor for derived classes.
void cancel()
Cause the message to enter the canceled state.
SharedPointer< class SequenceFilter > SequenceFilterPtr
Smart pointer.
MesgProps & defaultPropertiesNS()
Default values for message properties.
Colors to use for each message importance.
bool showElapsedTime() const
Property: whether to show time deltas.
Creates SharedPointer from this.
static void shutdownNS()
Reset to initial state to free memory.
Mesg(const std::string &facilityName, Importance imp, const std::string &mesg)
Creates a new, completed message with the specified text.
const Optional< std::string > & programName() const
Property: program name.
Send free-format messages to a C FILE pointer.
void disable()
Enable or disable a stream.
SharedPointer< class Gang > GangPtr
Smart pointer.
const ColorSet & colorSet() const
Property: colors to use for the prefix if coloring is enabled.
SharedPointer< class TimeFilter > TimeFilterPtr
Smart pointer.
Facilities & disable(const std::string &switch_name)
Enable/disable a facility by name.
bool showProgramName() const
Property: whether to show the program name in the message prefix area.
static FileSinkPtr instance(FILE *f, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
static SequenceFilterPtr instance(size_t nskip, size_t rate, size_t limit)
Construct an instance.
Facilities & disable(Importance imp)
Enable/disable specific importance level across all facilities.
Importance
Level of importance for a message.
void shutdown()
Reset global variables to initial states.
Filters messages based on time.
SharedPointer< class FdSink > FdSinkPtr
Smart pointer.
std::string stringifyImportance(Importance)
Convert an Importance enum to a string.
MesgProps dflts_
Default properties merged into each incoming message.
const MesgProps & overridePropertiesNS() const
Overrides message properties.
SProxy assertionStream
The stream to be used for assertions.
FileSink(FILE *f, const PrefixPtr &prefix)
Constructor for derived classes.
Base class for all types of message destinations.
Base class for reference counted objects.
DestinationPtr merr
Library-provided message destination.
void complete()
Cause the message to enter the completed state.
Number of distinct importance levels.
static FdSinkPtr instance(int fd, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
SharedPointer< class StreamSink > StreamSinkPtr
Smart pointer.
Send free-format messages to a C++ I/O stream.
PrefixPtr showFacilityName(When w)
Property: whether to show the facilityName property.
virtual void forwarded(const MesgProps &)
Called once by bakeDestinations if shouldForward() returned true.
std::string escape(const std::string &)
Convert a string to its C representation.
Warning messages that indicate an unusual situation from which the program was able to fully recover...
MesgProps & overridePropertiesNS()
Overrides message properties.
static PrefixPtr instance()
Allocating constructor.
Detailed tracing information useful to end-users that are trying to understand program internals...
Prefix()
Constructor for derived classes.
StreamSink(std::ostream &stream, const PrefixPtr &prefix)
Constructor for derived classes.
static GangPtr instanceForTty()
Returns the gang for streams that are emitting to a tty.
std::ostream & operator<<(std::ostream &o, const MesgProps &props)
Print the values for all message properties.
const MesgProps & properties() const
Returns a reference to message properties.
Optional< std::string > completionStr
String to append to the end of each complete message.
double now()
Current system time in seconds.
Optional< std::string > cancelationStr
String to append to a partial message when it is destroyed.
static GangPtr instance()
New non-shared gang with NO_GANG_ID.
Mesg(const MesgProps &props, const std::string &mesg)
Creates a new, completed message with the specified text.
Converts text to messages.
SequenceFilter(size_t nskip, size_t rate, size_t limit)
Constructor for derived classes.
ColorSpec(AnsiColor fg, AnsiColor bg, bool bold)
Constructs an object with fully-specified colors.
SharedPointer< class UnformattedSink > UnformattedSinkPtr
Smart pointer.
Optional< std::string > facilityName
The name of the logging facility that produced this message.
AnsiColor background
Background color, or COLOR_DEFAULT.
PrefixPtr showProgramName(bool b)
Property: whether to show the program name in the message prefix area.
bool showThreadId() const
Property: whether to show the thread ID in the message prefix area.
bool initializeLibrary()
Explicitly initialize the library.
Facilities & disable()
Enable/disable all facilities.
Container associating values with keys.
SharedPointer< class Multiplexer > MultiplexerPtr
Smart pointer.
bool operator!() const
Returns false if this stream is enabled.
AnsiColor foreground
Foreground color, or COLOR_DEFAULT.
Granular tracing information useful to end-users that are trying to understand program internals...
Filters messages based on how many messages have been seen.