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>
438 MesgProps(): isBuffered(boost::indeterminate), useColor(boost::indeterminate) {}
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&);
611 mutable SAWYER_THREAD_TRAITS::RecursiveMutex
mutex_;
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>
738 virtual bool shouldForward(
const MesgProps&) = 0;
743 virtual void forwarded(
const MesgProps&) = 0;
758 : nSkip_(nskip), rate_(rate), limit_(limit), nPosted_(0) {}
776 size_t nSkip()
const;
800 size_t limit()
const;
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) {}
847 double minInterval()
const;
858 double initialDelay()
const;
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_);
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;
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) {
1061 void setProgramName();
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_;
1218 bool partialMessagesAllowed()
const;
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
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_;
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);
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 =
"");
1720 static std::vector<std::string> parseName(
const std::string&);
1741 mutable SAWYER_THREAD_TRAITS::Mutex mutex_;
1742 #include <Sawyer/WarningsOff.h>
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;
1984 SAWYER_EXPORT
extern Facility
mlog;
2033 : facilities_(facilities) {
Facilities & disable(Importance imp)
Enable/disable specific importance level across all facilities.
Mesg()
Creates a new, partial message that is empty.
std::string stringifyColor(AnsiColor)
Convert an AnsiColor enum to a string.
FileSink(FILE *f, const PrefixPtr &prefix)
Constructor for derived classes.
Facilities & disable(const std::string &switch_name)
Enable/disable a facility by name.
SequenceFilter(size_t nskip, size_t rate, size_t limit)
Constructor for derived classes.
static FdSinkPtr instance(int fd, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
Colors to use for each message importance.
When showFacilityName() const
Property: whether to show the facilityName property.
Base class for all types of message destinations.
@ COLOR_DEFAULT
ANSI default color.
Optional< std::string > lineTermination
Line termination for completion, interruption, and cancelation.
PrefixPtr showImportance(bool b)
Property: whether to show the importance property.
Prefix()
Constructor for derived classes.
void disable()
Enable or disable a stream.
std::pair< DestinationPtr, MesgProps > BakedDestination
Baked properties for a destination.
~FacilitiesGuard()
Restores previously saved facility settings.
static GangPtr instanceForTty()
Returns the gang for streams that are emitting to a tty.
std::set< Importance > ImportanceSet
A set of importance levels.
std::string escape(const std::string &)
Convert a string to its C representation.
MesgProps overrides_
Override properties applied to incoming message.
SharedPointer< class Multiplexer > MultiplexerPtr
Smart pointer.
SharedPointer< class FileSink > FileSinkPtr
Smart pointer.
SharedPointer< class SequenceFilter > SequenceFilterPtr
Smart pointer.
@ COLOR_MAGENTA
ANSI "magenta" color.
Send free-format messages to a Unix file descriptor.
const ColorSpec & operator[](Importance imp) const
Colors for a message.
bool showElapsedTime() const
Property: whether to show time deltas.
Information printed at the beginning of each free-format message.
Facilities mfacilities
Library-provided facility group.
Facility mlog
Facility used by Sawyer components.
static GangPtr instance()
New non-shared gang with NO_GANG_ID.
Mesg(const std::string &facilityName, Importance imp, const std::string &mesg)
Creates a new, completed message with the specified text.
Optional< std::string > cancelationStr
String to append to a partial message when it is destroyed.
std::vector< BakedDestination > BakedDestinations
Baked properties for multiple destinations.
FacilitiesGuard()
Saves and restores the global message facilities.
Filters messages based on importance level.
@ N_IMPORTANCE
Number of distinct importance levels.
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 isComplete() const
Returns true if the message has entered the completed state.
Converts text to messages.
SharedPointer< class StreamSink > StreamSinkPtr
Smart pointer.
@ COLOR_BLUE
ANSI "blue" color.
bool isConstructed() const
Returns true if called on an object that has been constructed.
boost::tribool isBuffered
Whether the output buffered and emitted on a per-message basis.
MesgProps dflts_
Default properties merged into each incoming message.
PrefixPtr showElapsedTime(bool b)
Property: whether to show time deltas.
When
When to show something.
Container associating values with keys.
@ DEBUG
Messages intended to be useful primarily to the author of the code.
AnsiColor background
Background color, or COLOR_DEFAULT.
ANSI Color specification for text written to a terminal.
@ COLOR_GREEN
ANSI "green" color.
Mesg(const MesgProps &props, const std::string &mesg)
Creates a new, completed message with the specified text.
std::ostream & operator<<(std::ostream &o, const MesgProps &props)
Print the values for all message properties.
Facilities()
Constructs an empty container of Facility objects.
void shutdown()
Reset global variables to initial states.
SharedPointer< class Destination > DestinationPtr
Smart pointer.
ColorSpec()
Constructs an object with default foreground and background colors.
Stream & operator[](Importance imp)
Returns a stream for the specified importance level.
SharedPointer< class Prefix > PrefixPtr
Smart pointer.
std::string stringifyImportance(Importance)
Convert an Importance enum to a string.
virtual void forwarded(const MesgProps &)
Called once by bakeDestinations if shouldForward() returned true.
MesgProps & properties()
Returns a reference to message properties.
Sends messages to the syslog daemon.
Facilities & disable()
Enable/disable all facilities.
SProxy assertionStream
The stream to be used for assertions.
PrefixPtr showProgramName(bool b)
Property: whether to show the program name in the message prefix area.
ColorSet & colorSet()
Property: colors to use for the prefix if coloring is enabled.
Optional< std::string > completionStr
String to append to the end of each complete message.
Saves and restores facilities.
const std::string & text() const
Return the message text.
static TimeFilterPtr instance(double minInterval)
Allocating constructor.
SharedPointer< class SyslogSink > SyslogSinkPtr
Smart pointer.
StreamSink(std::ostream &stream, const PrefixPtr &prefix)
Constructor for derived classes.
static ImportanceFilterPtr instance(bool dflt)
Allocating constructor.
@ FATAL
Messages that indicate an abnormal situation from which the program was unable to recover.
bool isDefault() const
Returns true if this object is in its default-constructed state.
unsigned id() const
Return unique message ID.
Mesg(const MesgProps &props)
Creates a new, partial message that is empty.
Sends incoming messages to multiple destinations.
const Optional< std::string > & programName() const
Property: program name.
const ColorSet & colorSet() const
Property: colors to use for the prefix if coloring is enabled.
Collection of facilities.
Base class for internal nodes that filter messages.
Filters messages based on time.
AnsiColor foreground
Foreground color, or COLOR_DEFAULT.
Importance
Level of importance for a message.
ColorSpec & operator[](Importance imp)
Colors for a message.
ColorSpec(AnsiColor fg, AnsiColor bg, bool bold)
Constructs an object with fully-specified colors.
@ MARCH
Progress reports and other similar rapidly updating partial messages.
unsigned id() const
Exception unless isValid().
SharedPointer< class Gang > GangPtr
Smart pointer.
void clear()
Reset to initial state.
Multiplexer()
Constructor for derived classes.
Mesg(const std::string &facilityName, Importance imp)
Creates a new, partial message that is empty.
@ TRACE
Detailed tracing information useful to end-users that are trying to understand program internals.
boost::tribool useColor
Whether to use ANSI escape sequences to colorize output.
bool isValid() const
Returns true if high water is defined.
bool showProgramName() const
Property: whether to show the program name in the message prefix area.
const MesgProps & properties() const
Returns a reference to message properties.
@ INFO
Informative messages.
static GangPtr instanceForId(int id)
The gang for the specified ID, creating a new one if necessary.
static SequenceFilterPtr instance(size_t nskip, size_t rate, size_t limit)
Construct an instance.
FdSink(int fd, const PrefixPtr &prefix)
Constructor for derived classes.
static PrefixPtr instance()
Allocating constructor.
SharedPointer< class Filter > FilterPtr
Smart pointer.
PrefixPtr showFacilityName(When w)
Property: whether to show the facilityName property.
Reference-counting intrusive smart pointer.
Optional< std::string > facilityName
The name of the logging facility that produced this message.
Name space for the entire library.
const MesgProps & defaultPropertiesNS() const
Default values for message properties.
AnsiColor
Colors used by sinks that write to terminals.
SharedPointer< class UnformattedSink > UnformattedSinkPtr
Smart pointer.
static MultiplexerPtr instance()
Allocating constructor.
PrefixPtr showThreadId(bool b)
Property: whether to show the thread ID in the message prefix area.
@ WHERE
Granular tracing information useful to end-users that are trying to understand program internals.
PrefixPtr programName(const std::string &s)
Property: program name.
ImportanceFilter(bool dflt)
Constructor for derived classes.
DestinationPtr merr
Library-provided message destination.
Optional< std::string > interruptionStr
String to append when a partial message is interrupted.
double now()
Current system time in seconds.
static ColorSet fullColor()
Returns a color set that uses various foreground colors for the different message importance levels.
SharedPointer< class FdSink > FdSinkPtr
Smart pointer.
Send free-format messages to a C++ I/O stream.
Base class for reference counted objects.
boost::tribool bold
Use ANSI "bold" attribute?
bool isEmpty() const
Returns true if the message has no text.
Creates SharedPointer from this.
static void shutdownNS()
Reset to initial state to free memory.
ColorSpec(AnsiColor fg)
Constructs an object that specifies only a foreground color.
void cancel()
Cause the message to enter the canceled state.
Filters messages based on how many messages have been seen.
void emitted(const Mesg &, const MesgProps &)
Make specified message the high water mark.
TimeFilter(double minInterval)
Constructor for derived classes.
@ WARN
Warning messages that indicate an unusual situation from which the program was able to fully recover.
void complete()
Cause the message to enter the completed state.
Sawyer::SynchronizationTraits< Sawyer::SingleThreadedTag >::RecursiveMutex mutex_
Mutex protecting data members here and in subclasses.
static FileSinkPtr instance(FILE *f, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
@ COLOR_CYAN
ANSI "cyan" color.
bool isTerminal(int fd)
True if fd is a tty.
Filter()
Constructor for derived classes.
FacilitiesGuard(Facilities &facilities)
Saves and restores specified message facilities.
SharedPointer< class ImportanceFilter > ImportanceFilterPtr
Smart pointer.
@ COLOR_RED
ANSI "red" color.
bool isCanceled() const
Returns true if the message has entered the canceled state.
Mesg(const std::string &mesg)
Creates a new, completed message with the specified text.
@ COLOR_YELLOW
ANSI "yellow" color.
SharedPointer< class TimeFilter > TimeFilterPtr
Smart pointer.
bool operator!() const
Returns false if this stream is enabled.
const MesgProps & overridePropertiesNS() const
Overrides message properties.
@ COLOR_WHITE
ANSI "white" color.
Optional< Importance > importance
The message importance level.
bool showThreadId() const
Property: whether to show the thread ID in the message prefix area.
@ COLOR_BLACK
ANSI "black" color.
size_t ntext() const
Zero if !isValid().
MesgProps & defaultPropertiesNS()
Default values for message properties.
Facility()
Construct an empty facility.
bool initializeLibrary()
Explicitly initialize the library.
bool showImportance() const
Property: whether to show the importance property.
Send free-format messages to a C FILE pointer.
static StreamSinkPtr instance(std::ostream &stream, const PrefixPtr &prefix=PrefixPtr())
Allocating constructor.
@ ERROR
Error messages that indicate an abnormal situation from which the program was able to at least partia...
MesgProps & overridePropertiesNS()
Overrides message properties.