2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016 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.
18 #include "openvswitch/vlog.h"
27 #include <sys/types.h>
31 #include "async-append.h"
34 #include "dynamic-string.h"
36 #include "ovs-thread.h"
38 #include "socket-util.h"
40 #include "syslog-direct.h"
41 #include "syslog-libc.h"
42 #include "syslog-provider.h"
47 VLOG_DEFINE_THIS_MODULE(vlog);
49 /* ovs_assert() logs the assertion message, so using ovs_assert() in this
50 * source file could cause recursion. */
52 #define ovs_assert use_assert_instead_of_ovs_assert_in_this_module
54 /* Name for each logging level. */
55 static const char *const level_names[VLL_N_LEVELS] = {
56 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL, RFC5424) #NAME,
61 /* Syslog value for each logging level. */
62 static const int syslog_levels[VLL_N_LEVELS] = {
63 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL, RFC5424) SYSLOG_LEVEL,
68 /* RFC 5424 defines specific values for each syslog level. Normally LOG_* use
69 * the same values. Verify that in fact they're the same. If we get assertion
70 * failures here then we need to define a separate rfc5424_levels[] array. */
71 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL, RFC5424) \
72 BUILD_ASSERT_DECL(SYSLOG_LEVEL == RFC5424);
76 /* Similarly, RFC 5424 defines the local0 facility with the value ordinarily
77 * used for LOG_LOCAL0. */
78 BUILD_ASSERT_DECL(LOG_LOCAL0 == (16 << 3));
80 /* The log modules. */
81 static struct ovs_list vlog_modules = OVS_LIST_INITIALIZER(&vlog_modules);
83 /* Protects the 'pattern' in all "struct destination"s, so that a race between
84 * changing and reading the pattern does not cause an access to freed
86 static struct ovs_rwlock pattern_rwlock = OVS_RWLOCK_INITIALIZER;
88 /* Information about each destination. */
90 const char *name; /* Name. */
91 char *pattern OVS_GUARDED_BY(pattern_rwlock); /* Current pattern. */
92 bool default_pattern; /* Whether current pattern is the default. */
94 static struct destination destinations[VLF_N_DESTINATIONS] = {
95 #define VLOG_DESTINATION(NAME, PATTERN) {#NAME, PATTERN, true},
97 #undef VLOG_DESTINATION
100 /* Sequence number for the message currently being composed. */
101 DEFINE_STATIC_PER_THREAD_DATA(unsigned int, msg_num, 0);
103 /* VLF_FILE configuration.
105 * All of the following is protected by 'log_file_mutex', which nests inside
107 static struct ovs_mutex log_file_mutex = OVS_MUTEX_INITIALIZER;
108 static char *log_file_name OVS_GUARDED_BY(log_file_mutex) = NULL;
109 static int log_fd OVS_GUARDED_BY(log_file_mutex) = -1;
110 static struct async_append *log_writer OVS_GUARDED_BY(log_file_mutex);
111 static bool log_async OVS_GUARDED_BY(log_file_mutex);
112 static struct syslogger *syslogger = NULL;
114 /* Syslog export configuration. */
115 static int syslog_fd OVS_GUARDED_BY(pattern_rwlock) = -1;
117 /* Log facility configuration. */
118 static atomic_int log_facility = ATOMIC_VAR_INIT(0);
120 /* Facility name and its value. */
121 struct vlog_facility {
122 char *name; /* Name. */
123 unsigned int value; /* Facility associated with 'name'. */
125 static struct vlog_facility vlog_facilities[] = {
129 {"daemon", LOG_DAEMON},
131 {"syslog", LOG_SYSLOG},
141 {"local0", LOG_LOCAL0},
142 {"local1", LOG_LOCAL1},
143 {"local2", LOG_LOCAL2},
144 {"local3", LOG_LOCAL3},
145 {"local4", LOG_LOCAL4},
146 {"local5", LOG_LOCAL5},
147 {"local6", LOG_LOCAL6},
148 {"local7", LOG_LOCAL7}
150 static bool vlog_facility_exists(const char* facility, int *value);
152 static void format_log_message(const struct vlog_module *, enum vlog_level,
154 const char *message, va_list, struct ds *)
155 OVS_PRINTF_FORMAT(4, 0);
157 /* Searches the 'n_names' in 'names'. Returns the index of a match for
158 * 'target', or 'n_names' if no name matches. */
160 search_name_array(const char *target, const char *const *names, size_t n_names)
164 for (i = 0; i < n_names; i++) {
166 if (!strcasecmp(names[i], target)) {
173 /* Returns the name for logging level 'level'. */
175 vlog_get_level_name(enum vlog_level level)
177 assert(level < VLL_N_LEVELS);
178 return level_names[level];
181 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
182 * is not the name of a logging level. */
184 vlog_get_level_val(const char *name)
186 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
189 /* Returns the name for logging destination 'destination'. */
191 vlog_get_destination_name(enum vlog_destination destination)
193 assert(destination < VLF_N_DESTINATIONS);
194 return destinations[destination].name;
197 /* Returns the logging destination named 'name', or VLF_N_DESTINATIONS if
198 * 'name' is not the name of a logging destination. */
199 enum vlog_destination
200 vlog_get_destination_val(const char *name)
204 for (i = 0; i < VLF_N_DESTINATIONS; i++) {
205 if (!strcasecmp(destinations[i].name, name)) {
213 vlog_insert_module(struct ovs_list *vlog)
215 list_insert(&vlog_modules, vlog);
218 /* Returns the name for logging module 'module'. */
220 vlog_get_module_name(const struct vlog_module *module)
225 /* Returns the logging module named 'name', or NULL if 'name' is not the name
226 * of a logging module. */
228 vlog_module_from_name(const char *name)
230 struct vlog_module *mp;
232 LIST_FOR_EACH (mp, list, &vlog_modules) {
233 if (!strcasecmp(name, mp->name)) {
241 /* Returns the current logging level for the given 'module' and
244 vlog_get_level(const struct vlog_module *module,
245 enum vlog_destination destination)
247 assert(destination < VLF_N_DESTINATIONS);
248 return module->levels[destination];
252 update_min_level(struct vlog_module *module) OVS_REQUIRES(&log_file_mutex)
254 enum vlog_destination destination;
256 module->min_level = VLL_OFF;
257 for (destination = 0; destination < VLF_N_DESTINATIONS; destination++) {
258 if (log_fd >= 0 || destination != VLF_FILE) {
259 enum vlog_level level = module->levels[destination];
260 if (level > module->min_level) {
261 module->min_level = level;
268 set_destination_level(enum vlog_destination destination,
269 struct vlog_module *module, enum vlog_level level)
271 assert(destination >= 0 && destination < VLF_N_DESTINATIONS);
272 assert(level < VLL_N_LEVELS);
274 ovs_mutex_lock(&log_file_mutex);
276 struct vlog_module *mp;
277 LIST_FOR_EACH (mp, list, &vlog_modules) {
278 mp->levels[destination] = level;
279 update_min_level(mp);
282 module->levels[destination] = level;
283 update_min_level(module);
285 ovs_mutex_unlock(&log_file_mutex);
288 /* Sets the logging level for the given 'module' and 'destination' to 'level'.
289 * A null 'module' or a 'destination' of VLF_ANY_DESTINATION is treated as a
290 * wildcard across all modules or destinations, respectively. */
292 vlog_set_levels(struct vlog_module *module, enum vlog_destination destination,
293 enum vlog_level level)
295 assert(destination < VLF_N_DESTINATIONS ||
296 destination == VLF_ANY_DESTINATION);
297 if (destination == VLF_ANY_DESTINATION) {
298 for (destination = 0; destination < VLF_N_DESTINATIONS;
300 set_destination_level(destination, module, level);
303 set_destination_level(destination, module, level);
308 do_set_pattern(enum vlog_destination destination, const char *pattern)
310 struct destination *f = &destinations[destination];
312 ovs_rwlock_wrlock(&pattern_rwlock);
313 if (!f->default_pattern) {
316 f->default_pattern = false;
318 f->pattern = xstrdup(pattern);
319 ovs_rwlock_unlock(&pattern_rwlock);
322 /* Sets the pattern for the given 'destination' to 'pattern'. */
324 vlog_set_pattern(enum vlog_destination destination, const char *pattern)
326 assert(destination < VLF_N_DESTINATIONS ||
327 destination == VLF_ANY_DESTINATION);
328 if (destination == VLF_ANY_DESTINATION) {
329 for (destination = 0; destination < VLF_N_DESTINATIONS;
331 do_set_pattern(destination, pattern);
334 do_set_pattern(destination, pattern);
338 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
339 * default file name if 'file_name' is null. Returns 0 if successful,
340 * otherwise a positive errno value. */
342 vlog_set_log_file(const char *file_name)
344 char *new_log_file_name;
345 struct vlog_module *mp;
346 struct stat old_stat;
347 struct stat new_stat;
352 /* Open new log file. */
353 new_log_file_name = (file_name
355 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
356 new_log_fd = open(new_log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
357 if (new_log_fd < 0) {
358 VLOG_WARN("failed to open %s for logging: %s",
359 new_log_file_name, ovs_strerror(errno));
360 free(new_log_file_name);
364 /* If the new log file is the same one we already have open, bail out. */
365 ovs_mutex_lock(&log_file_mutex);
366 same_file = (log_fd >= 0
368 && !fstat(log_fd, &old_stat)
369 && !fstat(new_log_fd, &new_stat)
370 && old_stat.st_dev == new_stat.st_dev
371 && old_stat.st_ino == new_stat.st_ino);
372 ovs_mutex_unlock(&log_file_mutex);
375 free(new_log_file_name);
379 /* Log closing old log file (we can't log while holding log_file_mutex). */
380 ovs_mutex_lock(&log_file_mutex);
381 log_close = log_fd >= 0;
382 ovs_mutex_unlock(&log_file_mutex);
384 VLOG_INFO("closing log file");
387 /* Close old log file, if any, and install new one. */
388 ovs_mutex_lock(&log_file_mutex);
392 async_append_destroy(log_writer);
395 log_file_name = xstrdup(new_log_file_name);
398 log_writer = async_append_create(new_log_fd);
401 LIST_FOR_EACH (mp, list, &vlog_modules) {
402 update_min_level(mp);
404 ovs_mutex_unlock(&log_file_mutex);
406 /* Log opening new log file (we can't log while holding log_file_mutex). */
407 VLOG_INFO("opened log file %s", new_log_file_name);
408 free(new_log_file_name);
413 /* Closes and then attempts to re-open the current log file. (This is useful
414 * just after log rotation, to ensure that the new log file starts being used.)
415 * Returns 0 if successful, otherwise a positive errno value. */
417 vlog_reopen_log_file(void)
421 ovs_mutex_lock(&log_file_mutex);
422 fn = log_file_name ? xstrdup(log_file_name) : NULL;
423 ovs_mutex_unlock(&log_file_mutex);
426 int error = vlog_set_log_file(fn);
435 /* In case a log file exists, change its owner to new 'user' and 'group'.
437 * This is useful for handling cases where the --log-file option is
438 * specified ahead of the --user option. */
440 vlog_change_owner_unix(uid_t user, gid_t group)
442 struct ds err = DS_EMPTY_INITIALIZER;
445 ovs_mutex_lock(&log_file_mutex);
446 error = log_file_name ? chown(log_file_name, user, group) : 0;
448 /* Build the error message. We can not call VLOG_FATAL directly
449 * here because VLOG_FATAL() will try again to to acquire
450 * 'log_file_mutex' lock, causing deadlock.
452 ds_put_format(&err, "Failed to change %s ownership: %s.",
453 log_file_name, ovs_strerror(errno));
455 ovs_mutex_unlock(&log_file_mutex);
458 VLOG_FATAL("%s", ds_steal_cstr(&err));
463 /* Set debugging levels. Returns null if successful, otherwise an error
464 * message that the caller must free(). */
466 vlog_set_levels_from_string(const char *s_)
468 char *s = xstrdup(s_);
469 char *save_ptr = NULL;
473 word = strtok_r(s, " ,:\t", &save_ptr);
474 if (word && !strcasecmp(word, "PATTERN")) {
475 enum vlog_destination destination;
477 word = strtok_r(NULL, " ,:\t", &save_ptr);
479 msg = xstrdup("missing destination");
483 destination = (!strcasecmp(word, "ANY")
484 ? VLF_ANY_DESTINATION
485 : vlog_get_destination_val(word));
486 if (destination == VLF_N_DESTINATIONS) {
487 msg = xasprintf("unknown destination \"%s\"", word);
490 vlog_set_pattern(destination, save_ptr);
491 } else if (word && !strcasecmp(word, "FACILITY")) {
494 if (!vlog_facility_exists(save_ptr, &value)) {
495 msg = xstrdup("invalid facility");
498 atomic_store_explicit(&log_facility, value, memory_order_relaxed);
500 struct vlog_module *module = NULL;
501 enum vlog_level level = VLL_N_LEVELS;
502 enum vlog_destination destination = VLF_N_DESTINATIONS;
504 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
505 if (!strcasecmp(word, "ANY")) {
507 } else if (vlog_get_destination_val(word) != VLF_N_DESTINATIONS) {
508 if (destination != VLF_N_DESTINATIONS) {
509 msg = xstrdup("cannot specify multiple destinations");
512 destination = vlog_get_destination_val(word);
513 } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
514 if (level != VLL_N_LEVELS) {
515 msg = xstrdup("cannot specify multiple levels");
518 level = vlog_get_level_val(word);
519 } else if (vlog_module_from_name(word)) {
521 msg = xstrdup("cannot specify multiple modules");
524 module = vlog_module_from_name(word);
526 msg = xasprintf("no destination, level, or module \"%s\"",
532 if (destination == VLF_N_DESTINATIONS) {
533 destination = VLF_ANY_DESTINATION;
535 if (level == VLL_N_LEVELS) {
538 vlog_set_levels(module, destination, level);
546 /* Set debugging levels. Abort with an error message if 's' is invalid. */
548 vlog_set_levels_from_string_assert(const char *s)
550 char *error = vlog_set_levels_from_string(s);
552 ovs_fatal(0, "%s", error);
556 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
557 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
559 vlog_set_verbosity(const char *arg)
562 char *msg = vlog_set_levels_from_string(arg);
564 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
567 vlog_set_levels(NULL, VLF_ANY_DESTINATION, VLL_DBG);
572 vlog_set_syslog_method(const char *method)
575 /* Set syslogger only, if one is not already set. This effectively
576 * means that only the first --syslog-method argument is honored. */
580 if (!strcmp(method, "libc")) {
581 syslogger = syslog_libc_create();
582 } else if (!strncmp(method, "udp:", 4) || !strncmp(method, "unix:", 5)) {
583 syslogger = syslog_direct_create(method);
585 ovs_fatal(0, "unsupported syslog method '%s'", method);
589 /* Set the vlog udp syslog target. */
591 vlog_set_syslog_target(const char *target)
595 inet_open_active(SOCK_DGRAM, target, 0, NULL, &new_fd, 0);
597 ovs_rwlock_wrlock(&pattern_rwlock);
598 if (syslog_fd >= 0) {
602 ovs_rwlock_unlock(&pattern_rwlock);
605 /* Returns 'false' if 'facility' is not a valid string. If 'facility'
606 * is a valid string, sets 'value' with the integer value of 'facility'
607 * and returns 'true'. */
609 vlog_facility_exists(const char* facility, int *value)
612 for (i = 0; i < ARRAY_SIZE(vlog_facilities); i++) {
613 if (!strcasecmp(vlog_facilities[i].name, facility)) {
614 *value = vlog_facilities[i].value;
622 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
623 void *aux OVS_UNUSED)
627 for (i = 1; i < argc; i++) {
628 char *msg = vlog_set_levels_from_string(argv[i]);
630 unixctl_command_reply_error(conn, msg);
635 unixctl_command_reply(conn, NULL);
639 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
640 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
642 char *msg = vlog_get_levels();
643 unixctl_command_reply(conn, msg);
648 vlog_unixctl_list_pattern(struct unixctl_conn *conn, int argc OVS_UNUSED,
649 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
653 msg = vlog_get_patterns();
654 unixctl_command_reply(conn, msg);
659 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
660 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
664 ovs_mutex_lock(&log_file_mutex);
665 has_log_file = log_file_name != NULL;
666 ovs_mutex_unlock(&log_file_mutex);
669 int error = vlog_reopen_log_file();
671 unixctl_command_reply_error(conn, ovs_strerror(errno));
673 unixctl_command_reply(conn, NULL);
676 unixctl_command_reply_error(conn, "Logging to file not configured");
681 vlog_unixctl_close(struct unixctl_conn *conn, int argc OVS_UNUSED,
682 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
684 ovs_mutex_lock(&log_file_mutex);
689 async_append_destroy(log_writer);
692 struct vlog_module *mp;
693 LIST_FOR_EACH (mp, list, &vlog_modules) {
694 update_min_level(mp);
697 ovs_mutex_unlock(&log_file_mutex);
699 unixctl_command_reply(conn, NULL);
703 set_all_rate_limits(bool enable)
705 struct vlog_module *mp;
707 LIST_FOR_EACH (mp, list, &vlog_modules) {
708 mp->honor_rate_limits = enable;
713 set_rate_limits(struct unixctl_conn *conn, int argc,
714 const char *argv[], bool enable)
719 for (i = 1; i < argc; i++) {
720 if (!strcasecmp(argv[i], "ANY")) {
721 set_all_rate_limits(enable);
723 struct vlog_module *module = vlog_module_from_name(argv[i]);
725 unixctl_command_reply_error(conn, "unknown module");
728 module->honor_rate_limits = enable;
732 set_all_rate_limits(enable);
734 unixctl_command_reply(conn, NULL);
738 vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
739 const char *argv[], void *aux OVS_UNUSED)
741 set_rate_limits(conn, argc, argv, true);
745 vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
746 const char *argv[], void *aux OVS_UNUSED)
748 set_rate_limits(conn, argc, argv, false);
751 /* Initializes the logging subsystem and registers its unixctl server
756 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
758 if (ovsthread_once_start(&once)) {
761 bool print_syslog_target_deprecation;
763 /* Do initialization work that needs to be done before any logging
764 * occurs. We want to keep this really minimal because any attempt to
765 * log anything before calling ovsthread_once_done() will deadlock. */
766 atomic_read_explicit(&log_facility, &facility, memory_order_relaxed);
768 syslogger = syslog_libc_create();
770 syslogger->class->openlog(syslogger, facility ? facility : LOG_DAEMON);
771 ovsthread_once_done(&once);
773 /* Now do anything that we want to happen only once but doesn't have to
774 * finish before we start logging. */
776 now = time_wall_msec();
778 char *s = xastrftime_msec("%a, %d %b %Y %H:%M:%S", now, true);
779 VLOG_ERR("current time is negative: %s (%lld)", s, now);
783 unixctl_command_register(
784 "vlog/set", "{spec | PATTERN:destination:pattern}",
785 1, INT_MAX, vlog_unixctl_set, NULL);
786 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list,
788 unixctl_command_register("vlog/list-pattern", "", 0, 0,
789 vlog_unixctl_list_pattern, NULL);
790 unixctl_command_register("vlog/enable-rate-limit", "[module]...",
791 0, INT_MAX, vlog_enable_rate_limit, NULL);
792 unixctl_command_register("vlog/disable-rate-limit", "[module]...",
793 0, INT_MAX, vlog_disable_rate_limit, NULL);
794 unixctl_command_register("vlog/reopen", "", 0, 0,
795 vlog_unixctl_reopen, NULL);
796 unixctl_command_register("vlog/close", "", 0, 0,
797 vlog_unixctl_close, NULL);
799 ovs_rwlock_rdlock(&pattern_rwlock);
800 print_syslog_target_deprecation = syslog_fd >= 0;
801 ovs_rwlock_unlock(&pattern_rwlock);
803 if (print_syslog_target_deprecation) {
804 VLOG_WARN("--syslog-target flag is deprecated, use "
805 "--syslog-method instead");
810 /* Enables VLF_FILE log output to be written asynchronously to disk.
811 * Asynchronous file writes avoid blocking the process in the case of a busy
812 * disk, but on the other hand they are less robust: there is a chance that the
813 * write will not make it to the log file if the process crashes soon after the
816 vlog_enable_async(void)
818 ovs_mutex_lock(&log_file_mutex);
820 if (log_fd >= 0 && !log_writer) {
821 log_writer = async_append_create(log_fd);
823 ovs_mutex_unlock(&log_file_mutex);
826 /* Print the current logging level for each module. */
828 vlog_get_levels(void)
830 struct ds s = DS_EMPTY_INITIALIZER;
831 struct vlog_module *mp;
832 struct svec lines = SVEC_EMPTY_INITIALIZER;
836 ds_put_format(&s, " console syslog file\n");
837 ds_put_format(&s, " ------- ------ ------\n");
839 LIST_FOR_EACH (mp, list, &vlog_modules) {
843 ds_put_format(&line, "%-16s %4s %4s %4s",
844 vlog_get_module_name(mp),
845 vlog_get_level_name(vlog_get_level(mp, VLF_CONSOLE)),
846 vlog_get_level_name(vlog_get_level(mp, VLF_SYSLOG)),
847 vlog_get_level_name(vlog_get_level(mp, VLF_FILE)));
848 if (!mp->honor_rate_limits) {
849 ds_put_cstr(&line, " (rate limiting disabled)");
851 ds_put_char(&line, '\n');
853 svec_add_nocopy(&lines, ds_steal_cstr(&line));
857 SVEC_FOR_EACH (i, line, &lines) {
858 ds_put_cstr(&s, line);
860 svec_destroy(&lines);
865 /* Returns as a string current logging patterns for each destination.
866 * This string must be released by caller. */
868 vlog_get_patterns(void)
870 struct ds ds = DS_EMPTY_INITIALIZER;
871 enum vlog_destination destination;
873 ovs_rwlock_rdlock(&pattern_rwlock);
874 ds_put_format(&ds, " prefix format\n");
875 ds_put_format(&ds, " ------ ------\n");
877 for (destination = 0; destination < VLF_N_DESTINATIONS; destination++) {
878 struct destination *f = &destinations[destination];
879 const char *prefix = "none";
881 if (destination == VLF_SYSLOG && syslogger) {
882 prefix = syslog_get_prefix(syslogger);
884 ds_put_format(&ds, "%-7s %-32s %s\n", f->name, prefix, f->pattern);
886 ovs_rwlock_unlock(&pattern_rwlock);
891 /* Returns true if a log message emitted for the given 'module' and 'level'
892 * would cause some log output, false if that module and level are completely
895 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
897 return module->min_level >= level;
901 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
904 size_t n = strcspn(p + 1, "}");
905 size_t n_copy = MIN(n, out_size - 1);
906 memcpy(out, p + 1, n_copy);
910 ovs_strlcpy(out, def, out_size);
916 format_log_message(const struct vlog_module *module, enum vlog_level level,
917 const char *pattern, const char *message,
918 va_list args_, struct ds *s)
926 for (p = pattern; *p != '\0'; ) {
927 const char *subprogram_name;
928 enum { LEFT, RIGHT } justify = RIGHT;
930 size_t length, field, used;
933 ds_put_char(s, *p++);
947 while (isdigit((unsigned char)*p)) {
948 field = (field * 10) + (*p - '0');
955 ds_put_cstr(s, program_name);
958 atomic_read_explicit(&log_facility, &facility,
959 memory_order_relaxed);
960 facility = facility ? facility : LOG_LOCAL0;
961 ds_put_format(s, "%d", facility + syslog_levels[level]);
964 p = fetch_braces(p, "", tmp, sizeof tmp);
965 ds_put_cstr(s, vlog_get_module_name(module));
968 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
969 ds_put_strftime_msec(s, tmp, time_wall_msec(), false);
972 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
973 ds_put_strftime_msec(s, tmp, time_wall_msec(), true);
976 gethostname(tmp, sizeof tmp);
977 tmp[sizeof tmp - 1] = '\0';
981 /* Format user-supplied log message and trim trailing new-lines. */
983 va_copy(args, args_);
984 ds_put_format_valist(s, message, args);
986 while (s->length > length && s->string[s->length - 1] == '\n') {
991 ds_put_format(s, "%u", *msg_num_get_unsafe());
994 ds_put_char(s, '\n');
997 ds_put_cstr(s, vlog_get_level_name(level));
1000 ds_put_format(s, "%ld", (long int) getpid());
1003 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
1006 subprogram_name = get_subprogram_name();
1007 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
1010 subprogram_name = get_subprogram_name();
1011 if (subprogram_name[0]) {
1012 ds_put_format(s, "(%s)", subprogram_name);
1016 ds_put_char(s, p[-1]);
1019 used = s->length - length;
1021 size_t n_pad = field - used;
1022 if (justify == RIGHT) {
1023 ds_put_uninit(s, n_pad);
1024 memmove(&s->string[length + n_pad], &s->string[length], used);
1025 memset(&s->string[length], pad, n_pad);
1027 ds_put_char_multiple(s, pad, n_pad);
1033 /* Exports the given 'syslog_message' to the configured udp syslog sink. */
1035 send_to_syslog_fd(const char *s, size_t length)
1036 OVS_REQ_RDLOCK(pattern_rwlock)
1038 static size_t max_length = SIZE_MAX;
1039 size_t send_len = MIN(length, max_length);
1041 while (write(syslog_fd, s, send_len) < 0 && errno == EMSGSIZE) {
1042 send_len -= send_len / 20;
1043 max_length = send_len;
1047 /* Writes 'message' to the log at the given 'level' and as coming from the
1050 * Guaranteed to preserve errno. */
1052 vlog_valist(const struct vlog_module *module, enum vlog_level level,
1053 const char *message, va_list args)
1055 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
1056 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
1059 ovs_mutex_lock(&log_file_mutex);
1060 log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
1061 ovs_mutex_unlock(&log_file_mutex);
1062 if (log_to_console || log_to_syslog || log_to_file) {
1063 int save_errno = errno;
1069 ds_reserve(&s, 1024);
1072 ovs_rwlock_rdlock(&pattern_rwlock);
1073 if (log_to_console) {
1074 format_log_message(module, level,
1075 destinations[VLF_CONSOLE].pattern, message,
1077 ds_put_char(&s, '\n');
1078 fputs(ds_cstr(&s), stderr);
1081 if (log_to_syslog) {
1082 int syslog_level = syslog_levels[level];
1083 char *save_ptr = NULL;
1087 format_log_message(module, level, destinations[VLF_SYSLOG].pattern,
1089 for (line = strtok_r(s.string, "\n", &save_ptr); line;
1090 line = strtok_r(NULL, "\n", &save_ptr)) {
1091 atomic_read_explicit(&log_facility, &facility,
1092 memory_order_relaxed);
1093 syslogger->class->syslog(syslogger, syslog_level|facility, line);
1096 if (syslog_fd >= 0) {
1097 format_log_message(module, level,
1098 "<%B>1 %D{%Y-%m-%dT%H:%M:%S.###Z} "
1099 "%E %A %P %c - \xef\xbb\xbf%m",
1101 send_to_syslog_fd(ds_cstr(&s), s.length);
1106 format_log_message(module, level, destinations[VLF_FILE].pattern,
1108 ds_put_char(&s, '\n');
1110 ovs_mutex_lock(&log_file_mutex);
1113 async_append_write(log_writer, s.string, s.length);
1114 if (level == VLL_EMER) {
1115 async_append_flush(log_writer);
1118 ignore(write(log_fd, s.string, s.length));
1121 ovs_mutex_unlock(&log_file_mutex);
1123 ovs_rwlock_unlock(&pattern_rwlock);
1131 vlog(const struct vlog_module *module, enum vlog_level level,
1132 const char *message, ...)
1136 va_start(args, message);
1137 vlog_valist(module, level, message, args);
1141 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1142 * exit code. Always writes the message to stderr, even if the console
1143 * destination is disabled.
1145 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
1146 * facility shouldn't automatically restart the current daemon. */
1148 vlog_fatal_valist(const struct vlog_module *module_,
1149 const char *message, va_list args)
1151 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
1153 /* Don't log this message to the console to avoid redundancy with the
1154 * message written by the later ovs_fatal_valist(). */
1155 module->levels[VLF_CONSOLE] = VLL_OFF;
1157 vlog_valist(module, VLL_EMER, message, args);
1158 ovs_fatal_valist(0, message, args);
1161 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1162 * exit code. Always writes the message to stderr, even if the console
1163 * destination is disabled.
1165 * Choose this function instead of vlog_abort() if the daemon monitoring
1166 * facility shouldn't automatically restart the current daemon. */
1168 vlog_fatal(const struct vlog_module *module, const char *message, ...)
1172 va_start(args, message);
1173 vlog_fatal_valist(module, message, args);
1177 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
1178 * writes the message to stderr, even if the console destination is disabled.
1180 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
1181 * facility should automatically restart the current daemon. */
1183 vlog_abort_valist(const struct vlog_module *module_,
1184 const char *message, va_list args)
1186 struct vlog_module *module = (struct vlog_module *) module_;
1188 /* Don't log this message to the console to avoid redundancy with the
1189 * message written by the later ovs_abort_valist(). */
1190 module->levels[VLF_CONSOLE] = VLL_OFF;
1192 vlog_valist(module, VLL_EMER, message, args);
1193 ovs_abort_valist(0, message, args);
1196 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
1197 * writes the message to stderr, even if the console destination is disabled.
1199 * Choose this function instead of vlog_fatal() if the daemon monitoring
1200 * facility should automatically restart the current daemon. */
1202 vlog_abort(const struct vlog_module *module, const char *message, ...)
1206 va_start(args, message);
1207 vlog_abort_valist(module, message, args);
1212 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
1213 struct vlog_rate_limit *rl)
1215 if (!module->honor_rate_limits) {
1219 if (!vlog_is_enabled(module, level)) {
1223 ovs_mutex_lock(&rl->mutex);
1224 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
1225 time_t now = time_now();
1226 if (!rl->n_dropped) {
1227 rl->first_dropped = now;
1229 rl->last_dropped = now;
1231 ovs_mutex_unlock(&rl->mutex);
1235 if (!rl->n_dropped) {
1236 ovs_mutex_unlock(&rl->mutex);
1238 time_t now = time_now();
1239 unsigned int n_dropped = rl->n_dropped;
1240 unsigned int first_dropped_elapsed = now - rl->first_dropped;
1241 unsigned int last_dropped_elapsed = now - rl->last_dropped;
1243 ovs_mutex_unlock(&rl->mutex);
1246 "Dropped %u log messages in last %u seconds (most recently, "
1247 "%u seconds ago) due to excessive rate",
1248 n_dropped, first_dropped_elapsed, last_dropped_elapsed);
1255 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
1256 struct vlog_rate_limit *rl, const char *message, ...)
1258 if (!vlog_should_drop(module, level, rl)) {
1261 va_start(args, message);
1262 vlog_valist(module, level, message, args);
1272 -vSPEC, --verbose=SPEC set logging levels\n\
1273 -v, --verbose set maximum verbosity level\n\
1274 --log-file[=FILE] enable logging to specified FILE\n\
1275 (default: %s/%s.log)\n\
1276 --syslog-method=(libc|unix:file|udp:ip:port)\n\
1277 specify how to send messages to syslog daemon\n\
1278 --syslog-target=HOST:PORT also send syslog msgs to HOST:PORT via UDP\n",
1279 ovs_logdir(), program_name);