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