blob: 440e3fed48b7c030ad110d676164bb863e774183 [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.
Brian Silverman88471dc2014-02-15 22:35:42 -080043struct LogMessage {
44 enum class Type : uint8_t {
Brian Silvermanfd5e2a32014-02-22 20:02:39 -080045 kString, kStruct, kMatrix
Brian Silverman88471dc2014-02-15 22:35:42 -080046 };
47
48 int32_t seconds, nseconds;
Brian Silvermanff12c9f2014-03-19 17:53:29 -070049 // message_length is just the length of the actual data (which member depends
50 // on the type).
Brian Silverman88471dc2014-02-15 22:35:42 -080051 size_t message_length, name_length;
Brian Silvermanf665d692013-02-17 22:11:39 -080052 pid_t source;
53 static_assert(sizeof(source) == 4, "that's how they get printed");
54 // Per task/thread.
55 uint16_t sequence;
Brian Silverman88471dc2014-02-15 22:35:42 -080056 Type type;
Brian Silvermanf665d692013-02-17 22:11:39 -080057 log_level level;
Brian Silvermanf665d692013-02-17 22:11:39 -080058 char name[100];
Brian Silverman88471dc2014-02-15 22:35:42 -080059 union {
60 char message[LOG_MESSAGE_LEN];
61 struct {
62 uint32_t type_id;
63 size_t string_length;
64 // The message string and then the serialized structure.
65 char serialized[LOG_MESSAGE_LEN - sizeof(type) - sizeof(string_length)];
66 } structure;
Brian Silvermanfd5e2a32014-02-22 20:02:39 -080067 struct {
68 // The type ID of the element type.
69 uint32_t type;
Brian Silvermanff12c9f2014-03-19 17:53:29 -070070 int rows, cols;
71 size_t string_length;
72 // The message string and then the serialized matrix.
Brian Silvermanfd5e2a32014-02-22 20:02:39 -080073 char
Brian Silvermanff12c9f2014-03-19 17:53:29 -070074 data[LOG_MESSAGE_LEN - sizeof(type) - sizeof(rows) - sizeof(cols)];
Brian Silvermanfd5e2a32014-02-22 20:02:39 -080075 } matrix;
Brian Silverman88471dc2014-02-15 22:35:42 -080076 };
Brian Silvermanf665d692013-02-17 22:11:39 -080077};
78static_assert(shm_ok<LogMessage>::value, "it's going in a queue");
79
80// Returns left > right. LOG_UNKNOWN is most important.
81static inline bool log_gt_important(log_level left, log_level right) {
82 if (left == ERROR) left = 3;
83 if (right == ERROR) right = 3;
84 return left > right;
85}
86
87// Returns a string representing level or "unknown".
88static inline const char *log_str(log_level level) {
89#define DECL_LEVEL(name, value) if (level == name) return #name;
90 DECL_LEVELS;
91#undef DECL_LEVEL
92 return "unknown";
93}
94// Returns the log level represented by str or LOG_UNKNOWN.
95static inline log_level str_log(const char *str) {
96#define DECL_LEVEL(name, value) if (!strcmp(str, #name)) return name;
97 DECL_LEVELS;
98#undef DECL_LEVEL
99 return LOG_UNKNOWN;
100}
101
102// Takes a message and logs it. It will set everything up and then call DoLog
103// for the current LogImplementation.
104void VLog(log_level level, const char *format, va_list ap);
105// Adds to the saved up message.
106void VCork(int line, const char *format, va_list ap);
107// Actually logs the saved up message.
108void VUnCork(int line, log_level level, const char *file,
109 const char *format, va_list ap);
110
111// Will call VLog with the given arguments for the next logger in the chain.
112void LogNext(log_level level, const char *format, ...)
113 __attribute__((format(LOG_PRINTF_FORMAT_TYPE, 2, 3)));
114
Brian Silvermanfd5e2a32014-02-22 20:02:39 -0800115// Takes a structure and log it.
Brian Silvermand6974f42014-02-14 13:39:21 -0800116template <class T>
117void DoLogStruct(log_level, const ::std::string &, const T &);
Brian Silvermanfd5e2a32014-02-22 20:02:39 -0800118// Takes a matrix and logs it.
119template <class T>
120void DoLogMatrix(log_level, const ::std::string &, const T &);
Brian Silvermand6974f42014-02-14 13:39:21 -0800121
Brian Silvermanf665d692013-02-17 22:11:39 -0800122// Represents a system that can actually take log messages and do something
123// useful with them.
124// All of the code (transitively too!) in the DoLog here can make
125// normal LOG and LOG_DYNAMIC calls but can NOT call LOG_CORK/LOG_UNCORK. These
126// calls will not result in DoLog recursing. However, implementations must be
127// safe to call from multiple threads/tasks at the same time. Also, any other
128// overriden methods may end up logging through a given implementation's DoLog.
129class LogImplementation {
130 public:
131 LogImplementation() : next_(NULL) {}
132
133 // The one that this one's implementation logs to.
134 // NULL means that there is no next one.
135 LogImplementation *next() { return next_; }
136 // Virtual in case a subclass wants to perform checks. There will be a valid
137 // logger other than this one available while this is called.
138 virtual void set_next(LogImplementation *next) { next_ = next; }
139
140 private:
141 // Actually logs the given message. Implementations should somehow create a
142 // LogMessage and then call internal::FillInMessage.
143 virtual void DoLog(log_level level, const char *format, va_list ap) = 0;
Brian Silverman669669f2014-02-14 16:32:56 -0800144 void DoLogVariadic(log_level level, const char *format, ...) {
145 va_list ap;
146 va_start(ap, format);
147 DoLog(level, format, ap);
148 va_end(ap);
149 }
Brian Silvermanf665d692013-02-17 22:11:39 -0800150
Brian Silvermand6974f42014-02-14 13:39:21 -0800151 // Logs the contents of an auto-generated structure. The implementation here
152 // just converts it to a string with PrintMessage and then calls DoLog with
153 // that, however some implementations can be a lot more efficient than that.
154 // size and type are the result of calling Size() and Type() on the type of
155 // the message.
156 // serialize will call Serialize on the message.
157 virtual void LogStruct(log_level level, const ::std::string &message,
158 size_t size, const MessageType *type,
159 const ::std::function<size_t(char *)> &serialize);
Brian Silvermanfd5e2a32014-02-22 20:02:39 -0800160 // Similiar to LogStruct, except for matrixes.
161 // type_id is the type of the elements of the matrix.
162 // data points to rows*cols*type_id.Size() bytes of data in row-major order.
163 virtual void LogMatrix(log_level level, const ::std::string &message,
164 uint32_t type_id, int rows, int cols,
165 const void *data);
Brian Silvermand6974f42014-02-14 13:39:21 -0800166
167 // These functions call similar methods on the "current" LogImplementation or
168 // Die if they can't find one.
169 // levels is how many LogImplementations to not use off the stack.
Brian Silvermanf665d692013-02-17 22:11:39 -0800170 static void DoVLog(log_level, const char *format, va_list ap, int levels);
Brian Silvermand6974f42014-02-14 13:39:21 -0800171 // This one is implemented in queue_logging.cc.
172 static void DoLogStruct(log_level level, const ::std::string &message,
173 size_t size, const MessageType *type,
174 const ::std::function<size_t(char *)> &serialize,
175 int levels);
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700176 // This one is implemented in matrix_logging.cc.
Brian Silvermanfd5e2a32014-02-22 20:02:39 -0800177 static void DoLogMatrix(log_level level, const ::std::string &message,
178 uint32_t type_id, int rows, int cols,
Brian Silvermanff12c9f2014-03-19 17:53:29 -0700179 const void *data, int levels);
Brian Silvermand6974f42014-02-14 13:39:21 -0800180
181 // Friends so that they can access the static Do* functions.
Brian Silvermanf665d692013-02-17 22:11:39 -0800182 friend void VLog(log_level, const char *, va_list);
183 friend void LogNext(log_level, const char *, ...);
Brian Silvermand6974f42014-02-14 13:39:21 -0800184 template <class T>
185 friend void DoLogStruct(log_level, const ::std::string &, const T &);
Brian Silvermanfd5e2a32014-02-22 20:02:39 -0800186 template <class T>
187 friend void DoLogMatrix(log_level, const ::std::string &, const T &);
Brian Silvermanf665d692013-02-17 22:11:39 -0800188
189 LogImplementation *next_;
190};
191
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800192// A log implementation that dumps all messages to a C stdio stream.
193class StreamLogImplementation : public LogImplementation {
194 public:
195 StreamLogImplementation(FILE *stream);
196
197 private:
198 virtual void DoLog(log_level level, const char *format, va_list ap);
199
200 FILE *const stream_;
201};
202
Brian Silvermanf665d692013-02-17 22:11:39 -0800203// Adds another implementation to the stack of implementations in this
204// task/thread.
205// Any tasks/threads created after this call will also use this implementation.
206// The cutoff is when the state in a given task/thread is created (either lazily
207// when needed or by calling Load()).
208// The logging system takes ownership of implementation. It will delete it if
209// necessary, so it must be created with new.
210void AddImplementation(LogImplementation *implementation);
211
212// Must be called at least once per process/load before anything else is
213// called. This function is safe to call multiple times from multiple
214// tasks/threads.
215void Init();
216
217// Forces all of the state that is usually lazily created when first needed to
218// be created when called. Cleanup() will delete it.
219void Load();
220// Resets all information in this task/thread to its initial state.
221// NOTE: This is not the opposite of Init(). The state that this deletes is
222// lazily created when needed. It is actually the opposite of Load().
223void Cleanup();
224
225// This is where all of the code that is only used by actual LogImplementations
226// goes.
227namespace internal {
228
Brian Silvermanb0893882014-02-10 14:48:30 -0800229extern LogImplementation *global_top_implementation;
230
Brian Silvermanf665d692013-02-17 22:11:39 -0800231// An separate instance of this class is accessible from each task/thread.
Brian Silverman1a572cc2013-03-05 19:58:01 -0800232// NOTE: It will get deleted in the child of a fork.
Brian Silvermanf665d692013-02-17 22:11:39 -0800233struct Context {
234 Context();
235
236 // Gets the Context object for this task/thread. Will create one the first
237 // time it is called.
238 //
239 // The implementation for each platform will lazily instantiate a new instance
240 // and then initialize name the first time.
241 // IMPORTANT: The implementation of this can not use logging.
242 static Context *Get();
243 // Deletes the Context object for this task/thread so that the next Get() is
244 // called it will create a new one.
245 // It is valid to call this when Get() has never been called.
246 static void Delete();
247
248 // Which one to log to right now.
249 // Will be NULL if there is no logging implementation to use right now.
250 LogImplementation *implementation;
251
Brian Silvermanab6615c2013-03-05 20:29:29 -0800252 // A name representing this task/(process and thread).
253 // strlen(name.c_str()) must be <= sizeof(LogMessage::name).
254 ::std::string name;
Brian Silvermanf665d692013-02-17 22:11:39 -0800255
256 // What to assign LogMessage::source to in this task/thread.
257 pid_t source;
258
259 // The sequence value to send out with the next message.
260 uint16_t sequence;
261
262 // Contains all of the information related to implementing LOG_CORK and
263 // LOG_UNCORK.
264 struct {
265 char message[LOG_MESSAGE_LEN];
266 int line_min, line_max;
267 // Sets the data up to record a new series of corked logs.
268 void Reset() {
269 message[0] = '\0'; // make strlen of it 0
270 line_min = INT_MAX;
271 line_max = -1;
272 function = NULL;
273 }
274 // The function that the calls are in.
275 // REMEMBER: While the compiler/linker will probably optimize all of the
276 // identical strings to point to the same data, it might not, so using == to
277 // compare this with another value is a bad idea.
278 const char *function;
279 } cork_data;
280};
281
Brian Silverman88471dc2014-02-15 22:35:42 -0800282// Fills in all the parts of message according to the given inputs (with type
283// kStruct).
284void FillInMessageStructure(log_level level,
285 const ::std::string &message_string, size_t size,
286 const MessageType *type,
287 const ::std::function<size_t(char *)> &serialize,
288 LogMessage *message);
289
Brian Silverman664db1a2014-03-20 17:06:29 -0700290// Fills in all the parts of the message according to the given inputs (with
291// type kMatrix).
292void FillInMessageMatrix(log_level level,
293 const ::std::string &message_string, uint32_t type_id,
294 int rows, int cols, const void *data,
295 LogMessage *message);
296
Brian Silverman88471dc2014-02-15 22:35:42 -0800297// Fills in *message according to the given inputs (with type kString).
298// Used for implementing LogImplementation::DoLog.
Brian Silvermanf665d692013-02-17 22:11:39 -0800299void FillInMessage(log_level level, const char *format, va_list ap,
300 LogMessage *message);
301
Brian Silverman78968542014-03-05 17:03:43 -0800302static inline void FillInMessageVarargs(log_level level, LogMessage *message,
303 const char *format, ...) {
304 va_list ap;
305 va_start(ap, format);
306 FillInMessage(level, format, ap, message);
307 va_end(ap);
308}
309
Brian Silvermanf665d692013-02-17 22:11:39 -0800310// Prints message to output.
311void PrintMessage(FILE *output, const LogMessage &message);
312
Brian Silvermanb0893882014-02-10 14:48:30 -0800313// Prints format (with ap) into output and correctly deals with the result
314// being too long etc.
Brian Silverman88471dc2014-02-15 22:35:42 -0800315size_t ExecuteFormat(char *output, size_t output_size, const char *format,
316 va_list ap);
Brian Silvermanb0893882014-02-10 14:48:30 -0800317
Brian Silvermand6974f42014-02-14 13:39:21 -0800318// Runs the given function with the current LogImplementation (handles switching
319// it out while running function etc).
320void RunWithCurrentImplementation(
321 int levels, ::std::function<void(LogImplementation *)> function);
322
Brian Silvermanf665d692013-02-17 22:11:39 -0800323} // namespace internal
324} // namespace logging
325} // namespace aos
326
327#endif // AOS_COMMON_LOGGING_LOGGING_IMPL_H_