vlog: Use system calls instead of stdio to write log files.
[openvswitch] / lib / vlog.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "vlog.h"
19 #include <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <syslog.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include "dirs.h"
32 #include "dynamic-string.h"
33 #include "sat-math.h"
34 #include "svec.h"
35 #include "timeval.h"
36 #include "unixctl.h"
37 #include "util.h"
38
39 VLOG_DEFINE_THIS_MODULE(vlog);
40
41 /* Name for each logging level. */
42 static const char *level_names[VLL_N_LEVELS] = {
43 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
44     VLOG_LEVELS
45 #undef VLOG_LEVEL
46 };
47
48 /* Syslog value for each logging level. */
49 static int syslog_levels[VLL_N_LEVELS] = {
50 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
51     VLOG_LEVELS
52 #undef VLOG_LEVEL
53 };
54
55 /* The log modules. */
56 #if USE_LINKER_SECTIONS
57 extern struct vlog_module *__start_vlog_modules[];
58 extern struct vlog_module *__stop_vlog_modules[];
59 #define vlog_modules __start_vlog_modules
60 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
61 #else
62 #define VLOG_MODULE VLOG_DEFINE_MODULE__
63 #include "vlog-modules.def"
64 #undef VLOG_MODULE
65
66 struct vlog_module *vlog_modules[] = {
67 #define VLOG_MODULE(NAME) &VLM_##NAME,
68 #include "vlog-modules.def"
69 #undef VLOG_MODULE
70 };
71 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
72 #endif
73
74 /* Information about each facility. */
75 struct facility {
76     const char *name;           /* Name. */
77     char *pattern;              /* Current pattern. */
78     bool default_pattern;       /* Whether current pattern is the default. */
79 };
80 static struct facility facilities[VLF_N_FACILITIES] = {
81 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
82     VLOG_FACILITIES
83 #undef VLOG_FACILITY
84 };
85
86 /* VLF_FILE configuration. */
87 static char *log_file_name;
88 static int log_fd = -1;
89
90 /* vlog initialized? */
91 static bool vlog_inited;
92
93 static void format_log_message(const struct vlog_module *, enum vlog_level,
94                                enum vlog_facility, unsigned int msg_num,
95                                const char *message, va_list, struct ds *)
96     PRINTF_FORMAT(5, 0);
97
98 /* Searches the 'n_names' in 'names'.  Returns the index of a match for
99  * 'target', or 'n_names' if no name matches. */
100 static size_t
101 search_name_array(const char *target, const char **names, size_t n_names)
102 {
103     size_t i;
104
105     for (i = 0; i < n_names; i++) {
106         assert(names[i]);
107         if (!strcasecmp(names[i], target)) {
108             break;
109         }
110     }
111     return i;
112 }
113
114 /* Returns the name for logging level 'level'. */
115 const char *
116 vlog_get_level_name(enum vlog_level level)
117 {
118     assert(level < VLL_N_LEVELS);
119     return level_names[level];
120 }
121
122 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
123  * is not the name of a logging level. */
124 enum vlog_level
125 vlog_get_level_val(const char *name)
126 {
127     return search_name_array(name, level_names, ARRAY_SIZE(level_names));
128 }
129
130 /* Returns the name for logging facility 'facility'. */
131 const char *
132 vlog_get_facility_name(enum vlog_facility facility)
133 {
134     assert(facility < VLF_N_FACILITIES);
135     return facilities[facility].name;
136 }
137
138 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
139  * not the name of a logging facility. */
140 enum vlog_facility
141 vlog_get_facility_val(const char *name)
142 {
143     size_t i;
144
145     for (i = 0; i < VLF_N_FACILITIES; i++) {
146         if (!strcasecmp(facilities[i].name, name)) {
147             break;
148         }
149     }
150     return i;
151 }
152
153 /* Returns the name for logging module 'module'. */
154 const char *
155 vlog_get_module_name(const struct vlog_module *module)
156 {
157     return module->name;
158 }
159
160 /* Returns the logging module named 'name', or NULL if 'name' is not the name
161  * of a logging module. */
162 struct vlog_module *
163 vlog_module_from_name(const char *name)
164 {
165     struct vlog_module **mp;
166
167     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
168         if (!strcasecmp(name, (*mp)->name)) {
169             return *mp;
170         }
171     }
172     return NULL;
173 }
174
175 /* Returns the current logging level for the given 'module' and 'facility'. */
176 enum vlog_level
177 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
178 {
179     assert(facility < VLF_N_FACILITIES);
180     return module->levels[facility];
181 }
182
183 static void
184 update_min_level(struct vlog_module *module)
185 {
186     enum vlog_facility facility;
187
188     module->min_level = VLL_OFF;
189     for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
190         if (log_fd >= 0 || facility != VLF_FILE) {
191             enum vlog_level level = module->levels[facility];
192             if (level > module->min_level) {
193                 module->min_level = level;
194             }
195         }
196     }
197 }
198
199 static void
200 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
201                    enum vlog_level level)
202 {
203     assert(facility >= 0 && facility < VLF_N_FACILITIES);
204     assert(level < VLL_N_LEVELS);
205
206     if (!module) {
207         struct vlog_module **mp;
208
209         for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
210             (*mp)->levels[facility] = level;
211             update_min_level(*mp);
212         }
213     } else {
214         module->levels[facility] = level;
215         update_min_level(module);
216     }
217 }
218
219 /* Sets the logging level for the given 'module' and 'facility' to 'level'.  A
220  * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
221  * across all modules or facilities, respectively. */
222 void
223 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
224                 enum vlog_level level)
225 {
226     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
227     if (facility == VLF_ANY_FACILITY) {
228         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
229             set_facility_level(facility, module, level);
230         }
231     } else {
232         set_facility_level(facility, module, level);
233     }
234 }
235
236 static void
237 do_set_pattern(enum vlog_facility facility, const char *pattern)
238 {
239     struct facility *f = &facilities[facility];
240     if (!f->default_pattern) {
241         free(f->pattern);
242     } else {
243         f->default_pattern = false;
244     }
245     f->pattern = xstrdup(pattern);
246 }
247
248 /* Sets the pattern for the given 'facility' to 'pattern'. */
249 void
250 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
251 {
252     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
253     if (facility == VLF_ANY_FACILITY) {
254         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
255             do_set_pattern(facility, pattern);
256         }
257     } else {
258         do_set_pattern(facility, pattern);
259     }
260 }
261
262 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
263  * log file has been set.  (A non-null return value does not assert that the
264  * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
265  * fails, it still sets the log file name.) */
266 const char *
267 vlog_get_log_file(void)
268 {
269     return log_file_name;
270 }
271
272 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
273  * default file name if 'file_name' is null.  Returns 0 if successful,
274  * otherwise a positive errno value. */
275 int
276 vlog_set_log_file(const char *file_name)
277 {
278     char *old_log_file_name;
279     struct vlog_module **mp;
280     int error;
281
282     /* Close old log file. */
283     if (log_fd >= 0) {
284         VLOG_INFO("closing log file");
285         close(log_fd);
286         log_fd = -1;
287     }
288
289     /* Update log file name and free old name.  The ordering is important
290      * because 'file_name' might be 'log_file_name' or some suffix of it. */
291     old_log_file_name = log_file_name;
292     log_file_name = (file_name
293                      ? xstrdup(file_name)
294                      : xasprintf("%s/%s.log", ovs_logdir(), program_name));
295     free(old_log_file_name);
296     file_name = NULL;           /* Might have been freed. */
297
298     /* Open new log file and update min_levels[] to reflect whether we actually
299      * have a log_file. */
300     log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
301     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
302         update_min_level(*mp);
303     }
304
305     /* Log success or failure. */
306     if (log_fd < 0) {
307         VLOG_WARN("failed to open %s for logging: %s",
308                   log_file_name, strerror(errno));
309         error = errno;
310     } else {
311         VLOG_INFO("opened log file %s", log_file_name);
312         error = 0;
313     }
314
315     return error;
316 }
317
318 /* Closes and then attempts to re-open the current log file.  (This is useful
319  * just after log rotation, to ensure that the new log file starts being used.)
320  * Returns 0 if successful, otherwise a positive errno value. */
321 int
322 vlog_reopen_log_file(void)
323 {
324     struct stat old, new;
325
326     /* Skip re-opening if there's nothing to reopen. */
327     if (!log_file_name) {
328         return 0;
329     }
330
331     /* Skip re-opening if it would be a no-op because the old and new files are
332      * the same.  (This avoids writing "closing log file" followed immediately
333      * by "opened log file".) */
334     if (log_fd >= 0
335         && !fstat(log_fd, &old)
336         && !stat(log_file_name, &new)
337         && old.st_dev == new.st_dev
338         && old.st_ino == new.st_ino) {
339         return 0;
340     }
341
342     return vlog_set_log_file(log_file_name);
343 }
344
345 /* Set debugging levels.  Returns null if successful, otherwise an error
346  * message that the caller must free(). */
347 char *
348 vlog_set_levels_from_string(const char *s_)
349 {
350     char *s = xstrdup(s_);
351     char *save_ptr = NULL;
352     char *msg = NULL;
353     char *word;
354
355     word = strtok_r(s, " ,:\t", &save_ptr);
356     if (word && !strcasecmp(word, "PATTERN")) {
357         enum vlog_facility facility;
358
359         word = strtok_r(NULL, " ,:\t", &save_ptr);
360         if (!word) {
361             msg = xstrdup("missing facility");
362             goto exit;
363         }
364
365         facility = (!strcasecmp(word, "ANY")
366                     ? VLF_ANY_FACILITY
367                     : vlog_get_facility_val(word));
368         if (facility == VLF_N_FACILITIES) {
369             msg = xasprintf("unknown facility \"%s\"", word);
370             goto exit;
371         }
372         vlog_set_pattern(facility, save_ptr);
373     } else {
374         struct vlog_module *module = NULL;
375         enum vlog_level level = VLL_N_LEVELS;
376         enum vlog_facility facility = VLF_N_FACILITIES;
377
378         for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
379             if (!strcasecmp(word, "ANY")) {
380                 continue;
381             } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
382                 if (facility != VLF_N_FACILITIES) {
383                     msg = xstrdup("cannot specify multiple facilities");
384                     goto exit;
385                 }
386                 facility = vlog_get_facility_val(word);
387             } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
388                 if (level != VLL_N_LEVELS) {
389                     msg = xstrdup("cannot specify multiple levels");
390                     goto exit;
391                 }
392                 level = vlog_get_level_val(word);
393             } else if (vlog_module_from_name(word)) {
394                 if (module) {
395                     msg = xstrdup("cannot specify multiple modules");
396                     goto exit;
397                 }
398                 module = vlog_module_from_name(word);
399             } else {
400                 msg = xasprintf("no facility, level, or module \"%s\"", word);
401                 goto exit;
402             }
403         }
404
405         if (facility == VLF_N_FACILITIES) {
406             facility = VLF_ANY_FACILITY;
407         }
408         if (level == VLL_N_LEVELS) {
409             level = VLL_DBG;
410         }
411         vlog_set_levels(module, facility, level);
412     }
413
414 exit:
415     free(s);
416     return msg;
417 }
418
419 /* If 'arg' is null, configure maximum verbosity.  Otherwise, sets
420  * configuration according to 'arg' (see vlog_set_levels_from_string()). */
421 void
422 vlog_set_verbosity(const char *arg)
423 {
424     if (arg) {
425         char *msg = vlog_set_levels_from_string(arg);
426         if (msg) {
427             ovs_fatal(0, "processing \"%s\": %s", arg, msg);
428         }
429     } else {
430         vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
431     }
432 }
433
434 static void
435 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
436                  void *aux OVS_UNUSED)
437 {
438     int i;
439
440     for (i = 1; i < argc; i++) {
441         char *msg = vlog_set_levels_from_string(argv[i]);
442         if (msg) {
443             unixctl_command_reply_error(conn, msg);
444             free(msg);
445             return;
446         }
447     }
448     unixctl_command_reply(conn, NULL);
449 }
450
451 static void
452 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
453                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
454 {
455     char *msg = vlog_get_levels();
456     unixctl_command_reply(conn, msg);
457     free(msg);
458 }
459
460 static void
461 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
462                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
463 {
464     if (log_file_name) {
465         int error = vlog_reopen_log_file();
466         if (error) {
467             unixctl_command_reply_error(conn, strerror(errno));
468         } else {
469             unixctl_command_reply(conn, NULL);
470         }
471     } else {
472         unixctl_command_reply_error(conn, "Logging to file not configured");
473     }
474 }
475
476 /* Initializes the logging subsystem and registers its unixctl server
477  * commands. */
478 void
479 vlog_init(void)
480 {
481     static char *program_name_copy;
482     time_t now;
483
484     if (vlog_inited) {
485         return;
486     }
487     vlog_inited = true;
488
489     /* openlog() is allowed to keep the pointer passed in, without making a
490      * copy.  The daemonize code sometimes frees and replaces 'program_name',
491      * so make a private copy just for openlog().  (We keep a pointer to the
492      * private copy to suppress memory leak warnings in case openlog() does
493      * make its own copy.) */
494     program_name_copy = program_name ? xstrdup(program_name) : NULL;
495     openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
496
497     now = time_wall();
498     if (now < 0) {
499         struct tm tm;
500         char s[128];
501
502         gmtime_r(&now, &tm);
503         strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S", &tm);
504         VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
505     }
506
507     unixctl_command_register(
508         "vlog/set", "{spec | PATTERN:facility:pattern}",
509         1, INT_MAX, vlog_unixctl_set, NULL);
510     unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
511     unixctl_command_register("vlog/reopen", "", 0, 0,
512                              vlog_unixctl_reopen, NULL);
513 }
514
515 /* Closes the logging subsystem. */
516 void
517 vlog_exit(void)
518 {
519     if (vlog_inited) {
520         closelog();
521         vlog_inited = false;
522     }
523 }
524
525 /* Print the current logging level for each module. */
526 char *
527 vlog_get_levels(void)
528 {
529     struct ds s = DS_EMPTY_INITIALIZER;
530     struct vlog_module **mp;
531     struct svec lines = SVEC_EMPTY_INITIALIZER;
532     char *line;
533     size_t i;
534
535     ds_put_format(&s, "                 console    syslog    file\n");
536     ds_put_format(&s, "                 -------    ------    ------\n");
537
538     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
539         line = xasprintf("%-16s  %4s       %4s       %4s\n",
540            vlog_get_module_name(*mp),
541            vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
542            vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
543            vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
544         svec_add_nocopy(&lines, line);
545     }
546
547     svec_sort(&lines);
548     SVEC_FOR_EACH (i, line, &lines) {
549         ds_put_cstr(&s, line);
550     }
551     svec_destroy(&lines);
552
553     return ds_cstr(&s);
554 }
555
556 /* Returns true if a log message emitted for the given 'module' and 'level'
557  * would cause some log output, false if that module and level are completely
558  * disabled. */
559 bool
560 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
561 {
562     return module->min_level >= level;
563 }
564
565 static const char *
566 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
567 {
568     if (*p == '{') {
569         size_t n = strcspn(p + 1, "}");
570         size_t n_copy = MIN(n, out_size - 1);
571         memcpy(out, p + 1, n_copy);
572         out[n_copy] = '\0';
573         p += n + 2;
574     } else {
575         ovs_strlcpy(out, def, out_size);
576     }
577     return p;
578 }
579
580 static void
581 format_log_message(const struct vlog_module *module, enum vlog_level level,
582                    enum vlog_facility facility, unsigned int msg_num,
583                    const char *message, va_list args_, struct ds *s)
584 {
585     char tmp[128];
586     va_list args;
587     const char *p;
588
589     ds_clear(s);
590     for (p = facilities[facility].pattern; *p != '\0'; ) {
591         enum { LEFT, RIGHT } justify = RIGHT;
592         int pad = '0';
593         size_t length, field, used;
594
595         if (*p != '%') {
596             ds_put_char(s, *p++);
597             continue;
598         }
599
600         p++;
601         if (*p == '-') {
602             justify = LEFT;
603             p++;
604         }
605         if (*p == '0') {
606             pad = '0';
607             p++;
608         }
609         field = 0;
610         while (isdigit((unsigned char)*p)) {
611             field = (field * 10) + (*p - '0');
612             p++;
613         }
614
615         length = s->length;
616         switch (*p++) {
617         case 'A':
618             ds_put_cstr(s, program_name);
619             break;
620         case 'c':
621             p = fetch_braces(p, "", tmp, sizeof tmp);
622             ds_put_cstr(s, vlog_get_module_name(module));
623             break;
624         case 'd':
625             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
626             ds_put_strftime(s, tmp, false);
627             break;
628         case 'D':
629             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
630             ds_put_strftime(s, tmp, true);
631             break;
632         case 'm':
633             /* Format user-supplied log message and trim trailing new-lines. */
634             length = s->length;
635             va_copy(args, args_);
636             ds_put_format_valist(s, message, args);
637             va_end(args);
638             while (s->length > length && s->string[s->length - 1] == '\n') {
639                 s->length--;
640             }
641             break;
642         case 'N':
643             ds_put_format(s, "%u", msg_num);
644             break;
645         case 'n':
646             ds_put_char(s, '\n');
647             break;
648         case 'p':
649             ds_put_cstr(s, vlog_get_level_name(level));
650             break;
651         case 'P':
652             ds_put_format(s, "%ld", (long int) getpid());
653             break;
654         case 'r':
655             ds_put_format(s, "%lld", time_msec() - time_boot_msec());
656             break;
657         case 't':
658             ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
659             break;
660         case 'T':
661             if (subprogram_name[0]) {
662                 ds_put_format(s, "(%s)", subprogram_name);
663             }
664             break;
665         default:
666             ds_put_char(s, p[-1]);
667             break;
668         }
669         used = s->length - length;
670         if (used < field) {
671             size_t n_pad = field - used;
672             if (justify == RIGHT) {
673                 ds_put_uninit(s, n_pad);
674                 memmove(&s->string[length + n_pad], &s->string[length], used);
675                 memset(&s->string[length], pad, n_pad);
676             } else {
677                 ds_put_char_multiple(s, pad, n_pad);
678             }
679         }
680     }
681 }
682
683 /* Writes 'message' to the log at the given 'level' and as coming from the
684  * given 'module'.
685  *
686  * Guaranteed to preserve errno. */
687 void
688 vlog_valist(const struct vlog_module *module, enum vlog_level level,
689             const char *message, va_list args)
690 {
691     bool log_to_console = module->levels[VLF_CONSOLE] >= level;
692     bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
693     bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
694     if (log_to_console || log_to_syslog || log_to_file) {
695         int save_errno = errno;
696         static unsigned int msg_num;
697         struct ds s;
698
699         vlog_init();
700
701         ds_init(&s);
702         ds_reserve(&s, 1024);
703         msg_num++;
704
705         if (log_to_console) {
706             format_log_message(module, level, VLF_CONSOLE, msg_num,
707                                message, args, &s);
708             ds_put_char(&s, '\n');
709             fputs(ds_cstr(&s), stderr);
710         }
711
712         if (log_to_syslog) {
713             int syslog_level = syslog_levels[level];
714             char *save_ptr = NULL;
715             char *line;
716
717             format_log_message(module, level, VLF_SYSLOG, msg_num,
718                                message, args, &s);
719             for (line = strtok_r(s.string, "\n", &save_ptr); line;
720                  line = strtok_r(NULL, "\n", &save_ptr)) {
721                 syslog(syslog_level, "%s", line);
722             }
723         }
724
725         if (log_to_file) {
726             format_log_message(module, level, VLF_FILE, msg_num,
727                                message, args, &s);
728             ds_put_char(&s, '\n');
729             write(log_fd, s.string, s.length);
730         }
731
732         ds_destroy(&s);
733         errno = save_errno;
734     }
735 }
736
737 void
738 vlog(const struct vlog_module *module, enum vlog_level level,
739      const char *message, ...)
740 {
741     va_list args;
742
743     va_start(args, message);
744     vlog_valist(module, level, message, args);
745     va_end(args);
746 }
747
748 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
749  * exit code.  Always writes the message to stderr, even if the console
750  * facility is disabled.
751  *
752  * Choose this function instead of vlog_abort_valist() if the daemon monitoring
753  * facility shouldn't automatically restart the current daemon.  */
754 void
755 vlog_fatal_valist(const struct vlog_module *module_,
756                   const char *message, va_list args)
757 {
758     struct vlog_module *module = (struct vlog_module *) module_;
759
760     /* Don't log this message to the console to avoid redundancy with the
761      * message written by the later ovs_fatal_valist(). */
762     module->levels[VLF_CONSOLE] = VLL_OFF;
763
764     vlog_valist(module, VLL_EMER, message, args);
765     ovs_fatal_valist(0, message, args);
766 }
767
768 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
769  * exit code.  Always writes the message to stderr, even if the console
770  * facility is disabled.
771  *
772  * Choose this function instead of vlog_abort() if the daemon monitoring
773  * facility shouldn't automatically restart the current daemon.  */
774 void
775 vlog_fatal(const struct vlog_module *module, const char *message, ...)
776 {
777     va_list args;
778
779     va_start(args, message);
780     vlog_fatal_valist(module, message, args);
781     va_end(args);
782 }
783
784 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
785  * writes the message to stderr, even if the console facility is disabled.
786  *
787  * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
788  * facility should automatically restart the current daemon.  */
789 void
790 vlog_abort_valist(const struct vlog_module *module_,
791                   const char *message, va_list args)
792 {
793     struct vlog_module *module = (struct vlog_module *) module_;
794
795     /* Don't log this message to the console to avoid redundancy with the
796      * message written by the later ovs_abort_valist(). */
797     module->levels[VLF_CONSOLE] = VLL_OFF;
798
799     vlog_valist(module, VLL_EMER, message, args);
800     ovs_abort_valist(0, message, args);
801 }
802
803 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
804  * writes the message to stderr, even if the console facility is disabled.
805  *
806  * Choose this function instead of vlog_fatal() if the daemon monitoring
807  * facility should automatically restart the current daemon.  */
808 void
809 vlog_abort(const struct vlog_module *module, const char *message, ...)
810 {
811     va_list args;
812
813     va_start(args, message);
814     vlog_abort_valist(module, message, args);
815     va_end(args);
816 }
817
818 bool
819 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
820                  struct vlog_rate_limit *rl)
821 {
822     if (!vlog_is_enabled(module, level)) {
823         return true;
824     }
825
826     if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
827         time_t now = time_now();
828         if (!rl->n_dropped) {
829             rl->first_dropped = now;
830         }
831         rl->last_dropped = now;
832         rl->n_dropped++;
833         return true;
834     }
835
836     if (rl->n_dropped) {
837         time_t now = time_now();
838         unsigned int first_dropped_elapsed = now - rl->first_dropped;
839         unsigned int last_dropped_elapsed = now - rl->last_dropped;
840
841         vlog(module, level,
842              "Dropped %u log messages in last %u seconds (most recently, "
843              "%u seconds ago) due to excessive rate",
844              rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
845
846         rl->n_dropped = 0;
847     }
848     return false;
849 }
850
851 void
852 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
853                 struct vlog_rate_limit *rl, const char *message, ...)
854 {
855     if (!vlog_should_drop(module, level, rl)) {
856         va_list args;
857
858         va_start(args, message);
859         vlog_valist(module, level, message, args);
860         va_end(args);
861     }
862 }
863
864 void
865 vlog_usage(void)
866 {
867     printf("\nLogging options:\n"
868            "  -v, --verbose=[SPEC]    set logging levels\n"
869            "  -v, --verbose           set maximum verbosity level\n"
870            "  --log-file[=FILE]       enable logging to specified FILE\n"
871            "                          (default: %s/%s.log)\n",
872            ovs_logdir(), program_name);
873 }