]> mj.ucw.cz Git - libucw.git/blob - ucw/log.h
Opt: Documented opt and its interaction with conf
[libucw.git] / ucw / log.h
1 /*
2  *      UCW Library -- Logging
3  *
4  *      (c) 1997--2009 Martin Mares <mj@ucw.cz>
5  *      (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #ifndef _UCW_LOG_H_
12 #define _UCW_LOG_H_
13
14 #include <ucw/clists.h>
15
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_find_type ucw_log_find_type
23 #define log_new_configured ucw_log_new_configured
24 #define log_new_fd ucw_log_new_fd
25 #define log_new_file ucw_log_new_file
26 #define log_new_stream ucw_log_new_stream
27 #define log_new_syslog ucw_log_new_syslog
28 #define log_register_type ucw_log_register_type
29 #define log_rm_substream ucw_log_rm_substream
30 #define log_set_default_stream ucw_log_set_default_stream
31 #define log_set_format ucw_log_set_format
32 #define log_stream_by_flags ucw_log_stream_by_flags
33 #define log_switch ucw_log_switch
34 #define log_switch_disable ucw_log_switch_disable
35 #define log_switch_enable ucw_log_switch_enable
36 #define log_syslog_facility_exists ucw_log_syslog_facility_exists
37 #define log_type_name ucw_log_type_name
38 #endif
39
40 /*** === Messages and streams ***/
41
42 /**
43  * Inside the logging system, a log message is always represented by this structure.
44  **/
45 struct log_msg {
46   char *m;                              // The formatted message itself, ending with \n\0
47   int m_len;                            // Length without the \0
48   struct tm *tm;                        // Current time
49   struct timeval *tv;
50   uns flags;                            // Category and other flags as passed to msg()
51   char *raw_msg;                        // Unformatted parts
52   char *stime;
53   char *sutime;
54 };
55
56 /**
57  * Each stream is represented by an instance of this structure.
58  **/
59 struct log_stream {
60   char *name;                           // Optional name, allocated by the user (or constructor)
61   int regnum;                           // Stream number, already encoded by LS_SET_STRNUM(); -1 if closed
62   uns levels;                           // Bitmask of accepted severity levels (default: all)
63   uns types;                            // Bitmask of accepted message types (default: all)
64   uns msgfmt;                           // Formatting flags (LSFMT_xxx)
65   uns use_count;                        // Number of references to the stream
66   uns stream_flags;                     // Various other flags (LSFLAG_xxx)
67   int (*filter)(struct log_stream* ls, struct log_msg *m);      // Filter function, return non-zero to discard the message
68   clist substreams;                     // Pass the message to these streams (simple_list of pointers)
69   int (*handler)(struct log_stream *ls, struct log_msg *m);     // Called to commit the message, return 0 for success, errno on error
70   void (*close)(struct log_stream* ls); // Called upon log_close_stream()
71   void *user_data;                      // Not used by the logging system
72   // Private data of the handler follow
73 };
74
75 /**
76  * Formatting flags specifying the format of the message passed to the handler.
77  **/
78 enum ls_fmt {
79   LSFMT_LEVEL =         1,              // severity level (one letter) */
80   LSFMT_TIME =          2,              // date and time (YYYY-mm-dd HH:MM:SS) */
81   LSFMT_USEC =          4,              // also micro-seconds */
82   LSFMT_TITLE =         8,              // program title (log_title) */
83   LSFMT_PID =           16,             // program PID (log_pid) */
84   LSFMT_LOGNAME =       32,             // name of the log_stream */
85   LSFMT_TYPE =          64,             // message type
86 };
87
88 #define LSFMT_DEFAULT (LSFMT_LEVEL | LSFMT_TIME | LSFMT_TITLE | LSFMT_PID)      /** Default format **/
89
90 /**
91  * General stream flags.
92  **/
93 enum ls_flag {
94   LSFLAG_ERR_IS_FATAL = 1,              // When a logging error occurs, die() immediately
95   LSFLAG_ERR_REPORTED = 2,              // A logging error has been already reported on this stream
96 };
97
98 /***
99  * === Message flags
100  *
101  * The @flags parameter of msg() is divided to several groups of bits (from the LSB):
102  * message severity level (`L_xxx`), destination stream, message type
103  * and control bits (e.g., `L_SIGHANDLER`).
104  ***/
105
106 enum ls_flagbits {                      // Bit widths of groups
107   LS_LEVEL_BITS =       8,
108   LS_STRNUM_BITS =      16,
109   LS_TYPE_BITS =        5,
110   LS_CTRL_BITS =        3,
111 };
112
113 enum ls_flagpos {                       // Bit positions of groups
114   LS_LEVEL_POS =        0,
115   LS_STRNUM_POS =       LS_LEVEL_POS + LS_LEVEL_BITS,
116   LS_TYPE_POS =         LS_STRNUM_POS + LS_STRNUM_BITS,
117   LS_CTRL_POS =         LS_TYPE_POS + LS_TYPE_BITS,
118 };
119
120 enum ls_flagmasks {                     // Bit masks of groups
121   LS_LEVEL_MASK =       ((1 << LS_LEVEL_BITS) - 1) << LS_LEVEL_POS,
122   LS_STRNUM_MASK =      ((1 << LS_STRNUM_BITS) - 1) << LS_STRNUM_POS,
123   LS_TYPE_MASK =        ((1 << LS_TYPE_BITS) - 1) << LS_TYPE_POS,
124   LS_CTRL_MASK =        ((1 << LS_CTRL_BITS) - 1) << LS_CTRL_POS,
125 };
126
127 // "Get" macros (break flags to parts)
128 #define LS_GET_LEVEL(flags)     (((flags) & LS_LEVEL_MASK) >> LS_LEVEL_POS)     /** Extract severity level **/
129 #define LS_GET_STRNUM(flags)    (((flags) & LS_STRNUM_MASK) >> LS_STRNUM_POS)   /** Extract stream number **/
130 #define LS_GET_TYPE(flags)      (((flags) & LS_TYPE_MASK) >> LS_TYPE_POS)       /** Extract message type **/
131 #define LS_GET_CTRL(flags)      (((flags) & LS_CTRL_MASK) >> LS_CTRL_POS)       /** Extract control bits **/
132
133 // "Set" macros (parts to flags)
134 #define LS_SET_LEVEL(level)     ((level) << LS_LEVEL_POS)                       /** Convert severity level to flags **/
135 #define LS_SET_STRNUM(strnum)   ((strnum) << LS_STRNUM_POS)                     /** Convert stream number to flags **/
136 #define LS_SET_TYPE(type)       ((type) << LS_TYPE_POS)                         /** Convert message type to flags **/
137 #define LS_SET_CTRL(ctrl)       ((ctrl) << LS_CTRL_POS)                         /** Convert control bits to flags **/
138
139 #define LS_NUM_TYPES (1 << LS_TYPE_BITS)
140
141 /** Register a new message type and return the corresponding flag set (encoded by `LS_SET_TYPE`). **/
142 int log_register_type(const char *name);
143
144 /** Find a message type by name and return the corresponding flag set. Returns -1 if no such type found. **/
145 int log_find_type(const char *name);
146
147 /** Given a flag set, extract the message type ID and return its name. **/
148 char *log_type_name(uns flags);
149
150 /*** === Operations on streams ***/
151
152 /**
153  * Allocate a new log stream with no handler and an empty substream list.
154  * Since struct log_stream is followed by private data, @size bytes of memory are allocated
155  * for the whole structure. See below for functions creating specific stream types.
156  **/
157 struct log_stream *log_new_stream(size_t size);
158
159 /**
160  * Decrement the use count of a stream. If it becomes zero, close the stream,
161  * free its memory, and unlink all its substreams.
162  **/
163 int log_close_stream(struct log_stream *ls);
164
165 /**
166  * Get a new reference on an existing stream. For convenience, the return value is
167  * equal to the argument @ls.
168  **/
169 static inline struct log_stream *log_ref_stream(struct log_stream *ls)
170 {
171   ls->use_count++;
172   return ls;
173 }
174
175 /**
176  * Link a substream to a stream. The substream gains a reference, preventing
177  * it from being freed until it is unlinked.
178  **/
179 void log_add_substream(struct log_stream *where, struct log_stream *what);
180
181 /**
182  * Unlink all occurrences of a substream @what from stream @where. Each
183  * occurrence loses a reference. If @what is NULL, all substreams are unlinked.
184  * Returns the number of unlinked substreams.
185  **/
186 int log_rm_substream(struct log_stream *where, struct log_stream *what);
187
188 /**
189  * Set formatting flags of a given stream and all its substreams. The flags are
190  * AND'ed with @mask and OR'ed with @data.
191  **/
192 void log_set_format(struct log_stream *ls, uns mask, uns data);
193
194 /**
195  * Find a stream by its registration number (in the format of logging flags).
196  * Returns NULL if there is no such stream.
197  **/
198 struct log_stream *log_stream_by_flags(uns flags);
199
200 /** Return a pointer to the default stream (stream #0). **/
201 static inline struct log_stream *log_default_stream(void)
202 {
203   return log_stream_by_flags(0);
204 }
205
206 /**
207  * Make the specified stream the default destination.
208  *
209  * In fact, it takes the fixed default stream and attaches @ls as its only
210  * substream. If there were any other substreams, they are removed.
211  *
212  * Log streams created by log_file() or log_configured() are made default
213  * by calling this function.
214  **/
215 void log_set_default_stream(struct log_stream *ls);
216
217 /**
218  * Close all open streams, un-initialize the module, free all memory and
219  * reset the logging mechanism to use stderr only.
220  **/
221 void log_close_all(void);
222
223 /***
224  * === Logging to files
225  *
226  * All log files are open in append mode, which guarantees atomicity of write()
227  * even in multi-threaded programs.
228  ***/
229
230 struct log_stream *log_new_file(const char *path, uns flags);   /** Create a stream bound to a log file. See `FF_xxx` for @flags. **/
231 struct log_stream *log_new_fd(int fd, uns flags);               /** Create a stream bound to a file descriptor. See `FF_xxx` for @flags. **/
232
233 enum log_file_flag {            /** Flags used for file-based logging **/
234   FF_FORMAT_NAME = 1,           // Internal: Name contains strftime escapes
235   FF_CLOSE_FD = 2,              // Close the fd with the stream (use with log_new_fd())
236   FF_FD2_FOLLOWS = 4,           // Maintain stderr as a clone of this stream
237 };
238
239 /**
240  * When a time-based name of the log file changes, the logger switches to a new
241  * log file automatically. This can be sometimes inconvenient, so you can use
242  * this function to disable the automatic switches. The calls to this function
243  * can be nested.
244  **/
245 void log_switch_disable(void);
246 void log_switch_enable(void);           /** Negate the effect of log_switch_disable(). **/
247 int log_switch(void);                   /** Switch log files manually. **/
248
249 /***
250  * === Logging to syslog
251  *
252  * This log stream uses the libc interface to the system logging daemon (`syslogd`).
253  * This interface has several limitations:
254  *
255  *   * Syslog are poorer than our scheme, so they are translated with a slight
256  *     loss of information (most importantly, the distinction between local and
257  *     remote messages is lost). If you are interested in details, search the
258  *     source for syslog_level().
259  *   * Syslog options (especially logging of PID with each message) must be fixed
260  *     during initialization of the logger
261  *   * Syslog provides its own formatting, so we turn off all formatting flags
262  *     of the LibUCW logger. You can override this manually by setting the @msgfmt
263  *     field of the log stream, but the result won't be nice.
264  *   * Syslog does not support timestamps with sub-second precision.
265  ***/
266
267 /**
268  * Create a log stream for logging to a selected syslog facility.
269  * The @options are passed to openlog(). (Beware, due to limitations of the
270  * syslog interface in libc, the @options are shared for all syslog streams
271  * and they are applied when the first stream is created.)
272  **/
273 struct log_stream *log_new_syslog(const char *facility, int options);
274
275 /**
276  * Verify that a facility of the given name exists. Return 1 if it does, 0 otherwise.
277  **/
278 int log_syslog_facility_exists(const char *facility);
279
280 /***
281  * === Configuring log streams
282  *
283  * If you use the LibUCW mechanism for parsing config files, you can let your
284  * user configure arbitrary log streams in the Logging section of the config file
285  * (see examples in the default config file). LibUCW automatically verifies that
286  * the configuration is consistent (this is performed in the commit hook of the
287  * config section), but it opens the streams only upon request. The following
288  * functions can be used to control that.
289  ***/
290
291 /** Open a log stream configured under the specified name and increase its use count. **/
292 struct log_stream *log_new_configured(const char *name);
293
294 /** Open a log stream configured under the specified name and use it as the default destination. **/
295 void log_configured(const char *name);
296
297 /**
298  * Verify that a stream called @name was configured. If it wasn't, return an error
299  * message. This is intended to be used in configuration commit hooks.
300  **/
301 char *log_check_configured(const char *name);
302
303 #endif