2 * Copyright (c) 2008, 2009, 2010, 2011 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 /* Time at which vlog was initialized, in milliseconds. */
86 static long long int boot_time;
88 /* VLF_FILE configuration. */
89 static char *log_file_name;
90 static FILE *log_file;
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 *)
100 /* Searches the 'n_names' in 'names'. Returns the index of a match for
101 * 'target', or 'n_names' if no name matches. */
103 search_name_array(const char *target, const char **names, size_t n_names)
107 for (i = 0; i < n_names; i++) {
109 if (!strcasecmp(names[i], target)) {
116 /* Returns the name for logging level 'level'. */
118 vlog_get_level_name(enum vlog_level level)
120 assert(level < VLL_N_LEVELS);
121 return level_names[level];
124 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
125 * is not the name of a logging level. */
127 vlog_get_level_val(const char *name)
129 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
132 /* Returns the name for logging facility 'facility'. */
134 vlog_get_facility_name(enum vlog_facility facility)
136 assert(facility < VLF_N_FACILITIES);
137 return facilities[facility].name;
140 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
141 * not the name of a logging facility. */
143 vlog_get_facility_val(const char *name)
147 for (i = 0; i < VLF_N_FACILITIES; i++) {
148 if (!strcasecmp(facilities[i].name, name)) {
155 /* Returns the name for logging module 'module'. */
157 vlog_get_module_name(const struct vlog_module *module)
162 /* Returns the logging module named 'name', or NULL if 'name' is not the name
163 * of a logging module. */
165 vlog_module_from_name(const char *name)
167 struct vlog_module **mp;
169 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
170 if (!strcasecmp(name, (*mp)->name)) {
177 /* Returns the current logging level for the given 'module' and 'facility'. */
179 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
181 assert(facility < VLF_N_FACILITIES);
182 return module->levels[facility];
186 update_min_level(struct vlog_module *module)
188 enum vlog_facility facility;
190 module->min_level = VLL_OFF;
191 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
192 if (log_file || facility != VLF_FILE) {
193 enum vlog_level level = module->levels[facility];
194 if (level > module->min_level) {
195 module->min_level = level;
202 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
203 enum vlog_level level)
205 assert(facility >= 0 && facility < VLF_N_FACILITIES);
206 assert(level < VLL_N_LEVELS);
209 struct vlog_module **mp;
211 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
212 (*mp)->levels[facility] = level;
213 update_min_level(*mp);
216 module->levels[facility] = level;
217 update_min_level(module);
221 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
222 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
223 * across all modules or facilities, respectively. */
225 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
226 enum vlog_level level)
228 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
229 if (facility == VLF_ANY_FACILITY) {
230 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
231 set_facility_level(facility, module, level);
234 set_facility_level(facility, module, level);
239 do_set_pattern(enum vlog_facility facility, const char *pattern)
241 struct facility *f = &facilities[facility];
242 if (!f->default_pattern) {
245 f->default_pattern = false;
247 f->pattern = xstrdup(pattern);
250 /* Sets the pattern for the given 'facility' to 'pattern'. */
252 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
254 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
255 if (facility == VLF_ANY_FACILITY) {
256 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
257 do_set_pattern(facility, pattern);
260 do_set_pattern(facility, pattern);
264 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
265 * log file has been set. (A non-null return value does not assert that the
266 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
267 * fails, it still sets the log file name.) */
269 vlog_get_log_file(void)
271 return log_file_name;
274 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
275 * default file name if 'file_name' is null. Returns 0 if successful,
276 * otherwise a positive errno value. */
278 vlog_set_log_file(const char *file_name)
280 char *old_log_file_name;
281 struct vlog_module **mp;
284 /* Close old log file. */
286 VLOG_INFO("closing log file");
291 /* Update log file name and free old name. The ordering is important
292 * because 'file_name' might be 'log_file_name' or some suffix of it. */
293 old_log_file_name = log_file_name;
294 log_file_name = (file_name
296 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
297 free(old_log_file_name);
298 file_name = NULL; /* Might have been freed. */
300 /* Open new log file and update min_levels[] to reflect whether we actually
301 * have a log_file. */
302 log_file = fopen(log_file_name, "a");
303 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
304 update_min_level(*mp);
307 /* Log success or failure. */
309 VLOG_WARN("failed to open %s for logging: %s",
310 log_file_name, strerror(errno));
313 VLOG_INFO("opened log file %s", log_file_name);
320 /* Closes and then attempts to re-open the current log file. (This is useful
321 * just after log rotation, to ensure that the new log file starts being used.)
322 * Returns 0 if successful, otherwise a positive errno value. */
324 vlog_reopen_log_file(void)
326 struct stat old, new;
328 /* Skip re-opening if there's nothing to reopen. */
329 if (!log_file_name) {
333 /* Skip re-opening if it would be a no-op because the old and new files are
334 * the same. (This avoids writing "closing log file" followed immediately
335 * by "opened log file".) */
337 && !fstat(fileno(log_file), &old)
338 && !stat(log_file_name, &new)
339 && old.st_dev == new.st_dev
340 && old.st_ino == new.st_ino) {
344 return vlog_set_log_file(log_file_name);
347 /* Set debugging levels:
349 * mod[:facility[:level]] mod2[:facility[:level]] ...
351 * Return null if successful, otherwise an error message that the caller must
355 vlog_set_levels_from_string(const char *s_)
357 char *save_ptr = NULL;
358 char *s = xstrdup(s_);
359 char *module, *facility;
361 for (module = strtok_r(s, ": \t", &save_ptr); module != NULL;
362 module = strtok_r(NULL, ": \t", &save_ptr)) {
363 struct vlog_module *e_module;
364 enum vlog_facility e_facility;
366 facility = strtok_r(NULL, ":", &save_ptr);
368 if (!facility || !strcasecmp(facility, "ANY")) {
369 e_facility = VLF_ANY_FACILITY;
371 e_facility = vlog_get_facility_val(facility);
372 if (e_facility >= VLF_N_FACILITIES) {
373 char *msg = xasprintf("unknown facility \"%s\"", facility);
379 if (!strcasecmp(module, "PATTERN")) {
380 vlog_set_pattern(e_facility, save_ptr);
384 enum vlog_level e_level;
386 if (!strcasecmp(module, "ANY")) {
389 e_module = vlog_module_from_name(module);
391 char *msg = xasprintf("unknown module \"%s\"", module);
397 level = strtok_r(NULL, ":", &save_ptr);
398 e_level = level ? vlog_get_level_val(level) : VLL_DBG;
399 if (e_level >= VLL_N_LEVELS) {
400 char *msg = xasprintf("unknown level \"%s\"", level);
405 vlog_set_levels(e_module, e_facility, e_level);
412 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
413 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
415 vlog_set_verbosity(const char *arg)
418 char *msg = vlog_set_levels_from_string(arg);
420 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
423 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
428 vlog_unixctl_set(struct unixctl_conn *conn,
429 const char *args, void *aux OVS_UNUSED)
431 char *msg = vlog_set_levels_from_string(args);
432 unixctl_command_reply(conn, msg ? 501 : 202, msg);
437 vlog_unixctl_list(struct unixctl_conn *conn,
438 const char *args OVS_UNUSED, void *aux OVS_UNUSED)
440 char *msg = vlog_get_levels();
441 unixctl_command_reply(conn, 200, msg);
446 vlog_unixctl_reopen(struct unixctl_conn *conn,
447 const char *args OVS_UNUSED, void *aux OVS_UNUSED)
450 int error = vlog_reopen_log_file();
452 unixctl_command_reply(conn, 503, strerror(errno));
454 unixctl_command_reply(conn, 202, NULL);
457 unixctl_command_reply(conn, 403, "Logging to file not configured");
461 /* Initializes the logging subsystem and registers its unixctl server
473 openlog(program_name, LOG_NDELAY, LOG_DAEMON);
475 boot_time = time_msec();
481 localtime_r(&now, &tm);
482 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
483 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
486 unixctl_command_register("vlog/set",
487 "{module[:facility[:level]] | PATTERN:facility:pattern}",
488 vlog_unixctl_set, NULL);
489 unixctl_command_register("vlog/list", "", vlog_unixctl_list, NULL);
490 unixctl_command_register("vlog/reopen", "", vlog_unixctl_reopen, NULL);
493 /* Closes the logging subsystem. */
503 /* Print the current logging level for each module. */
505 vlog_get_levels(void)
507 struct ds s = DS_EMPTY_INITIALIZER;
508 struct vlog_module **mp;
509 struct svec lines = SVEC_EMPTY_INITIALIZER;
513 ds_put_format(&s, " console syslog file\n");
514 ds_put_format(&s, " ------- ------ ------\n");
516 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
517 line = xasprintf("%-16s %4s %4s %4s\n",
518 vlog_get_module_name(*mp),
519 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
520 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
521 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
522 svec_add_nocopy(&lines, line);
526 SVEC_FOR_EACH (i, line, &lines) {
527 ds_put_cstr(&s, line);
529 svec_destroy(&lines);
534 /* Returns true if a log message emitted for the given 'module' and 'level'
535 * would cause some log output, false if that module and level are completely
538 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
540 return module->min_level >= level;
544 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
547 size_t n = strcspn(p + 1, "}");
548 size_t n_copy = MIN(n, out_size - 1);
549 memcpy(out, p + 1, n_copy);
553 ovs_strlcpy(out, def, out_size);
559 format_log_message(const struct vlog_module *module, enum vlog_level level,
560 enum vlog_facility facility, unsigned int msg_num,
561 const char *message, va_list args_, struct ds *s)
568 for (p = facilities[facility].pattern; *p != '\0'; ) {
569 enum { LEFT, RIGHT } justify = RIGHT;
571 size_t length, field, used;
574 ds_put_char(s, *p++);
588 while (isdigit((unsigned char)*p)) {
589 field = (field * 10) + (*p - '0');
596 ds_put_cstr(s, program_name);
599 p = fetch_braces(p, "", tmp, sizeof tmp);
600 ds_put_cstr(s, vlog_get_module_name(module));
603 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
604 ds_put_strftime(s, tmp, NULL);
607 /* Format user-supplied log message and trim trailing new-lines. */
609 va_copy(args, args_);
610 ds_put_format_valist(s, message, args);
612 while (s->length > length && s->string[s->length - 1] == '\n') {
617 ds_put_format(s, "%u", msg_num);
620 ds_put_char(s, '\n');
623 ds_put_cstr(s, vlog_get_level_name(level));
626 ds_put_format(s, "%ld", (long int) getpid());
629 ds_put_format(s, "%lld", time_msec() - boot_time);
632 ds_put_char(s, p[-1]);
635 used = s->length - length;
637 size_t n_pad = field - used;
638 if (justify == RIGHT) {
639 ds_put_uninit(s, n_pad);
640 memmove(&s->string[length + n_pad], &s->string[length], used);
641 memset(&s->string[length], pad, n_pad);
643 ds_put_char_multiple(s, pad, n_pad);
649 /* Writes 'message' to the log at the given 'level' and as coming from the
652 * Guaranteed to preserve errno. */
654 vlog_valist(const struct vlog_module *module, enum vlog_level level,
655 const char *message, va_list args)
657 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
658 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
659 bool log_to_file = module->levels[VLF_FILE] >= level && log_file;
660 if (log_to_console || log_to_syslog || log_to_file) {
661 int save_errno = errno;
662 static unsigned int msg_num;
668 ds_reserve(&s, 1024);
671 if (log_to_console) {
672 format_log_message(module, level, VLF_CONSOLE, msg_num,
674 ds_put_char(&s, '\n');
675 fputs(ds_cstr(&s), stderr);
679 int syslog_level = syslog_levels[level];
680 char *save_ptr = NULL;
683 format_log_message(module, level, VLF_SYSLOG, msg_num,
685 for (line = strtok_r(s.string, "\n", &save_ptr); line;
686 line = strtok_r(NULL, "\n", &save_ptr)) {
687 syslog(syslog_level, "%s", line);
692 format_log_message(module, level, VLF_FILE, msg_num,
694 ds_put_char(&s, '\n');
695 fputs(ds_cstr(&s), log_file);
705 vlog(const struct vlog_module *module, enum vlog_level level,
706 const char *message, ...)
710 va_start(args, message);
711 vlog_valist(module, level, message, args);
716 vlog_fatal_valist(const struct vlog_module *module_,
717 const char *message, va_list args)
719 struct vlog_module *module = (struct vlog_module *) module_;
721 /* Don't log this message to the console to avoid redundancy with the
722 * message written by the later ovs_fatal_valist(). */
723 module->levels[VLF_CONSOLE] = VLL_OFF;
725 vlog_valist(module, VLL_EMER, message, args);
726 ovs_fatal_valist(0, message, args);
730 vlog_fatal(const struct vlog_module *module, const char *message, ...)
734 va_start(args, message);
735 vlog_fatal_valist(module, message, args);
740 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
741 struct vlog_rate_limit *rl)
743 if (!vlog_is_enabled(module, level)) {
747 if (rl->tokens < VLOG_MSG_TOKENS) {
748 time_t now = time_now();
749 if (rl->last_fill > now) {
750 /* Last filled in the future? Time must have gone backward, or
751 * 'rl' has not been used before. */
752 rl->tokens = rl->burst;
753 } else if (rl->last_fill < now) {
754 unsigned int add = sat_mul(rl->rate, now - rl->last_fill);
755 unsigned int tokens = sat_add(rl->tokens, add);
756 rl->tokens = MIN(tokens, rl->burst);
759 if (rl->tokens < VLOG_MSG_TOKENS) {
760 if (!rl->n_dropped) {
761 rl->first_dropped = now;
763 rl->last_dropped = now;
768 rl->tokens -= VLOG_MSG_TOKENS;
771 time_t now = time_now();
772 unsigned int first_dropped_elapsed = now - rl->first_dropped;
773 unsigned int last_dropped_elapsed = now - rl->last_dropped;
776 "Dropped %u log messages in last %u seconds (most recently, "
777 "%u seconds ago) due to excessive rate",
778 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
786 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
787 struct vlog_rate_limit *rl, const char *message, ...)
789 if (!vlog_should_drop(module, level, rl)) {
792 va_start(args, message);
793 vlog_valist(module, level, message, args);
801 printf("\nLogging options:\n"
802 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
803 " -v, --verbose set maximum verbosity level\n"
804 " --log-file[=FILE] enable logging to specified FILE\n"
805 " (default: %s/%s.log)\n",
806 ovs_logdir(), program_name);