blob: 3d5b387e3cd192aa2f5ecdef100767909e8bf8e7 [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 {
45 kString, kStruct,
46 };
47
48 int32_t seconds, nseconds;
49 // message_length is the length of everything in message for all types.
50 size_t message_length, name_length;
Brian Silvermanf665d692013-02-17 22:11:39 -080051 pid_t source;
52 static_assert(sizeof(source) == 4, "that's how they get printed");
53 // Per task/thread.
54 uint16_t sequence;
Brian Silverman88471dc2014-02-15 22:35:42 -080055 Type type;
Brian Silvermanf665d692013-02-17 22:11:39 -080056 log_level level;
Brian Silvermanf665d692013-02-17 22:11:39 -080057 char name[100];
Brian Silverman88471dc2014-02-15 22:35:42 -080058 union {
59 char message[LOG_MESSAGE_LEN];
60 struct {
61 uint32_t type_id;
62 size_t string_length;
63 // The message string and then the serialized structure.
64 char serialized[LOG_MESSAGE_LEN - sizeof(type) - sizeof(string_length)];
65 } structure;
66 };
Brian Silvermanf665d692013-02-17 22:11:39 -080067};
68static_assert(shm_ok<LogMessage>::value, "it's going in a queue");
69
70// Returns left > right. LOG_UNKNOWN is most important.
71static inline bool log_gt_important(log_level left, log_level right) {
72 if (left == ERROR) left = 3;
73 if (right == ERROR) right = 3;
74 return left > right;
75}
76
77// Returns a string representing level or "unknown".
78static inline const char *log_str(log_level level) {
79#define DECL_LEVEL(name, value) if (level == name) return #name;
80 DECL_LEVELS;
81#undef DECL_LEVEL
82 return "unknown";
83}
84// Returns the log level represented by str or LOG_UNKNOWN.
85static inline log_level str_log(const char *str) {
86#define DECL_LEVEL(name, value) if (!strcmp(str, #name)) return name;
87 DECL_LEVELS;
88#undef DECL_LEVEL
89 return LOG_UNKNOWN;
90}
91
92// Takes a message and logs it. It will set everything up and then call DoLog
93// for the current LogImplementation.
94void VLog(log_level level, const char *format, va_list ap);
95// Adds to the saved up message.
96void VCork(int line, const char *format, va_list ap);
97// Actually logs the saved up message.
98void VUnCork(int line, log_level level, const char *file,
99 const char *format, va_list ap);
100
101// Will call VLog with the given arguments for the next logger in the chain.
102void LogNext(log_level level, const char *format, ...)
103 __attribute__((format(LOG_PRINTF_FORMAT_TYPE, 2, 3)));
104
Brian Silvermand6974f42014-02-14 13:39:21 -0800105// Will take a structure and log it.
106template <class T>
107void DoLogStruct(log_level, const ::std::string &, const T &);
108
Brian Silvermanf665d692013-02-17 22:11:39 -0800109// Represents a system that can actually take log messages and do something
110// useful with them.
111// All of the code (transitively too!) in the DoLog here can make
112// normal LOG and LOG_DYNAMIC calls but can NOT call LOG_CORK/LOG_UNCORK. These
113// calls will not result in DoLog recursing. However, implementations must be
114// safe to call from multiple threads/tasks at the same time. Also, any other
115// overriden methods may end up logging through a given implementation's DoLog.
116class LogImplementation {
117 public:
118 LogImplementation() : next_(NULL) {}
119
120 // The one that this one's implementation logs to.
121 // NULL means that there is no next one.
122 LogImplementation *next() { return next_; }
123 // Virtual in case a subclass wants to perform checks. There will be a valid
124 // logger other than this one available while this is called.
125 virtual void set_next(LogImplementation *next) { next_ = next; }
126
127 private:
128 // Actually logs the given message. Implementations should somehow create a
129 // LogMessage and then call internal::FillInMessage.
130 virtual void DoLog(log_level level, const char *format, va_list ap) = 0;
Brian Silverman669669f2014-02-14 16:32:56 -0800131 void DoLogVariadic(log_level level, const char *format, ...) {
132 va_list ap;
133 va_start(ap, format);
134 DoLog(level, format, ap);
135 va_end(ap);
136 }
Brian Silvermanf665d692013-02-17 22:11:39 -0800137
Brian Silvermand6974f42014-02-14 13:39:21 -0800138 // Logs the contents of an auto-generated structure. The implementation here
139 // just converts it to a string with PrintMessage and then calls DoLog with
140 // that, however some implementations can be a lot more efficient than that.
141 // size and type are the result of calling Size() and Type() on the type of
142 // the message.
143 // serialize will call Serialize on the message.
144 virtual void LogStruct(log_level level, const ::std::string &message,
145 size_t size, const MessageType *type,
146 const ::std::function<size_t(char *)> &serialize);
147
148 // These functions call similar methods on the "current" LogImplementation or
149 // Die if they can't find one.
150 // levels is how many LogImplementations to not use off the stack.
Brian Silvermanf665d692013-02-17 22:11:39 -0800151 static void DoVLog(log_level, const char *format, va_list ap, int levels);
Brian Silvermand6974f42014-02-14 13:39:21 -0800152 // This one is implemented in queue_logging.cc.
153 static void DoLogStruct(log_level level, const ::std::string &message,
154 size_t size, const MessageType *type,
155 const ::std::function<size_t(char *)> &serialize,
156 int levels);
157
158 // Friends so that they can access the static Do* functions.
Brian Silvermanf665d692013-02-17 22:11:39 -0800159 friend void VLog(log_level, const char *, va_list);
160 friend void LogNext(log_level, const char *, ...);
Brian Silvermand6974f42014-02-14 13:39:21 -0800161 template <class T>
162 friend void DoLogStruct(log_level, const ::std::string &, const T &);
Brian Silvermanf665d692013-02-17 22:11:39 -0800163
164 LogImplementation *next_;
165};
166
Brian Silverman1e8ddfe2013-12-19 16:20:53 -0800167// A log implementation that dumps all messages to a C stdio stream.
168class StreamLogImplementation : public LogImplementation {
169 public:
170 StreamLogImplementation(FILE *stream);
171
172 private:
173 virtual void DoLog(log_level level, const char *format, va_list ap);
174
175 FILE *const stream_;
176};
177
Brian Silvermanf665d692013-02-17 22:11:39 -0800178// Adds another implementation to the stack of implementations in this
179// task/thread.
180// Any tasks/threads created after this call will also use this implementation.
181// The cutoff is when the state in a given task/thread is created (either lazily
182// when needed or by calling Load()).
183// The logging system takes ownership of implementation. It will delete it if
184// necessary, so it must be created with new.
185void AddImplementation(LogImplementation *implementation);
186
187// Must be called at least once per process/load before anything else is
188// called. This function is safe to call multiple times from multiple
189// tasks/threads.
190void Init();
191
192// Forces all of the state that is usually lazily created when first needed to
193// be created when called. Cleanup() will delete it.
194void Load();
195// Resets all information in this task/thread to its initial state.
196// NOTE: This is not the opposite of Init(). The state that this deletes is
197// lazily created when needed. It is actually the opposite of Load().
198void Cleanup();
199
200// This is where all of the code that is only used by actual LogImplementations
201// goes.
202namespace internal {
203
Brian Silvermanb0893882014-02-10 14:48:30 -0800204extern LogImplementation *global_top_implementation;
205
Brian Silvermanf665d692013-02-17 22:11:39 -0800206// An separate instance of this class is accessible from each task/thread.
Brian Silverman1a572cc2013-03-05 19:58:01 -0800207// NOTE: It will get deleted in the child of a fork.
Brian Silvermanf665d692013-02-17 22:11:39 -0800208struct Context {
209 Context();
210
211 // Gets the Context object for this task/thread. Will create one the first
212 // time it is called.
213 //
214 // The implementation for each platform will lazily instantiate a new instance
215 // and then initialize name the first time.
216 // IMPORTANT: The implementation of this can not use logging.
217 static Context *Get();
218 // Deletes the Context object for this task/thread so that the next Get() is
219 // called it will create a new one.
220 // It is valid to call this when Get() has never been called.
221 static void Delete();
222
223 // Which one to log to right now.
224 // Will be NULL if there is no logging implementation to use right now.
225 LogImplementation *implementation;
226
Brian Silvermanab6615c2013-03-05 20:29:29 -0800227 // A name representing this task/(process and thread).
228 // strlen(name.c_str()) must be <= sizeof(LogMessage::name).
229 ::std::string name;
Brian Silvermanf665d692013-02-17 22:11:39 -0800230
231 // What to assign LogMessage::source to in this task/thread.
232 pid_t source;
233
234 // The sequence value to send out with the next message.
235 uint16_t sequence;
236
237 // Contains all of the information related to implementing LOG_CORK and
238 // LOG_UNCORK.
239 struct {
240 char message[LOG_MESSAGE_LEN];
241 int line_min, line_max;
242 // Sets the data up to record a new series of corked logs.
243 void Reset() {
244 message[0] = '\0'; // make strlen of it 0
245 line_min = INT_MAX;
246 line_max = -1;
247 function = NULL;
248 }
249 // The function that the calls are in.
250 // REMEMBER: While the compiler/linker will probably optimize all of the
251 // identical strings to point to the same data, it might not, so using == to
252 // compare this with another value is a bad idea.
253 const char *function;
254 } cork_data;
255};
256
Brian Silverman88471dc2014-02-15 22:35:42 -0800257// Fills in all the parts of message according to the given inputs (with type
258// kStruct).
259void FillInMessageStructure(log_level level,
260 const ::std::string &message_string, size_t size,
261 const MessageType *type,
262 const ::std::function<size_t(char *)> &serialize,
263 LogMessage *message);
264
265// Fills in *message according to the given inputs (with type kString).
266// Used for implementing LogImplementation::DoLog.
Brian Silvermanf665d692013-02-17 22:11:39 -0800267void FillInMessage(log_level level, const char *format, va_list ap,
268 LogMessage *message);
269
270// Prints message to output.
271void PrintMessage(FILE *output, const LogMessage &message);
272
Brian Silvermanb0893882014-02-10 14:48:30 -0800273// Prints format (with ap) into output and correctly deals with the result
274// being too long etc.
Brian Silverman88471dc2014-02-15 22:35:42 -0800275size_t ExecuteFormat(char *output, size_t output_size, const char *format,
276 va_list ap);
Brian Silvermanb0893882014-02-10 14:48:30 -0800277
Brian Silvermand6974f42014-02-14 13:39:21 -0800278// Runs the given function with the current LogImplementation (handles switching
279// it out while running function etc).
280void RunWithCurrentImplementation(
281 int levels, ::std::function<void(LogImplementation *)> function);
282
Brian Silvermanf665d692013-02-17 22:11:39 -0800283} // namespace internal
284} // namespace logging
285} // namespace aos
286
287#endif // AOS_COMMON_LOGGING_LOGGING_IMPL_H_