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