blob: f2d975282e16c0753052dc1bb2a1bebae1783e0d [file] [log] [blame]
Brian Silvermanf665d692013-02-17 22:11:39 -08001#ifndef AOS_COMMON_LOGGING_LOGGING_IMPL_H_
2#define AOS_COMMON_LOGGING_LOGGING_IMPL_H_
3
4#include <sys/types.h>
5#include <unistd.h>
6#include <stdint.h>
7#include <limits.h>
8#include <string.h>
9#include <stdio.h>
Brian Silverman669669f2014-02-14 16:32:56 -080010#include <stdarg.h>
Brian Silvermanf665d692013-02-17 22:11:39 -080011
12#include <string>
Brian Silvermand6974f42014-02-14 13:39:21 -080013#include <functional>
Brian Silvermanf665d692013-02-17 22:11:39 -080014
15#include "aos/common/logging/logging.h"
16#include "aos/common/type_traits.h"
17#include "aos/common/mutex.h"
18
Brian Silvermand6974f42014-02-14 13:39:21 -080019namespace aos {
20
21class MessageType;
22
23} // namespace aos
24
Brian Silvermanf665d692013-02-17 22:11:39 -080025// This file has all of the logging implementation. It can't be #included by C
26// code like logging.h can.
Brian Silverman1a572cc2013-03-05 19:58:01 -080027// It is useful for the rest of the logging implementation and other C++ code
28// that needs to do special things with logging.
Brian Silvermanb0893882014-02-10 14:48:30 -080029//
30// It is implemented in logging_impl.cc and logging_interface.cc. They are
31// separate so that code used by logging_impl.cc can link in
32// logging_interface.cc to use logging.
Brian Silvermanf665d692013-02-17 22:11:39 -080033
34namespace aos {
35namespace logging {
36
37// Unless explicitly stated otherwise, format must always be a string constant,
38// args are printf-style arguments for format, and ap is a va_list of args.
Brian Silverman1a572cc2013-03-05 19:58:01 -080039// The validity of format and args together will be checked at compile time
Brian Silvermanf665d692013-02-17 22:11:39 -080040// using a gcc function attribute.
41
42// The struct that the code uses for making logging calls.
43// Packed so that it ends up the same under both linux and vxworks.
44struct __attribute__((packed)) LogMessage {
45#ifdef __VXWORKS__
46 static_assert(sizeof(pid_t) == sizeof(int),
47 "we use task IDs (aka ints) and pid_t interchangeably");
48#endif
49 // Actually the task ID (aka a pointer to the TCB) on the cRIO.
50 pid_t source;
51 static_assert(sizeof(source) == 4, "that's how they get printed");
52 // Per task/thread.
53 uint16_t sequence;
54 log_level level;
55 int32_t seconds, nseconds;
56 char name[100];
57 char message[LOG_MESSAGE_LEN];
58};
59static_assert(shm_ok<LogMessage>::value, "it's going in a queue");
60
61// Returns left > right. LOG_UNKNOWN is most important.
62static inline bool log_gt_important(log_level left, log_level right) {
63 if (left == ERROR) left = 3;
64 if (right == ERROR) right = 3;
65 return left > right;
66}
67
68// Returns a string representing level or "unknown".
69static inline const char *log_str(log_level level) {
70#define DECL_LEVEL(name, value) if (level == name) return #name;
71 DECL_LEVELS;
72#undef DECL_LEVEL
73 return "unknown";
74}
75// Returns the log level represented by str or LOG_UNKNOWN.
76static inline log_level str_log(const char *str) {
77#define DECL_LEVEL(name, value) if (!strcmp(str, #name)) return name;
78 DECL_LEVELS;
79#undef DECL_LEVEL
80 return LOG_UNKNOWN;
81}
82
83// Takes a message and logs it. It will set everything up and then call DoLog
84// for the current LogImplementation.
85void VLog(log_level level, const char *format, va_list ap);
86// Adds to the saved up message.
87void VCork(int line, const char *format, va_list ap);
88// Actually logs the saved up message.
89void VUnCork(int line, log_level level, const char *file,
90 const char *format, va_list ap);
91
92// Will call VLog with the given arguments for the next logger in the chain.
93void LogNext(log_level level, const char *format, ...)
94 __attribute__((format(LOG_PRINTF_FORMAT_TYPE, 2, 3)));
95
Brian Silvermand6974f42014-02-14 13:39:21 -080096// Will take a structure and log it.
97template <class T>
98void DoLogStruct(log_level, const ::std::string &, const T &);
99
Brian Silvermanf665d692013-02-17 22:11:39 -0800100// Represents a system that can actually take log messages and do something
101// useful with them.
102// All of the code (transitively too!) in the DoLog here can make
103// normal LOG and LOG_DYNAMIC calls but can NOT call LOG_CORK/LOG_UNCORK. These
104// calls will not result in DoLog recursing. However, implementations must be
105// safe to call from multiple threads/tasks at the same time. Also, any other
106// overriden methods may end up logging through a given implementation's DoLog.
107class LogImplementation {
108 public:
109 LogImplementation() : next_(NULL) {}
110
111 // The one that this one's implementation logs to.
112 // NULL means that there is no next one.
113 LogImplementation *next() { return next_; }
114 // Virtual in case a subclass wants to perform checks. There will be a valid
115 // logger other than this one available while this is called.
116 virtual void set_next(LogImplementation *next) { next_ = next; }
117
118 private:
119 // Actually logs the given message. Implementations should somehow create a
120 // LogMessage and then call internal::FillInMessage.
121 virtual void DoLog(log_level level, const char *format, va_list ap) = 0;
Brian Silverman669669f2014-02-14 16:32:56 -0800122 void DoLogVariadic(log_level level, const char *format, ...) {
123 va_list ap;
124 va_start(ap, format);
125 DoLog(level, format, ap);
126 va_end(ap);
127 }
Brian Silvermanf665d692013-02-17 22:11:39 -0800128
Brian Silvermand6974f42014-02-14 13:39:21 -0800129 // Logs the contents of an auto-generated structure. The implementation here
130 // just converts it to a string with PrintMessage and then calls DoLog with
131 // that, however some implementations can be a lot more efficient than that.
132 // size and type are the result of calling Size() and Type() on the type of
133 // the message.
134 // serialize will call Serialize on the message.
135 virtual void LogStruct(log_level level, const ::std::string &message,
136 size_t size, const MessageType *type,
137 const ::std::function<size_t(char *)> &serialize);
138
139 // These functions call similar methods on the "current" LogImplementation or
140 // Die if they can't find one.
141 // levels is how many LogImplementations to not use off the stack.
Brian Silvermanf665d692013-02-17 22:11:39 -0800142 static void DoVLog(log_level, const char *format, va_list ap, int levels);
Brian Silvermand6974f42014-02-14 13:39:21 -0800143 // This one is implemented in queue_logging.cc.
144 static void DoLogStruct(log_level level, const ::std::string &message,
145 size_t size, const MessageType *type,
146 const ::std::function<size_t(char *)> &serialize,
147 int levels);
148
149 // Friends so that they can access the static Do* functions.
Brian Silvermanf665d692013-02-17 22:11:39 -0800150 friend void VLog(log_level, const char *, va_list);
151 friend void LogNext(log_level, const char *, ...);
Brian Silvermand6974f42014-02-14 13:39:21 -0800152 template <class T>
153 friend void DoLogStruct(log_level, const ::std::string &, const T &);
Brian Silvermanf665d692013-02-17 22:11:39 -0800154
155 LogImplementation *next_;
156};
157
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800158// A log implementation that dumps all messages to a C stdio stream.
159class StreamLogImplementation : public LogImplementation {
160 public:
161 StreamLogImplementation(FILE *stream);
162
163 private:
164 virtual void DoLog(log_level level, const char *format, va_list ap);
165
166 FILE *const stream_;
167};
168
Brian Silvermanf665d692013-02-17 22:11:39 -0800169// Adds another implementation to the stack of implementations in this
170// task/thread.
171// Any tasks/threads created after this call will also use this implementation.
172// The cutoff is when the state in a given task/thread is created (either lazily
173// when needed or by calling Load()).
174// The logging system takes ownership of implementation. It will delete it if
175// necessary, so it must be created with new.
176void AddImplementation(LogImplementation *implementation);
177
178// Must be called at least once per process/load before anything else is
179// called. This function is safe to call multiple times from multiple
180// tasks/threads.
181void Init();
182
183// Forces all of the state that is usually lazily created when first needed to
184// be created when called. Cleanup() will delete it.
185void Load();
186// Resets all information in this task/thread to its initial state.
187// NOTE: This is not the opposite of Init(). The state that this deletes is
188// lazily created when needed. It is actually the opposite of Load().
189void Cleanup();
190
191// This is where all of the code that is only used by actual LogImplementations
192// goes.
193namespace internal {
194
Brian Silvermanb0893882014-02-10 14:48:30 -0800195extern LogImplementation *global_top_implementation;
196
Brian Silvermanf665d692013-02-17 22:11:39 -0800197// An separate instance of this class is accessible from each task/thread.
Brian Silverman1a572cc2013-03-05 19:58:01 -0800198// NOTE: It will get deleted in the child of a fork.
Brian Silvermanf665d692013-02-17 22:11:39 -0800199struct Context {
200 Context();
201
202 // Gets the Context object for this task/thread. Will create one the first
203 // time it is called.
204 //
205 // The implementation for each platform will lazily instantiate a new instance
206 // and then initialize name the first time.
207 // IMPORTANT: The implementation of this can not use logging.
208 static Context *Get();
209 // Deletes the Context object for this task/thread so that the next Get() is
210 // called it will create a new one.
211 // It is valid to call this when Get() has never been called.
212 static void Delete();
213
214 // Which one to log to right now.
215 // Will be NULL if there is no logging implementation to use right now.
216 LogImplementation *implementation;
217
Brian Silvermanab6615c2013-03-05 20:29:29 -0800218 // A name representing this task/(process and thread).
219 // strlen(name.c_str()) must be <= sizeof(LogMessage::name).
220 ::std::string name;
Brian Silvermanf665d692013-02-17 22:11:39 -0800221
222 // What to assign LogMessage::source to in this task/thread.
223 pid_t source;
224
225 // The sequence value to send out with the next message.
226 uint16_t sequence;
227
228 // Contains all of the information related to implementing LOG_CORK and
229 // LOG_UNCORK.
230 struct {
231 char message[LOG_MESSAGE_LEN];
232 int line_min, line_max;
233 // Sets the data up to record a new series of corked logs.
234 void Reset() {
235 message[0] = '\0'; // make strlen of it 0
236 line_min = INT_MAX;
237 line_max = -1;
238 function = NULL;
239 }
240 // The function that the calls are in.
241 // REMEMBER: While the compiler/linker will probably optimize all of the
242 // identical strings to point to the same data, it might not, so using == to
243 // compare this with another value is a bad idea.
244 const char *function;
245 } cork_data;
246};
247
248// Fills in *message according to the given inputs. Used for implementing
249// LogImplementation::DoLog.
250void FillInMessage(log_level level, const char *format, va_list ap,
251 LogMessage *message);
252
253// Prints message to output.
254void PrintMessage(FILE *output, const LogMessage &message);
255
Brian Silvermanb0893882014-02-10 14:48:30 -0800256// Prints format (with ap) into output and correctly deals with the result
257// being too long etc.
258void ExecuteFormat(char *output, size_t output_size, const char *format,
259 va_list ap);
260
Brian Silvermand6974f42014-02-14 13:39:21 -0800261// Runs the given function with the current LogImplementation (handles switching
262// it out while running function etc).
263void RunWithCurrentImplementation(
264 int levels, ::std::function<void(LogImplementation *)> function);
265
Brian Silvermanf665d692013-02-17 22:11:39 -0800266} // namespace internal
267} // namespace logging
268} // namespace aos
269
270#endif // AOS_COMMON_LOGGING_LOGGING_IMPL_H_