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");
484 set_all_rate_limits(bool enable)
486 struct vlog_module **mp;
488 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
489 (*mp)->honor_rate_limits = enable;
494 set_rate_limits(struct unixctl_conn *conn, int argc,
495 const char *argv[], bool enable)
500 for (i = 1; i < argc; i++) {
501 if (!strcasecmp(argv[i], "ANY")) {
502 set_all_rate_limits(enable);
504 struct vlog_module *module = vlog_module_from_name(argv[i]);
506 unixctl_command_reply_error(conn, "unknown module");
509 module->honor_rate_limits = enable;
513 set_all_rate_limits(enable);
515 unixctl_command_reply(conn, NULL);
519 vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
520 const char *argv[], void *aux OVS_UNUSED)
522 set_rate_limits(conn, argc, argv, true);
526 vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
527 const char *argv[], void *aux OVS_UNUSED)
529 set_rate_limits(conn, argc, argv, false);
532 /* Initializes the logging subsystem and registers its unixctl server
537 static char *program_name_copy;
545 /* openlog() is allowed to keep the pointer passed in, without making a
546 * copy. The daemonize code sometimes frees and replaces 'program_name',
547 * so make a private copy just for openlog(). (We keep a pointer to the
548 * private copy to suppress memory leak warnings in case openlog() does
549 * make its own copy.) */
550 program_name_copy = program_name ? xstrdup(program_name) : NULL;
551 openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
559 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S", &tm);
560 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
563 unixctl_command_register(
564 "vlog/set", "{spec | PATTERN:facility:pattern}",
565 1, INT_MAX, vlog_unixctl_set, NULL);
566 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
567 unixctl_command_register("vlog/enable-rate-limit", "[module]...",
568 0, INT_MAX, vlog_enable_rate_limit, NULL);
569 unixctl_command_register("vlog/disable-rate-limit", "[module]...",
570 0, INT_MAX, vlog_disable_rate_limit, NULL);
571 unixctl_command_register("vlog/reopen", "", 0, 0,
572 vlog_unixctl_reopen, NULL);
575 /* Closes the logging subsystem. */
585 /* Print the current logging level for each module. */
587 vlog_get_levels(void)
589 struct ds s = DS_EMPTY_INITIALIZER;
590 struct vlog_module **mp;
591 struct svec lines = SVEC_EMPTY_INITIALIZER;
595 ds_put_format(&s, " console syslog file\n");
596 ds_put_format(&s, " ------- ------ ------\n");
598 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
602 ds_put_format(&line, "%-16s %4s %4s %4s",
603 vlog_get_module_name(*mp),
604 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
605 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
606 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
607 if (!(*mp)->honor_rate_limits) {
608 ds_put_cstr(&line, " (rate limiting disabled)");
610 ds_put_char(&line, '\n');
612 svec_add_nocopy(&lines, ds_steal_cstr(&line));
616 SVEC_FOR_EACH (i, line, &lines) {
617 ds_put_cstr(&s, line);
619 svec_destroy(&lines);
624 /* Returns true if a log message emitted for the given 'module' and 'level'
625 * would cause some log output, false if that module and level are completely
628 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
630 return module->min_level >= level;
634 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
637 size_t n = strcspn(p + 1, "}");
638 size_t n_copy = MIN(n, out_size - 1);
639 memcpy(out, p + 1, n_copy);
643 ovs_strlcpy(out, def, out_size);
649 format_log_message(const struct vlog_module *module, enum vlog_level level,
650 enum vlog_facility facility, unsigned int msg_num,
651 const char *message, va_list args_, struct ds *s)
658 for (p = facilities[facility].pattern; *p != '\0'; ) {
659 enum { LEFT, RIGHT } justify = RIGHT;
661 size_t length, field, used;
664 ds_put_char(s, *p++);
678 while (isdigit((unsigned char)*p)) {
679 field = (field * 10) + (*p - '0');
686 ds_put_cstr(s, program_name);
689 p = fetch_braces(p, "", tmp, sizeof tmp);
690 ds_put_cstr(s, vlog_get_module_name(module));
693 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
694 ds_put_strftime(s, tmp, false);
697 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
698 ds_put_strftime(s, tmp, true);
701 /* Format user-supplied log message and trim trailing new-lines. */
703 va_copy(args, args_);
704 ds_put_format_valist(s, message, args);
706 while (s->length > length && s->string[s->length - 1] == '\n') {
711 ds_put_format(s, "%u", msg_num);
714 ds_put_char(s, '\n');
717 ds_put_cstr(s, vlog_get_level_name(level));
720 ds_put_format(s, "%ld", (long int) getpid());
723 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
726 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
729 if (subprogram_name[0]) {
730 ds_put_format(s, "(%s)", subprogram_name);
734 ds_put_char(s, p[-1]);
737 used = s->length - length;
739 size_t n_pad = field - used;
740 if (justify == RIGHT) {
741 ds_put_uninit(s, n_pad);
742 memmove(&s->string[length + n_pad], &s->string[length], used);
743 memset(&s->string[length], pad, n_pad);
745 ds_put_char_multiple(s, pad, n_pad);
751 /* Writes 'message' to the log at the given 'level' and as coming from the
754 * Guaranteed to preserve errno. */
756 vlog_valist(const struct vlog_module *module, enum vlog_level level,
757 const char *message, va_list args)
759 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
760 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
761 bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
762 if (log_to_console || log_to_syslog || log_to_file) {
763 int save_errno = errno;
764 static unsigned int msg_num;
770 ds_reserve(&s, 1024);
773 if (log_to_console) {
774 format_log_message(module, level, VLF_CONSOLE, msg_num,
776 ds_put_char(&s, '\n');
777 fputs(ds_cstr(&s), stderr);
781 int syslog_level = syslog_levels[level];
782 char *save_ptr = NULL;
785 format_log_message(module, level, VLF_SYSLOG, msg_num,
787 for (line = strtok_r(s.string, "\n", &save_ptr); line;
788 line = strtok_r(NULL, "\n", &save_ptr)) {
789 syslog(syslog_level, "%s", line);
794 format_log_message(module, level, VLF_FILE, msg_num,
796 ds_put_char(&s, '\n');
806 vlog(const struct vlog_module *module, enum vlog_level level,
807 const char *message, ...)
811 va_start(args, message);
812 vlog_valist(module, level, message, args);
816 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
817 * exit code. Always writes the message to stderr, even if the console
818 * facility is disabled.
820 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
821 * facility shouldn't automatically restart the current daemon. */
823 vlog_fatal_valist(const struct vlog_module *module_,
824 const char *message, va_list args)
826 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
828 /* Don't log this message to the console to avoid redundancy with the
829 * message written by the later ovs_fatal_valist(). */
830 module->levels[VLF_CONSOLE] = VLL_OFF;
832 vlog_valist(module, VLL_EMER, message, args);
833 ovs_fatal_valist(0, message, args);
836 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
837 * exit code. Always writes the message to stderr, even if the console
838 * facility is disabled.
840 * Choose this function instead of vlog_abort() if the daemon monitoring
841 * facility shouldn't automatically restart the current daemon. */
843 vlog_fatal(const struct vlog_module *module, const char *message, ...)
847 va_start(args, message);
848 vlog_fatal_valist(module, message, args);
852 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
853 * writes the message to stderr, even if the console facility is disabled.
855 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
856 * facility should automatically restart the current daemon. */
858 vlog_abort_valist(const struct vlog_module *module_,
859 const char *message, va_list args)
861 struct vlog_module *module = (struct vlog_module *) module_;
863 /* Don't log this message to the console to avoid redundancy with the
864 * message written by the later ovs_abort_valist(). */
865 module->levels[VLF_CONSOLE] = VLL_OFF;
867 vlog_valist(module, VLL_EMER, message, args);
868 ovs_abort_valist(0, message, args);
871 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
872 * writes the message to stderr, even if the console facility is disabled.
874 * Choose this function instead of vlog_fatal() if the daemon monitoring
875 * facility should automatically restart the current daemon. */
877 vlog_abort(const struct vlog_module *module, const char *message, ...)
881 va_start(args, message);
882 vlog_abort_valist(module, message, args);
887 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
888 struct vlog_rate_limit *rl)
890 if (!module->honor_rate_limits) {
894 if (!vlog_is_enabled(module, level)) {
898 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
899 time_t now = time_now();
900 if (!rl->n_dropped) {
901 rl->first_dropped = now;
903 rl->last_dropped = now;
909 time_t now = time_now();
910 unsigned int first_dropped_elapsed = now - rl->first_dropped;
911 unsigned int last_dropped_elapsed = now - rl->last_dropped;
914 "Dropped %u log messages in last %u seconds (most recently, "
915 "%u seconds ago) due to excessive rate",
916 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
924 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
925 struct vlog_rate_limit *rl, const char *message, ...)
927 if (!vlog_should_drop(module, level, rl)) {
930 va_start(args, message);
931 vlog_valist(module, level, message, args);
939 printf("\nLogging options:\n"
940 " -v, --verbose=[SPEC] set logging levels\n"
941 " -v, --verbose set maximum verbosity level\n"
942 " --log-file[=FILE] enable logging to specified FILE\n"
943 " (default: %s/%s.log)\n",
944 ovs_logdir(), program_name);
947 static bool vlog_async_inited = false;
949 static worker_request_func vlog_async_write_request_cb;
952 vlog_write_file(struct ds *s)
954 if (worker_is_running()) {
955 worker_request(s->string, s->length,
956 &log_fd, vlog_async_inited ? 0 : 1,
957 vlog_async_write_request_cb, NULL, NULL);
958 vlog_async_inited = true;
960 ignore(write(log_fd, s->string, s->length));
965 vlog_update_async_log_fd(void)
967 if (worker_is_running()) {
968 worker_request(NULL, 0, &log_fd, 1, vlog_async_write_request_cb,
970 vlog_async_inited = true;
975 vlog_async_write_request_cb(struct ofpbuf *request,
976 const int *fd, size_t n_fds)
985 if (request->size > 0) {
986 ignore(write(log_fd, request->data, request->size));