2 * UCW Library -- Logging
4 * (c) 1997--2015 Martin Mares <mj@ucw.cz>
5 * (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include <ucw/clists.h>
16 #ifdef CONFIG_UCW_CLEAN_ABI
17 #define log_add_substream ucw_log_add_substream
18 #define log_check_configured ucw_log_check_configured
19 #define log_close_all ucw_log_close_all
20 #define log_close_stream ucw_log_close_stream
21 #define log_configured ucw_log_configured
22 #define log_drop_stderr ucw_log_drop_stderr
23 #define log_find_type ucw_log_find_type
24 #define log_new_configured ucw_log_new_configured
25 #define log_new_fd ucw_log_new_fd
26 #define log_new_file ucw_log_new_file
27 #define log_new_stream ucw_log_new_stream
28 #define log_new_syslog ucw_log_new_syslog
29 #define log_pass_filtered ucw_log_pass_filtered
30 #define log_register_type ucw_log_register_type
31 #define log_rm_substream ucw_log_rm_substream
32 #define log_set_default_stream ucw_log_set_default_stream
33 #define log_set_format ucw_log_set_format
34 #define log_stream_by_flags ucw_log_stream_by_flags
35 #define log_switch ucw_log_switch
36 #define log_switch_disable ucw_log_switch_disable
37 #define log_switch_enable ucw_log_switch_enable
38 #define log_syslog_facility_exists ucw_log_syslog_facility_exists
39 #define log_type_name ucw_log_type_name
42 /*** === Messages and streams ***/
45 * Inside the logging system, a log message is always represented by this structure.
48 char *m; // The formatted message itself, ending with \n\0
49 int m_len; // Length without the \0
50 struct tm *tm; // Current time
52 uint flags; // Category and other flags as passed to msg()
53 char *raw_msg; // Unformatted parts
56 uint depth; // Recursion depth
57 bool error; // An error has occurred (e.g., an infinite loop in sub-streams)
61 * Each stream is represented by an instance of this structure.
64 char *name; // Optional name, allocated by the user (or constructor)
65 int regnum; // Stream number, already encoded by LS_SET_STRNUM(); -1 if closed
66 uint levels; // Bitmask of accepted severity levels (default: all)
67 uint types; // Bitmask of accepted message types (default: all)
68 uint msgfmt; // Formatting flags (LSFMT_xxx)
69 uint use_count; // Number of references to the stream
70 uint stream_flags; // Various other flags (LSFLAG_xxx)
71 int (*filter)(struct log_stream* ls, struct log_msg *m); // Filter function, return non-zero to discard the message
72 clist substreams; // Pass the message to these streams (simple_list of pointers)
73 int (*handler)(struct log_stream *ls, struct log_msg *m); // Called to commit the message, return 0 for success, errno on error
74 void (*close)(struct log_stream* ls); // Called upon log_close_stream()
75 void *user_data; // Not used by the logging system
76 // Private data of the handler follow
80 * Formatting flags specifying the format of the message passed to the handler.
83 LSFMT_LEVEL = 1, // severity level (one letter) */
84 LSFMT_TIME = 2, // date and time (YYYY-mm-dd HH:MM:SS) */
85 LSFMT_USEC = 4, // also micro-seconds */
86 LSFMT_TITLE = 8, // program title (log_title) */
87 LSFMT_PID = 16, // program PID (log_pid) */
88 LSFMT_LOGNAME = 32, // name of the log_stream */
89 LSFMT_TYPE = 64, // message type
92 #define LSFMT_DEFAULT (LSFMT_LEVEL | LSFMT_TIME | LSFMT_TITLE | LSFMT_PID) /** Default format **/
95 * General stream flags.
98 LSFLAG_ERR_IS_FATAL = 1, // When a logging error occurs, die() immediately
99 LSFLAG_ERR_REPORTED = 2, // A logging error has been already reported on this stream
105 * The @flags parameter of <<basics:msg()>> is divided to several groups of bits (from the LSB):
106 * message severity level (`L_xxx`), destination stream, message type
107 * and control bits (e.g., `L_SIGHANDLER`).
110 enum ls_flagbits { // Bit widths of groups
117 enum ls_flagpos { // Bit positions of groups
119 LS_STRNUM_POS = LS_LEVEL_POS + LS_LEVEL_BITS,
120 LS_TYPE_POS = LS_STRNUM_POS + LS_STRNUM_BITS,
121 LS_CTRL_POS = LS_TYPE_POS + LS_TYPE_BITS,
124 enum ls_flagmasks { // Bit masks of groups
125 LS_LEVEL_MASK = ((1 << LS_LEVEL_BITS) - 1) << LS_LEVEL_POS,
126 LS_STRNUM_MASK = ((1 << LS_STRNUM_BITS) - 1) << LS_STRNUM_POS,
127 LS_TYPE_MASK = ((1 << LS_TYPE_BITS) - 1) << LS_TYPE_POS,
128 LS_CTRL_MASK = ((1 << LS_CTRL_BITS) - 1) << LS_CTRL_POS,
131 // "Get" macros (break flags to parts)
132 #define LS_GET_LEVEL(flags) (((flags) & LS_LEVEL_MASK) >> LS_LEVEL_POS) /** Extract severity level **/
133 #define LS_GET_STRNUM(flags) (((flags) & LS_STRNUM_MASK) >> LS_STRNUM_POS) /** Extract stream number **/
134 #define LS_GET_TYPE(flags) (((flags) & LS_TYPE_MASK) >> LS_TYPE_POS) /** Extract message type **/
135 #define LS_GET_CTRL(flags) (((flags) & LS_CTRL_MASK) >> LS_CTRL_POS) /** Extract control bits **/
137 // "Set" macros (parts to flags)
138 #define LS_SET_LEVEL(level) ((level) << LS_LEVEL_POS) /** Convert severity level to flags **/
139 #define LS_SET_STRNUM(strnum) ((strnum) << LS_STRNUM_POS) /** Convert stream number to flags **/
140 #define LS_SET_TYPE(type) ((type) << LS_TYPE_POS) /** Convert message type to flags **/
141 #define LS_SET_CTRL(ctrl) ((ctrl) << LS_CTRL_POS) /** Convert control bits to flags **/
143 #define LS_NUM_TYPES (1 << LS_TYPE_BITS)
145 /** Register a new message type and return the corresponding flag set (encoded by `LS_SET_TYPE`). **/
146 int log_register_type(const char *name);
148 /** Find a message type by name and return the corresponding flag set. Returns -1 if no such type found. **/
149 int log_find_type(const char *name);
151 /** Given a flag set, extract the message type ID and return its name. **/
152 char *log_type_name(uint flags);
154 /*** === Operations on streams ***/
157 * Allocate a new log stream with no handler and an empty substream list.
158 * Since struct log_stream is followed by private data, @size bytes of memory are allocated
159 * for the whole structure. See below for functions creating specific stream types.
161 struct log_stream *log_new_stream(size_t size);
164 * Decrement the use count of a stream. If it becomes zero, close the stream,
165 * free its memory, and unlink all its substreams.
167 int log_close_stream(struct log_stream *ls);
170 * Get a new reference on an existing stream. For convenience, the return value is
171 * equal to the argument @ls.
173 static inline struct log_stream *log_ref_stream(struct log_stream *ls)
180 * Link a substream to a stream. The substream gains a reference, preventing
181 * it from being freed until it is unlinked.
183 void log_add_substream(struct log_stream *where, struct log_stream *what);
186 * Unlink all occurrences of a substream @what from stream @where. Each
187 * occurrence loses a reference. If @what is NULL, all substreams are unlinked.
188 * Returns the number of unlinked substreams.
190 int log_rm_substream(struct log_stream *where, struct log_stream *what);
193 * Set formatting flags of a given stream and all its substreams. The flags are
194 * AND'ed with @mask and OR'ed with @data.
196 void log_set_format(struct log_stream *ls, uint mask, uint data);
199 * Find a stream by its registration number (in the format of logging flags).
200 * Returns NULL if there is no such stream.
202 struct log_stream *log_stream_by_flags(uint flags);
204 /** Return a pointer to the default stream (stream #0). **/
205 static inline struct log_stream *log_default_stream(void)
207 return log_stream_by_flags(0);
211 * Make the specified stream the default destination.
213 * In fact, it takes the fixed default stream and attaches @ls as its only
214 * substream. If there were any other substreams, they are removed.
216 * Log streams created by <<basics:log_file()>> or @log_configured() are made default
217 * by calling this function.
219 void log_set_default_stream(struct log_stream *ls);
222 * Close all open streams, un-initialize the module, free all memory and
223 * reset the logging mechanism to use stderr only.
225 void log_close_all(void);
228 * The filter function of a stream might want to modify the message
229 * before passing it to the handler and/or substreams. In this case,
230 * the filter should make a local copy of `struct log_msg`, call
231 * @log_pass_filtered() on it and return true, so that the original
232 * message will not be processed any further.
234 void log_pass_filtered(struct log_stream *ls, struct log_msg *m);
237 * === Logging to files
239 * All log files are open in append mode, which guarantees atomicity of write()
240 * even in multi-threaded programs.
243 struct log_stream *log_new_file(const char *path, uint flags); /** Create a stream bound to a log file. See `FF_xxx` for @flags. **/
244 struct log_stream *log_new_fd(int fd, uint flags); /** Create a stream bound to a file descriptor. See `FF_xxx` for @flags. **/
246 enum log_file_flag { /** Flags used for file-based logging **/
247 FF_FORMAT_NAME = 1, // Internal: Name contains strftime escapes
248 FF_CLOSE_FD = 2, // Close the fd with the stream (use with log_new_fd())
249 FF_FD2_FOLLOWS = 4, // Maintain stderr as a clone of this stream
253 * When a time-based name of the log file changes, the logger switches to a new
254 * log file automatically. This can be sometimes inconvenient, so you can use
255 * this function to disable the automatic switches. The calls to this function
258 void log_switch_disable(void);
259 void log_switch_enable(void); /** Negate the effect of log_switch_disable(). **/
260 int log_switch(void); /** Switch log files manually. **/
263 * Drop stderr if it is not already redirected to a log file.
264 * This is usually needed in daemons to make sure that the original
265 * stderr does not stay open (stdin and stdout are dropped by our
266 * <<daemon:,daemon setup functions>> automatically). More specifically,
267 * it makes stderr a clone of stdout.
269 void log_drop_stderr(void);
272 * === Logging to syslog
274 * This log stream uses the libc interface to the system logging daemon (`syslogd`).
275 * This interface has several limitations:
277 * * Syslog are poorer than our scheme, so they are translated with a slight
278 * loss of information (most importantly, the distinction between local and
279 * remote messages is lost). If you are interested in details, search the
280 * source for syslog_level().
281 * * Syslog options (especially logging of PID with each message) must be fixed
282 * during initialization of the logger
283 * * Syslog provides its own formatting, so we turn off all formatting flags
284 * of the LibUCW logger. You can override this manually by setting the @msgfmt
285 * field of the log stream, but the result won't be nice.
286 * * Syslog does not support timestamps with sub-second precision.
290 * Create a log stream for logging to a selected syslog facility.
291 * The @options are passed to openlog(). (Beware, due to limitations of the
292 * syslog interface in libc, the @options are shared for all syslog streams
293 * and they are applied when the first stream is created.)
295 struct log_stream *log_new_syslog(const char *facility, int options);
298 * Verify that a facility of the given name exists. Return 1 if it does, 0 otherwise.
300 int log_syslog_facility_exists(const char *facility);
303 * === Configuring log streams
305 * If you use the LibUCW mechanism for parsing config files, you can let your
306 * user configure arbitrary log streams in the Logging section of the config file
307 * (see examples in the default config file). LibUCW automatically verifies that
308 * the configuration is consistent (this is performed in the commit hook of the
309 * config section), but it opens the streams only upon request. The following
310 * functions can be used to control that.
313 /** Open a log stream configured under the specified name and increase its use count. **/
314 struct log_stream *log_new_configured(const char *name);
316 /** Open a log stream configured under the specified name and use it as the default destination. **/
317 void log_configured(const char *name);
320 * Verify that a stream called @name was configured. If it wasn't, return an error
321 * message. This is intended to be used in configuration commit hooks.
323 char *log_check_configured(const char *name);