2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
27 #include <sys/types.h>
32 #include "dynamic-string.h"
41 VLOG_DEFINE_THIS_MODULE(vlog);
43 /* Name for each logging level. */
44 static const char *level_names[VLL_N_LEVELS] = {
45 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
50 /* Syslog value for each logging level. */
51 static int syslog_levels[VLL_N_LEVELS] = {
52 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
57 /* The log modules. */
58 #if USE_LINKER_SECTIONS
59 extern struct vlog_module *__start_vlog_modules[];
60 extern struct vlog_module *__stop_vlog_modules[];
61 #define vlog_modules __start_vlog_modules
62 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
64 #define VLOG_MODULE VLOG_DEFINE_MODULE__
65 #include "vlog-modules.def"
68 struct vlog_module *vlog_modules[] = {
69 #define VLOG_MODULE(NAME) &VLM_##NAME,
70 #include "vlog-modules.def"
73 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
76 /* Information about each facility. */
78 const char *name; /* Name. */
79 char *pattern; /* Current pattern. */
80 bool default_pattern; /* Whether current pattern is the default. */
82 static struct facility facilities[VLF_N_FACILITIES] = {
83 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
88 /* VLF_FILE configuration. */
89 static char *log_file_name;
90 static int log_fd = -1;
92 /* vlog initialized? */
93 static bool vlog_inited;
95 static void format_log_message(const struct vlog_module *, enum vlog_level,
96 enum vlog_facility, unsigned int msg_num,
97 const char *message, va_list, struct ds *)
99 static void vlog_write_file(struct ds *);
100 static void vlog_update_async_log_fd(void);
102 /* Searches the 'n_names' in 'names'. Returns the index of a match for
103 * 'target', or 'n_names' if no name matches. */
105 search_name_array(const char *target, const char **names, size_t n_names)
109 for (i = 0; i < n_names; i++) {
111 if (!strcasecmp(names[i], target)) {
118 /* Returns the name for logging level 'level'. */
120 vlog_get_level_name(enum vlog_level level)
122 assert(level < VLL_N_LEVELS);
123 return level_names[level];
126 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
127 * is not the name of a logging level. */
129 vlog_get_level_val(const char *name)
131 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
134 /* Returns the name for logging facility 'facility'. */
136 vlog_get_facility_name(enum vlog_facility facility)
138 assert(facility < VLF_N_FACILITIES);
139 return facilities[facility].name;
142 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
143 * not the name of a logging facility. */
145 vlog_get_facility_val(const char *name)
149 for (i = 0; i < VLF_N_FACILITIES; i++) {
150 if (!strcasecmp(facilities[i].name, name)) {
157 /* Returns the name for logging module 'module'. */
159 vlog_get_module_name(const struct vlog_module *module)
164 /* Returns the logging module named 'name', or NULL if 'name' is not the name
165 * of a logging module. */
167 vlog_module_from_name(const char *name)
169 struct vlog_module **mp;
171 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
172 if (!strcasecmp(name, (*mp)->name)) {
179 /* Returns the current logging level for the given 'module' and 'facility'. */
181 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
183 assert(facility < VLF_N_FACILITIES);
184 return module->levels[facility];
188 update_min_level(struct vlog_module *module)
190 enum vlog_facility facility;
192 module->min_level = VLL_OFF;
193 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
194 if (log_fd >= 0 || facility != VLF_FILE) {
195 enum vlog_level level = module->levels[facility];
196 if (level > module->min_level) {
197 module->min_level = level;
204 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
205 enum vlog_level level)
207 assert(facility >= 0 && facility < VLF_N_FACILITIES);
208 assert(level < VLL_N_LEVELS);
211 struct vlog_module **mp;
213 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
214 (*mp)->levels[facility] = level;
215 update_min_level(*mp);
218 module->levels[facility] = level;
219 update_min_level(module);
223 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
224 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
225 * across all modules or facilities, respectively. */
227 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
228 enum vlog_level level)
230 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
231 if (facility == VLF_ANY_FACILITY) {
232 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
233 set_facility_level(facility, module, level);
236 set_facility_level(facility, module, level);
241 do_set_pattern(enum vlog_facility facility, const char *pattern)
243 struct facility *f = &facilities[facility];
244 if (!f->default_pattern) {
247 f->default_pattern = false;
249 f->pattern = xstrdup(pattern);
252 /* Sets the pattern for the given 'facility' to 'pattern'. */
254 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
256 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
257 if (facility == VLF_ANY_FACILITY) {
258 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
259 do_set_pattern(facility, pattern);
262 do_set_pattern(facility, pattern);
266 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
267 * log file has been set. (A non-null return value does not assert that the
268 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
269 * fails, it still sets the log file name.) */
271 vlog_get_log_file(void)
273 return log_file_name;
276 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
277 * default file name if 'file_name' is null. Returns 0 if successful,
278 * otherwise a positive errno value. */
280 vlog_set_log_file(const char *file_name)
282 char *old_log_file_name;
283 struct vlog_module **mp;
286 /* Close old log file. */
288 VLOG_INFO("closing log file");
293 /* Update log file name and free old name. The ordering is important
294 * because 'file_name' might be 'log_file_name' or some suffix of it. */
295 old_log_file_name = log_file_name;
296 log_file_name = (file_name
298 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
299 free(old_log_file_name);
300 file_name = NULL; /* Might have been freed. */
302 /* Open new log file and update min_levels[] to reflect whether we actually
303 * have a log_file. */
304 log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
306 vlog_update_async_log_fd();
308 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
309 update_min_level(*mp);
312 /* Log success or failure. */
314 VLOG_WARN("failed to open %s for logging: %s",
315 log_file_name, strerror(errno));
318 VLOG_INFO("opened log file %s", log_file_name);
325 /* Closes and then attempts to re-open the current log file. (This is useful
326 * just after log rotation, to ensure that the new log file starts being used.)
327 * Returns 0 if successful, otherwise a positive errno value. */
329 vlog_reopen_log_file(void)
331 struct stat old, new;
333 /* Skip re-opening if there's nothing to reopen. */
334 if (!log_file_name) {
338 /* Skip re-opening if it would be a no-op because the old and new files are
339 * the same. (This avoids writing "closing log file" followed immediately
340 * by "opened log file".) */
342 && !fstat(log_fd, &old)
343 && !stat(log_file_name, &new)
344 && old.st_dev == new.st_dev
345 && old.st_ino == new.st_ino) {
349 return vlog_set_log_file(log_file_name);
352 /* Set debugging levels. Returns null if successful, otherwise an error
353 * message that the caller must free(). */
355 vlog_set_levels_from_string(const char *s_)
357 char *s = xstrdup(s_);
358 char *save_ptr = NULL;
362 word = strtok_r(s, " ,:\t", &save_ptr);
363 if (word && !strcasecmp(word, "PATTERN")) {
364 enum vlog_facility facility;
366 word = strtok_r(NULL, " ,:\t", &save_ptr);
368 msg = xstrdup("missing facility");
372 facility = (!strcasecmp(word, "ANY")
374 : vlog_get_facility_val(word));
375 if (facility == VLF_N_FACILITIES) {
376 msg = xasprintf("unknown facility \"%s\"", word);
379 vlog_set_pattern(facility, save_ptr);
381 struct vlog_module *module = NULL;
382 enum vlog_level level = VLL_N_LEVELS;
383 enum vlog_facility facility = VLF_N_FACILITIES;
385 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
386 if (!strcasecmp(word, "ANY")) {
388 } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
389 if (facility != VLF_N_FACILITIES) {
390 msg = xstrdup("cannot specify multiple facilities");
393 facility = vlog_get_facility_val(word);
394 } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
395 if (level != VLL_N_LEVELS) {
396 msg = xstrdup("cannot specify multiple levels");
399 level = vlog_get_level_val(word);
400 } else if (vlog_module_from_name(word)) {
402 msg = xstrdup("cannot specify multiple modules");
405 module = vlog_module_from_name(word);
407 msg = xasprintf("no facility, level, or module \"%s\"", word);
412 if (facility == VLF_N_FACILITIES) {
413 facility = VLF_ANY_FACILITY;
415 if (level == VLL_N_LEVELS) {
418 vlog_set_levels(module, facility, level);
426 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
427 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
429 vlog_set_verbosity(const char *arg)
432 char *msg = vlog_set_levels_from_string(arg);
434 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
437 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
442 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
443 void *aux OVS_UNUSED)
447 for (i = 1; i < argc; i++) {
448 char *msg = vlog_set_levels_from_string(argv[i]);
450 unixctl_command_reply_error(conn, msg);
455 unixctl_command_reply(conn, NULL);
459 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
460 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
462 char *msg = vlog_get_levels();
463 unixctl_command_reply(conn, msg);
468 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
469 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
472 int error = vlog_reopen_log_file();
474 unixctl_command_reply_error(conn, strerror(errno));
476 unixctl_command_reply(conn, NULL);
479 unixctl_command_reply_error(conn, "Logging to file not configured");
483 /* Initializes the logging subsystem and registers its unixctl server
488 static char *program_name_copy;
496 /* openlog() is allowed to keep the pointer passed in, without making a
497 * copy. The daemonize code sometimes frees and replaces 'program_name',
498 * so make a private copy just for openlog(). (We keep a pointer to the
499 * private copy to suppress memory leak warnings in case openlog() does
500 * make its own copy.) */
501 program_name_copy = program_name ? xstrdup(program_name) : NULL;
502 openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
510 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S", &tm);
511 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
514 unixctl_command_register(
515 "vlog/set", "{spec | PATTERN:facility:pattern}",
516 1, INT_MAX, vlog_unixctl_set, NULL);
517 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
518 unixctl_command_register("vlog/reopen", "", 0, 0,
519 vlog_unixctl_reopen, NULL);
522 /* Closes the logging subsystem. */
532 /* Print the current logging level for each module. */
534 vlog_get_levels(void)
536 struct ds s = DS_EMPTY_INITIALIZER;
537 struct vlog_module **mp;
538 struct svec lines = SVEC_EMPTY_INITIALIZER;
542 ds_put_format(&s, " console syslog file\n");
543 ds_put_format(&s, " ------- ------ ------\n");
545 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
546 line = xasprintf("%-16s %4s %4s %4s\n",
547 vlog_get_module_name(*mp),
548 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
549 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
550 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
551 svec_add_nocopy(&lines, line);
555 SVEC_FOR_EACH (i, line, &lines) {
556 ds_put_cstr(&s, line);
558 svec_destroy(&lines);
563 /* Returns true if a log message emitted for the given 'module' and 'level'
564 * would cause some log output, false if that module and level are completely
567 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
569 return module->min_level >= level;
573 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
576 size_t n = strcspn(p + 1, "}");
577 size_t n_copy = MIN(n, out_size - 1);
578 memcpy(out, p + 1, n_copy);
582 ovs_strlcpy(out, def, out_size);
588 format_log_message(const struct vlog_module *module, enum vlog_level level,
589 enum vlog_facility facility, unsigned int msg_num,
590 const char *message, va_list args_, struct ds *s)
597 for (p = facilities[facility].pattern; *p != '\0'; ) {
598 enum { LEFT, RIGHT } justify = RIGHT;
600 size_t length, field, used;
603 ds_put_char(s, *p++);
617 while (isdigit((unsigned char)*p)) {
618 field = (field * 10) + (*p - '0');
625 ds_put_cstr(s, program_name);
628 p = fetch_braces(p, "", tmp, sizeof tmp);
629 ds_put_cstr(s, vlog_get_module_name(module));
632 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
633 ds_put_strftime(s, tmp, false);
636 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
637 ds_put_strftime(s, tmp, true);
640 /* Format user-supplied log message and trim trailing new-lines. */
642 va_copy(args, args_);
643 ds_put_format_valist(s, message, args);
645 while (s->length > length && s->string[s->length - 1] == '\n') {
650 ds_put_format(s, "%u", msg_num);
653 ds_put_char(s, '\n');
656 ds_put_cstr(s, vlog_get_level_name(level));
659 ds_put_format(s, "%ld", (long int) getpid());
662 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
665 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
668 if (subprogram_name[0]) {
669 ds_put_format(s, "(%s)", subprogram_name);
673 ds_put_char(s, p[-1]);
676 used = s->length - length;
678 size_t n_pad = field - used;
679 if (justify == RIGHT) {
680 ds_put_uninit(s, n_pad);
681 memmove(&s->string[length + n_pad], &s->string[length], used);
682 memset(&s->string[length], pad, n_pad);
684 ds_put_char_multiple(s, pad, n_pad);
690 /* Writes 'message' to the log at the given 'level' and as coming from the
693 * Guaranteed to preserve errno. */
695 vlog_valist(const struct vlog_module *module, enum vlog_level level,
696 const char *message, va_list args)
698 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
699 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
700 bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
701 if (log_to_console || log_to_syslog || log_to_file) {
702 int save_errno = errno;
703 static unsigned int msg_num;
709 ds_reserve(&s, 1024);
712 if (log_to_console) {
713 format_log_message(module, level, VLF_CONSOLE, msg_num,
715 ds_put_char(&s, '\n');
716 fputs(ds_cstr(&s), stderr);
720 int syslog_level = syslog_levels[level];
721 char *save_ptr = NULL;
724 format_log_message(module, level, VLF_SYSLOG, msg_num,
726 for (line = strtok_r(s.string, "\n", &save_ptr); line;
727 line = strtok_r(NULL, "\n", &save_ptr)) {
728 syslog(syslog_level, "%s", line);
733 format_log_message(module, level, VLF_FILE, msg_num,
735 ds_put_char(&s, '\n');
745 vlog(const struct vlog_module *module, enum vlog_level level,
746 const char *message, ...)
750 va_start(args, message);
751 vlog_valist(module, level, message, args);
755 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
756 * exit code. Always writes the message to stderr, even if the console
757 * facility is disabled.
759 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
760 * facility shouldn't automatically restart the current daemon. */
762 vlog_fatal_valist(const struct vlog_module *module_,
763 const char *message, va_list args)
765 struct vlog_module *module = (struct vlog_module *) module_;
767 /* Don't log this message to the console to avoid redundancy with the
768 * message written by the later ovs_fatal_valist(). */
769 module->levels[VLF_CONSOLE] = VLL_OFF;
771 vlog_valist(module, VLL_EMER, message, args);
772 ovs_fatal_valist(0, message, args);
775 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
776 * exit code. Always writes the message to stderr, even if the console
777 * facility is disabled.
779 * Choose this function instead of vlog_abort() if the daemon monitoring
780 * facility shouldn't automatically restart the current daemon. */
782 vlog_fatal(const struct vlog_module *module, const char *message, ...)
786 va_start(args, message);
787 vlog_fatal_valist(module, message, args);
791 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
792 * writes the message to stderr, even if the console facility is disabled.
794 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
795 * facility should automatically restart the current daemon. */
797 vlog_abort_valist(const struct vlog_module *module_,
798 const char *message, va_list args)
800 struct vlog_module *module = (struct vlog_module *) module_;
802 /* Don't log this message to the console to avoid redundancy with the
803 * message written by the later ovs_abort_valist(). */
804 module->levels[VLF_CONSOLE] = VLL_OFF;
806 vlog_valist(module, VLL_EMER, message, args);
807 ovs_abort_valist(0, message, args);
810 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
811 * writes the message to stderr, even if the console facility is disabled.
813 * Choose this function instead of vlog_fatal() if the daemon monitoring
814 * facility should automatically restart the current daemon. */
816 vlog_abort(const struct vlog_module *module, const char *message, ...)
820 va_start(args, message);
821 vlog_abort_valist(module, message, args);
826 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
827 struct vlog_rate_limit *rl)
829 if (!vlog_is_enabled(module, level)) {
833 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
834 time_t now = time_now();
835 if (!rl->n_dropped) {
836 rl->first_dropped = now;
838 rl->last_dropped = now;
844 time_t now = time_now();
845 unsigned int first_dropped_elapsed = now - rl->first_dropped;
846 unsigned int last_dropped_elapsed = now - rl->last_dropped;
849 "Dropped %u log messages in last %u seconds (most recently, "
850 "%u seconds ago) due to excessive rate",
851 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
859 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
860 struct vlog_rate_limit *rl, const char *message, ...)
862 if (!vlog_should_drop(module, level, rl)) {
865 va_start(args, message);
866 vlog_valist(module, level, message, args);
874 printf("\nLogging options:\n"
875 " -v, --verbose=[SPEC] set logging levels\n"
876 " -v, --verbose set maximum verbosity level\n"
877 " --log-file[=FILE] enable logging to specified FILE\n"
878 " (default: %s/%s.log)\n",
879 ovs_logdir(), program_name);
882 static bool vlog_async_inited = false;
884 static worker_request_func vlog_async_write_request_cb;
887 vlog_write_file(struct ds *s)
889 if (worker_is_running()) {
890 worker_request(s->string, s->length,
891 &log_fd, vlog_async_inited ? 0 : 1,
892 vlog_async_write_request_cb, NULL, NULL);
893 vlog_async_inited = true;
895 write(log_fd, s->string, s->length);
900 vlog_update_async_log_fd(void)
902 if (worker_is_running()) {
903 worker_request(NULL, 0, &log_fd, 1, vlog_async_write_request_cb,
905 vlog_async_inited = true;
910 vlog_async_write_request_cb(struct ofpbuf *request,
911 const int *fd, size_t n_fds)
920 if (request->size > 0) {
921 write(log_fd, request->data, request->size);