2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira Networks.
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.
26 #include <sys/types.h>
31 #include "dynamic-string.h"
38 VLOG_DEFINE_THIS_MODULE(vlog);
40 /* Name for each logging level. */
41 static const char *level_names[VLL_N_LEVELS] = {
42 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
47 /* Syslog value for each logging level. */
48 static int syslog_levels[VLL_N_LEVELS] = {
49 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
54 /* The log modules. */
55 #if USE_LINKER_SECTIONS
56 extern struct vlog_module *__start_vlog_modules[];
57 extern struct vlog_module *__stop_vlog_modules[];
58 #define vlog_modules __start_vlog_modules
59 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
61 #define VLOG_MODULE VLOG_DEFINE_MODULE__
62 #include "vlog-modules.def"
65 struct vlog_module *vlog_modules[] = {
66 #define VLOG_MODULE(NAME) &VLM_##NAME,
67 #include "vlog-modules.def"
70 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
73 /* Information about each facility. */
75 const char *name; /* Name. */
76 char *pattern; /* Current pattern. */
77 bool default_pattern; /* Whether current pattern is the default. */
79 static struct facility facilities[VLF_N_FACILITIES] = {
80 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
85 /* VLF_FILE configuration. */
86 static char *log_file_name;
87 static FILE *log_file;
89 /* vlog initialized? */
90 static bool vlog_inited;
92 static void format_log_message(const struct vlog_module *, enum vlog_level,
93 enum vlog_facility, unsigned int msg_num,
94 const char *message, va_list, struct ds *)
97 /* Searches the 'n_names' in 'names'. Returns the index of a match for
98 * 'target', or 'n_names' if no name matches. */
100 search_name_array(const char *target, const char **names, size_t n_names)
104 for (i = 0; i < n_names; i++) {
106 if (!strcasecmp(names[i], target)) {
113 /* Returns the name for logging level 'level'. */
115 vlog_get_level_name(enum vlog_level level)
117 assert(level < VLL_N_LEVELS);
118 return level_names[level];
121 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
122 * is not the name of a logging level. */
124 vlog_get_level_val(const char *name)
126 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
129 /* Returns the name for logging facility 'facility'. */
131 vlog_get_facility_name(enum vlog_facility facility)
133 assert(facility < VLF_N_FACILITIES);
134 return facilities[facility].name;
137 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
138 * not the name of a logging facility. */
140 vlog_get_facility_val(const char *name)
144 for (i = 0; i < VLF_N_FACILITIES; i++) {
145 if (!strcasecmp(facilities[i].name, name)) {
152 /* Returns the name for logging module 'module'. */
154 vlog_get_module_name(const struct vlog_module *module)
159 /* Returns the logging module named 'name', or NULL if 'name' is not the name
160 * of a logging module. */
162 vlog_module_from_name(const char *name)
164 struct vlog_module **mp;
166 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
167 if (!strcasecmp(name, (*mp)->name)) {
174 /* Returns the current logging level for the given 'module' and 'facility'. */
176 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
178 assert(facility < VLF_N_FACILITIES);
179 return module->levels[facility];
183 update_min_level(struct vlog_module *module)
185 enum vlog_facility facility;
187 module->min_level = VLL_OFF;
188 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
189 if (log_file || facility != VLF_FILE) {
190 enum vlog_level level = module->levels[facility];
191 if (level > module->min_level) {
192 module->min_level = level;
199 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
200 enum vlog_level level)
202 assert(facility >= 0 && facility < VLF_N_FACILITIES);
203 assert(level < VLL_N_LEVELS);
206 struct vlog_module **mp;
208 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
209 (*mp)->levels[facility] = level;
210 update_min_level(*mp);
213 module->levels[facility] = level;
214 update_min_level(module);
218 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
219 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
220 * across all modules or facilities, respectively. */
222 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
223 enum vlog_level level)
225 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
226 if (facility == VLF_ANY_FACILITY) {
227 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
228 set_facility_level(facility, module, level);
231 set_facility_level(facility, module, level);
236 do_set_pattern(enum vlog_facility facility, const char *pattern)
238 struct facility *f = &facilities[facility];
239 if (!f->default_pattern) {
242 f->default_pattern = false;
244 f->pattern = xstrdup(pattern);
247 /* Sets the pattern for the given 'facility' to 'pattern'. */
249 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
251 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
252 if (facility == VLF_ANY_FACILITY) {
253 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
254 do_set_pattern(facility, pattern);
257 do_set_pattern(facility, pattern);
261 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
262 * log file has been set. (A non-null return value does not assert that the
263 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
264 * fails, it still sets the log file name.) */
266 vlog_get_log_file(void)
268 return log_file_name;
271 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
272 * default file name if 'file_name' is null. Returns 0 if successful,
273 * otherwise a positive errno value. */
275 vlog_set_log_file(const char *file_name)
277 char *old_log_file_name;
278 struct vlog_module **mp;
281 /* Close old log file. */
283 VLOG_INFO("closing log file");
288 /* Update log file name and free old name. The ordering is important
289 * because 'file_name' might be 'log_file_name' or some suffix of it. */
290 old_log_file_name = log_file_name;
291 log_file_name = (file_name
293 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
294 free(old_log_file_name);
295 file_name = NULL; /* Might have been freed. */
297 /* Open new log file and update min_levels[] to reflect whether we actually
298 * have a log_file. */
299 log_file = fopen(log_file_name, "a");
300 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
301 update_min_level(*mp);
304 /* Log success or failure. */
306 VLOG_WARN("failed to open %s for logging: %s",
307 log_file_name, strerror(errno));
310 VLOG_INFO("opened log file %s", log_file_name);
317 /* Closes and then attempts to re-open the current log file. (This is useful
318 * just after log rotation, to ensure that the new log file starts being used.)
319 * Returns 0 if successful, otherwise a positive errno value. */
321 vlog_reopen_log_file(void)
323 struct stat old, new;
325 /* Skip re-opening if there's nothing to reopen. */
326 if (!log_file_name) {
330 /* Skip re-opening if it would be a no-op because the old and new files are
331 * the same. (This avoids writing "closing log file" followed immediately
332 * by "opened log file".) */
334 && !fstat(fileno(log_file), &old)
335 && !stat(log_file_name, &new)
336 && old.st_dev == new.st_dev
337 && old.st_ino == new.st_ino) {
341 return vlog_set_log_file(log_file_name);
344 /* Set debugging levels:
346 * mod[:facility[:level]] mod2[:facility[:level]] ...
348 * Return null if successful, otherwise an error message that the caller must
352 vlog_set_levels_from_string(const char *s_)
354 char *save_ptr = NULL;
355 char *s = xstrdup(s_);
356 char *module, *facility;
358 for (module = strtok_r(s, ": \t", &save_ptr); module != NULL;
359 module = strtok_r(NULL, ": \t", &save_ptr)) {
360 struct vlog_module *e_module;
361 enum vlog_facility e_facility;
363 facility = strtok_r(NULL, ":", &save_ptr);
365 if (!facility || !strcasecmp(facility, "ANY")) {
366 e_facility = VLF_ANY_FACILITY;
368 e_facility = vlog_get_facility_val(facility);
369 if (e_facility >= VLF_N_FACILITIES) {
370 char *msg = xasprintf("unknown facility \"%s\"", facility);
376 if (!strcasecmp(module, "PATTERN")) {
377 vlog_set_pattern(e_facility, save_ptr);
381 enum vlog_level e_level;
383 if (!strcasecmp(module, "ANY")) {
386 e_module = vlog_module_from_name(module);
388 char *msg = xasprintf("unknown module \"%s\"", module);
394 level = strtok_r(NULL, ":", &save_ptr);
395 e_level = level ? vlog_get_level_val(level) : VLL_DBG;
396 if (e_level >= VLL_N_LEVELS) {
397 char *msg = xasprintf("unknown level \"%s\"", level);
402 vlog_set_levels(e_module, e_facility, e_level);
409 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
410 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
412 vlog_set_verbosity(const char *arg)
415 char *msg = vlog_set_levels_from_string(arg);
417 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
420 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
425 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
426 void *aux OVS_UNUSED)
430 for (i = 1; i < argc; i++) {
431 char *msg = vlog_set_levels_from_string(argv[i]);
433 unixctl_command_reply(conn, 501, msg);
438 unixctl_command_reply(conn, 202, NULL);
442 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
443 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
445 char *msg = vlog_get_levels();
446 unixctl_command_reply(conn, 200, msg);
451 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
452 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
455 int error = vlog_reopen_log_file();
457 unixctl_command_reply(conn, 503, strerror(errno));
459 unixctl_command_reply(conn, 202, NULL);
462 unixctl_command_reply(conn, 403, "Logging to file not configured");
466 /* Initializes the logging subsystem and registers its unixctl server
478 openlog(program_name, LOG_NDELAY, LOG_DAEMON);
485 localtime_r(&now, &tm);
486 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
487 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
490 unixctl_command_register(
491 "vlog/set", "{module[:facility[:level]] | PATTERN:facility:pattern}",
492 1, INT_MAX, vlog_unixctl_set, NULL);
493 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
494 unixctl_command_register("vlog/reopen", "", 0, 0,
495 vlog_unixctl_reopen, NULL);
498 /* Closes the logging subsystem. */
508 /* Print the current logging level for each module. */
510 vlog_get_levels(void)
512 struct ds s = DS_EMPTY_INITIALIZER;
513 struct vlog_module **mp;
514 struct svec lines = SVEC_EMPTY_INITIALIZER;
518 ds_put_format(&s, " console syslog file\n");
519 ds_put_format(&s, " ------- ------ ------\n");
521 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
522 line = xasprintf("%-16s %4s %4s %4s\n",
523 vlog_get_module_name(*mp),
524 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
525 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
526 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
527 svec_add_nocopy(&lines, line);
531 SVEC_FOR_EACH (i, line, &lines) {
532 ds_put_cstr(&s, line);
534 svec_destroy(&lines);
539 /* Returns true if a log message emitted for the given 'module' and 'level'
540 * would cause some log output, false if that module and level are completely
543 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
545 return module->min_level >= level;
549 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
552 size_t n = strcspn(p + 1, "}");
553 size_t n_copy = MIN(n, out_size - 1);
554 memcpy(out, p + 1, n_copy);
558 ovs_strlcpy(out, def, out_size);
564 format_log_message(const struct vlog_module *module, enum vlog_level level,
565 enum vlog_facility facility, unsigned int msg_num,
566 const char *message, va_list args_, struct ds *s)
573 for (p = facilities[facility].pattern; *p != '\0'; ) {
574 enum { LEFT, RIGHT } justify = RIGHT;
576 size_t length, field, used;
579 ds_put_char(s, *p++);
593 while (isdigit((unsigned char)*p)) {
594 field = (field * 10) + (*p - '0');
601 ds_put_cstr(s, program_name);
604 p = fetch_braces(p, "", tmp, sizeof tmp);
605 ds_put_cstr(s, vlog_get_module_name(module));
608 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
609 ds_put_strftime(s, tmp, false);
612 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
613 ds_put_strftime(s, tmp, true);
616 /* Format user-supplied log message and trim trailing new-lines. */
618 va_copy(args, args_);
619 ds_put_format_valist(s, message, args);
621 while (s->length > length && s->string[s->length - 1] == '\n') {
626 ds_put_format(s, "%u", msg_num);
629 ds_put_char(s, '\n');
632 ds_put_cstr(s, vlog_get_level_name(level));
635 ds_put_format(s, "%ld", (long int) getpid());
638 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
641 ds_put_char(s, p[-1]);
644 used = s->length - length;
646 size_t n_pad = field - used;
647 if (justify == RIGHT) {
648 ds_put_uninit(s, n_pad);
649 memmove(&s->string[length + n_pad], &s->string[length], used);
650 memset(&s->string[length], pad, n_pad);
652 ds_put_char_multiple(s, pad, n_pad);
658 /* Writes 'message' to the log at the given 'level' and as coming from the
661 * Guaranteed to preserve errno. */
663 vlog_valist(const struct vlog_module *module, enum vlog_level level,
664 const char *message, va_list args)
666 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
667 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
668 bool log_to_file = module->levels[VLF_FILE] >= level && log_file;
669 if (log_to_console || log_to_syslog || log_to_file) {
670 int save_errno = errno;
671 static unsigned int msg_num;
677 ds_reserve(&s, 1024);
680 if (log_to_console) {
681 format_log_message(module, level, VLF_CONSOLE, msg_num,
683 ds_put_char(&s, '\n');
684 fputs(ds_cstr(&s), stderr);
688 int syslog_level = syslog_levels[level];
689 char *save_ptr = NULL;
692 format_log_message(module, level, VLF_SYSLOG, msg_num,
694 for (line = strtok_r(s.string, "\n", &save_ptr); line;
695 line = strtok_r(NULL, "\n", &save_ptr)) {
696 syslog(syslog_level, "%s", line);
701 format_log_message(module, level, VLF_FILE, msg_num,
703 ds_put_char(&s, '\n');
704 fputs(ds_cstr(&s), log_file);
714 vlog(const struct vlog_module *module, enum vlog_level level,
715 const char *message, ...)
719 va_start(args, message);
720 vlog_valist(module, level, message, args);
725 vlog_fatal_valist(const struct vlog_module *module_,
726 const char *message, va_list args)
728 struct vlog_module *module = (struct vlog_module *) module_;
730 /* Don't log this message to the console to avoid redundancy with the
731 * message written by the later ovs_fatal_valist(). */
732 module->levels[VLF_CONSOLE] = VLL_OFF;
734 vlog_valist(module, VLL_EMER, message, args);
735 ovs_fatal_valist(0, message, args);
739 vlog_fatal(const struct vlog_module *module, const char *message, ...)
743 va_start(args, message);
744 vlog_fatal_valist(module, message, args);
749 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
750 struct vlog_rate_limit *rl)
752 if (!vlog_is_enabled(module, level)) {
756 if (rl->tokens < VLOG_MSG_TOKENS) {
757 time_t now = time_now();
758 if (rl->last_fill > now) {
759 /* Last filled in the future? Time must have gone backward, or
760 * 'rl' has not been used before. */
761 rl->tokens = rl->burst;
762 } else if (rl->last_fill < now) {
763 unsigned int add = sat_mul(rl->rate, now - rl->last_fill);
764 unsigned int tokens = sat_add(rl->tokens, add);
765 rl->tokens = MIN(tokens, rl->burst);
768 if (rl->tokens < VLOG_MSG_TOKENS) {
769 if (!rl->n_dropped) {
770 rl->first_dropped = now;
772 rl->last_dropped = now;
777 rl->tokens -= VLOG_MSG_TOKENS;
780 time_t now = time_now();
781 unsigned int first_dropped_elapsed = now - rl->first_dropped;
782 unsigned int last_dropped_elapsed = now - rl->last_dropped;
785 "Dropped %u log messages in last %u seconds (most recently, "
786 "%u seconds ago) due to excessive rate",
787 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
795 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
796 struct vlog_rate_limit *rl, const char *message, ...)
798 if (!vlog_should_drop(module, level, rl)) {
801 va_start(args, message);
802 vlog_valist(module, level, message, args);
810 printf("\nLogging options:\n"
811 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
812 " -v, --verbose set maximum verbosity level\n"
813 " --log-file[=FILE] enable logging to specified FILE\n"
814 " (default: %s/%s.log)\n",
815 ovs_logdir(), program_name);