2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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>
33 #include "dynamic-string.h"
42 VLOG_DEFINE_THIS_MODULE(vlog);
44 COVERAGE_DEFINE(vlog_recursive);
46 /* Name for each logging level. */
47 static const char *level_names[VLL_N_LEVELS] = {
48 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
53 /* Syslog value for each logging level. */
54 static int syslog_levels[VLL_N_LEVELS] = {
55 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
60 /* The log modules. */
61 #if USE_LINKER_SECTIONS
62 extern struct vlog_module *__start_vlog_modules[];
63 extern struct vlog_module *__stop_vlog_modules[];
64 #define vlog_modules __start_vlog_modules
65 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
67 #define VLOG_MODULE VLOG_DEFINE_MODULE__
68 #include "vlog-modules.def"
71 struct vlog_module *vlog_modules[] = {
72 #define VLOG_MODULE(NAME) &VLM_##NAME,
73 #include "vlog-modules.def"
76 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
79 /* Information about each facility. */
81 const char *name; /* Name. */
82 char *pattern; /* Current pattern. */
83 bool default_pattern; /* Whether current pattern is the default. */
85 static struct facility facilities[VLF_N_FACILITIES] = {
86 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
91 /* VLF_FILE configuration. */
92 static char *log_file_name;
93 static int log_fd = -1;
95 /* vlog initialized? */
96 static bool vlog_inited;
98 static void format_log_message(const struct vlog_module *, enum vlog_level,
99 enum vlog_facility, unsigned int msg_num,
100 const char *message, va_list, struct ds *)
102 static void vlog_write_file(struct ds *);
103 static void vlog_update_async_log_fd(void);
105 /* Searches the 'n_names' in 'names'. Returns the index of a match for
106 * 'target', or 'n_names' if no name matches. */
108 search_name_array(const char *target, const char **names, size_t n_names)
112 for (i = 0; i < n_names; i++) {
114 if (!strcasecmp(names[i], target)) {
121 /* Returns the name for logging level 'level'. */
123 vlog_get_level_name(enum vlog_level level)
125 assert(level < VLL_N_LEVELS);
126 return level_names[level];
129 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
130 * is not the name of a logging level. */
132 vlog_get_level_val(const char *name)
134 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
137 /* Returns the name for logging facility 'facility'. */
139 vlog_get_facility_name(enum vlog_facility facility)
141 assert(facility < VLF_N_FACILITIES);
142 return facilities[facility].name;
145 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
146 * not the name of a logging facility. */
148 vlog_get_facility_val(const char *name)
152 for (i = 0; i < VLF_N_FACILITIES; i++) {
153 if (!strcasecmp(facilities[i].name, name)) {
160 /* Returns the name for logging module 'module'. */
162 vlog_get_module_name(const struct vlog_module *module)
167 /* Returns the logging module named 'name', or NULL if 'name' is not the name
168 * of a logging module. */
170 vlog_module_from_name(const char *name)
172 struct vlog_module **mp;
174 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
175 if (!strcasecmp(name, (*mp)->name)) {
182 /* Returns the current logging level for the given 'module' and 'facility'. */
184 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
186 assert(facility < VLF_N_FACILITIES);
187 return module->levels[facility];
191 update_min_level(struct vlog_module *module)
193 enum vlog_facility facility;
195 module->min_level = VLL_OFF;
196 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
197 if (log_fd >= 0 || facility != VLF_FILE) {
198 enum vlog_level level = module->levels[facility];
199 if (level > module->min_level) {
200 module->min_level = level;
207 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
208 enum vlog_level level)
210 assert(facility >= 0 && facility < VLF_N_FACILITIES);
211 assert(level < VLL_N_LEVELS);
214 struct vlog_module **mp;
216 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
217 (*mp)->levels[facility] = level;
218 update_min_level(*mp);
221 module->levels[facility] = level;
222 update_min_level(module);
226 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
227 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
228 * across all modules or facilities, respectively. */
230 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
231 enum vlog_level level)
233 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
234 if (facility == VLF_ANY_FACILITY) {
235 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
236 set_facility_level(facility, module, level);
239 set_facility_level(facility, module, level);
244 do_set_pattern(enum vlog_facility facility, const char *pattern)
246 struct facility *f = &facilities[facility];
247 if (!f->default_pattern) {
250 f->default_pattern = false;
252 f->pattern = xstrdup(pattern);
255 /* Sets the pattern for the given 'facility' to 'pattern'. */
257 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
259 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
260 if (facility == VLF_ANY_FACILITY) {
261 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
262 do_set_pattern(facility, pattern);
265 do_set_pattern(facility, pattern);
269 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
270 * log file has been set. (A non-null return value does not assert that the
271 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
272 * fails, it still sets the log file name.) */
274 vlog_get_log_file(void)
276 return log_file_name;
279 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
280 * default file name if 'file_name' is null. Returns 0 if successful,
281 * otherwise a positive errno value. */
283 vlog_set_log_file(const char *file_name)
285 char *old_log_file_name;
286 struct vlog_module **mp;
289 /* Close old log file. */
291 VLOG_INFO("closing log file");
296 /* Update log file name and free old name. The ordering is important
297 * because 'file_name' might be 'log_file_name' or some suffix of it. */
298 old_log_file_name = log_file_name;
299 log_file_name = (file_name
301 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
302 free(old_log_file_name);
303 file_name = NULL; /* Might have been freed. */
305 /* Open new log file and update min_levels[] to reflect whether we actually
306 * have a log_file. */
307 log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
309 vlog_update_async_log_fd();
311 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
312 update_min_level(*mp);
315 /* Log success or failure. */
317 VLOG_WARN("failed to open %s for logging: %s",
318 log_file_name, strerror(errno));
321 VLOG_INFO("opened log file %s", log_file_name);
328 /* Closes and then attempts to re-open the current log file. (This is useful
329 * just after log rotation, to ensure that the new log file starts being used.)
330 * Returns 0 if successful, otherwise a positive errno value. */
332 vlog_reopen_log_file(void)
334 struct stat old, new;
336 /* Skip re-opening if there's nothing to reopen. */
337 if (!log_file_name) {
341 /* Skip re-opening if it would be a no-op because the old and new files are
342 * the same. (This avoids writing "closing log file" followed immediately
343 * by "opened log file".) */
345 && !fstat(log_fd, &old)
346 && !stat(log_file_name, &new)
347 && old.st_dev == new.st_dev
348 && old.st_ino == new.st_ino) {
352 return vlog_set_log_file(log_file_name);
355 /* Set debugging levels. Returns null if successful, otherwise an error
356 * message that the caller must free(). */
358 vlog_set_levels_from_string(const char *s_)
360 char *s = xstrdup(s_);
361 char *save_ptr = NULL;
365 word = strtok_r(s, " ,:\t", &save_ptr);
366 if (word && !strcasecmp(word, "PATTERN")) {
367 enum vlog_facility facility;
369 word = strtok_r(NULL, " ,:\t", &save_ptr);
371 msg = xstrdup("missing facility");
375 facility = (!strcasecmp(word, "ANY")
377 : vlog_get_facility_val(word));
378 if (facility == VLF_N_FACILITIES) {
379 msg = xasprintf("unknown facility \"%s\"", word);
382 vlog_set_pattern(facility, save_ptr);
384 struct vlog_module *module = NULL;
385 enum vlog_level level = VLL_N_LEVELS;
386 enum vlog_facility facility = VLF_N_FACILITIES;
388 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
389 if (!strcasecmp(word, "ANY")) {
391 } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
392 if (facility != VLF_N_FACILITIES) {
393 msg = xstrdup("cannot specify multiple facilities");
396 facility = vlog_get_facility_val(word);
397 } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
398 if (level != VLL_N_LEVELS) {
399 msg = xstrdup("cannot specify multiple levels");
402 level = vlog_get_level_val(word);
403 } else if (vlog_module_from_name(word)) {
405 msg = xstrdup("cannot specify multiple modules");
408 module = vlog_module_from_name(word);
410 msg = xasprintf("no facility, level, or module \"%s\"", word);
415 if (facility == VLF_N_FACILITIES) {
416 facility = VLF_ANY_FACILITY;
418 if (level == VLL_N_LEVELS) {
421 vlog_set_levels(module, facility, level);
429 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
430 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
432 vlog_set_verbosity(const char *arg)
435 char *msg = vlog_set_levels_from_string(arg);
437 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
440 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
445 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
446 void *aux OVS_UNUSED)
450 for (i = 1; i < argc; i++) {
451 char *msg = vlog_set_levels_from_string(argv[i]);
453 unixctl_command_reply_error(conn, msg);
458 unixctl_command_reply(conn, NULL);
462 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
463 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
465 char *msg = vlog_get_levels();
466 unixctl_command_reply(conn, msg);
471 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
472 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
475 int error = vlog_reopen_log_file();
477 unixctl_command_reply_error(conn, strerror(errno));
479 unixctl_command_reply(conn, NULL);
482 unixctl_command_reply_error(conn, "Logging to file not configured");
486 /* Initializes the logging subsystem and registers its unixctl server
491 static char *program_name_copy;
499 /* openlog() is allowed to keep the pointer passed in, without making a
500 * copy. The daemonize code sometimes frees and replaces 'program_name',
501 * so make a private copy just for openlog(). (We keep a pointer to the
502 * private copy to suppress memory leak warnings in case openlog() does
503 * make its own copy.) */
504 program_name_copy = program_name ? xstrdup(program_name) : NULL;
505 openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
513 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S", &tm);
514 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
517 unixctl_command_register(
518 "vlog/set", "{spec | PATTERN:facility:pattern}",
519 1, INT_MAX, vlog_unixctl_set, NULL);
520 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
521 unixctl_command_register("vlog/reopen", "", 0, 0,
522 vlog_unixctl_reopen, NULL);
525 /* Closes the logging subsystem. */
535 /* Print the current logging level for each module. */
537 vlog_get_levels(void)
539 struct ds s = DS_EMPTY_INITIALIZER;
540 struct vlog_module **mp;
541 struct svec lines = SVEC_EMPTY_INITIALIZER;
545 ds_put_format(&s, " console syslog file\n");
546 ds_put_format(&s, " ------- ------ ------\n");
548 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
549 line = xasprintf("%-16s %4s %4s %4s\n",
550 vlog_get_module_name(*mp),
551 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
552 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
553 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
554 svec_add_nocopy(&lines, line);
558 SVEC_FOR_EACH (i, line, &lines) {
559 ds_put_cstr(&s, line);
561 svec_destroy(&lines);
566 /* Returns true if a log message emitted for the given 'module' and 'level'
567 * would cause some log output, false if that module and level are completely
570 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
572 return module->min_level >= level;
576 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
579 size_t n = strcspn(p + 1, "}");
580 size_t n_copy = MIN(n, out_size - 1);
581 memcpy(out, p + 1, n_copy);
585 ovs_strlcpy(out, def, out_size);
591 format_log_message(const struct vlog_module *module, enum vlog_level level,
592 enum vlog_facility facility, unsigned int msg_num,
593 const char *message, va_list args_, struct ds *s)
600 for (p = facilities[facility].pattern; *p != '\0'; ) {
601 enum { LEFT, RIGHT } justify = RIGHT;
603 size_t length, field, used;
606 ds_put_char(s, *p++);
620 while (isdigit((unsigned char)*p)) {
621 field = (field * 10) + (*p - '0');
628 ds_put_cstr(s, program_name);
631 p = fetch_braces(p, "", tmp, sizeof tmp);
632 ds_put_cstr(s, vlog_get_module_name(module));
635 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
636 ds_put_strftime(s, tmp, false);
639 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
640 ds_put_strftime(s, tmp, true);
643 /* Format user-supplied log message and trim trailing new-lines. */
645 va_copy(args, args_);
646 ds_put_format_valist(s, message, args);
648 while (s->length > length && s->string[s->length - 1] == '\n') {
653 ds_put_format(s, "%u", msg_num);
656 ds_put_char(s, '\n');
659 ds_put_cstr(s, vlog_get_level_name(level));
662 ds_put_format(s, "%ld", (long int) getpid());
665 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
668 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
671 if (subprogram_name[0]) {
672 ds_put_format(s, "(%s)", subprogram_name);
676 ds_put_char(s, p[-1]);
679 used = s->length - length;
681 size_t n_pad = field - used;
682 if (justify == RIGHT) {
683 ds_put_uninit(s, n_pad);
684 memmove(&s->string[length + n_pad], &s->string[length], used);
685 memset(&s->string[length], pad, n_pad);
687 ds_put_char_multiple(s, pad, n_pad);
693 /* Writes 'message' to the log at the given 'level' and as coming from the
696 * Guaranteed to preserve errno. */
698 vlog_valist(const struct vlog_module *module, enum vlog_level level,
699 const char *message, va_list args)
701 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
702 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
703 bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
704 if (log_to_console || log_to_syslog || log_to_file) {
705 int save_errno = errno;
706 static unsigned int msg_num;
712 ds_reserve(&s, 1024);
715 if (log_to_console) {
716 format_log_message(module, level, VLF_CONSOLE, msg_num,
718 ds_put_char(&s, '\n');
719 fputs(ds_cstr(&s), stderr);
723 int syslog_level = syslog_levels[level];
724 char *save_ptr = NULL;
727 format_log_message(module, level, VLF_SYSLOG, msg_num,
729 for (line = strtok_r(s.string, "\n", &save_ptr); line;
730 line = strtok_r(NULL, "\n", &save_ptr)) {
731 syslog(syslog_level, "%s", line);
736 format_log_message(module, level, VLF_FILE, msg_num,
738 ds_put_char(&s, '\n');
748 vlog(const struct vlog_module *module, enum vlog_level level,
749 const char *message, ...)
753 va_start(args, message);
754 vlog_valist(module, level, message, args);
758 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
759 * exit code. Always writes the message to stderr, even if the console
760 * facility is disabled.
762 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
763 * facility shouldn't automatically restart the current daemon. */
765 vlog_fatal_valist(const struct vlog_module *module_,
766 const char *message, va_list args)
768 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
770 /* Don't log this message to the console to avoid redundancy with the
771 * message written by the later ovs_fatal_valist(). */
772 module->levels[VLF_CONSOLE] = VLL_OFF;
774 vlog_valist(module, VLL_EMER, message, args);
775 ovs_fatal_valist(0, message, args);
778 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
779 * exit code. Always writes the message to stderr, even if the console
780 * facility is disabled.
782 * Choose this function instead of vlog_abort() if the daemon monitoring
783 * facility shouldn't automatically restart the current daemon. */
785 vlog_fatal(const struct vlog_module *module, const char *message, ...)
789 va_start(args, message);
790 vlog_fatal_valist(module, message, args);
794 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
795 * writes the message to stderr, even if the console facility is disabled.
797 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
798 * facility should automatically restart the current daemon. */
800 vlog_abort_valist(const struct vlog_module *module_,
801 const char *message, va_list args)
803 struct vlog_module *module = (struct vlog_module *) module_;
805 /* Don't log this message to the console to avoid redundancy with the
806 * message written by the later ovs_abort_valist(). */
807 module->levels[VLF_CONSOLE] = VLL_OFF;
809 vlog_valist(module, VLL_EMER, message, args);
810 ovs_abort_valist(0, message, args);
813 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
814 * writes the message to stderr, even if the console facility is disabled.
816 * Choose this function instead of vlog_fatal() if the daemon monitoring
817 * facility should automatically restart the current daemon. */
819 vlog_abort(const struct vlog_module *module, const char *message, ...)
823 va_start(args, message);
824 vlog_abort_valist(module, message, args);
829 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
830 struct vlog_rate_limit *rl)
832 if (!vlog_is_enabled(module, level)) {
836 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
837 time_t now = time_now();
838 if (!rl->n_dropped) {
839 rl->first_dropped = now;
841 rl->last_dropped = now;
847 time_t now = time_now();
848 unsigned int first_dropped_elapsed = now - rl->first_dropped;
849 unsigned int last_dropped_elapsed = now - rl->last_dropped;
852 "Dropped %u log messages in last %u seconds (most recently, "
853 "%u seconds ago) due to excessive rate",
854 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
862 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
863 struct vlog_rate_limit *rl, const char *message, ...)
865 if (!vlog_should_drop(module, level, rl)) {
868 va_start(args, message);
869 vlog_valist(module, level, message, args);
877 printf("\nLogging options:\n"
878 " -v, --verbose=[SPEC] set logging levels\n"
879 " -v, --verbose set maximum verbosity level\n"
880 " --log-file[=FILE] enable logging to specified FILE\n"
881 " (default: %s/%s.log)\n",
882 ovs_logdir(), program_name);
885 static bool vlog_async_inited = false;
887 static worker_request_func vlog_async_write_request_cb;
890 vlog_write_file(struct ds *s)
892 if (worker_is_running()) {
893 static bool in_worker_request = false;
894 if (!in_worker_request) {
895 in_worker_request = true;
897 worker_request(s->string, s->length,
898 &log_fd, vlog_async_inited ? 0 : 1,
899 vlog_async_write_request_cb, NULL, NULL);
900 vlog_async_inited = true;
902 in_worker_request = false;
905 /* We've been entered recursively. This can happen if
906 * worker_request(), or a function that it calls, tries to log
907 * something. We can't call worker_request() recursively, so fall
908 * back to writing the log file directly. */
909 COVERAGE_INC(vlog_recursive);
912 ignore(write(log_fd, s->string, s->length));
916 vlog_update_async_log_fd(void)
918 if (worker_is_running()) {
919 worker_request(NULL, 0, &log_fd, 1, vlog_async_write_request_cb,
921 vlog_async_inited = true;
926 vlog_async_write_request_cb(struct ofpbuf *request,
927 const int *fd, size_t n_fds)
936 if (request->size > 0) {
937 ignore(write(log_fd, request->data, request->size));