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.
25 #include <sys/types.h>
30 #include "dynamic-string.h"
37 VLOG_DEFINE_THIS_MODULE(vlog);
39 /* Name for each logging level. */
40 static const char *level_names[VLL_N_LEVELS] = {
41 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
46 /* Syslog value for each logging level. */
47 static int syslog_levels[VLL_N_LEVELS] = {
48 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
53 /* The log modules. */
54 #if USE_LINKER_SECTIONS
55 extern struct vlog_module *__start_vlog_modules[];
56 extern struct vlog_module *__stop_vlog_modules[];
57 #define vlog_modules __start_vlog_modules
58 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
60 #define VLOG_MODULE VLOG_DEFINE_MODULE__
61 #include "vlog-modules.def"
64 struct vlog_module *vlog_modules[] = {
65 #define VLOG_MODULE(NAME) &VLM_##NAME,
66 #include "vlog-modules.def"
69 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
72 /* Information about each facility. */
74 const char *name; /* Name. */
75 char *pattern; /* Current pattern. */
76 bool default_pattern; /* Whether current pattern is the default. */
78 static struct facility facilities[VLF_N_FACILITIES] = {
79 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
84 /* Time at which vlog was initialized, in milliseconds. */
85 static long long int boot_time;
87 /* VLF_FILE configuration. */
88 static char *log_file_name;
89 static FILE *log_file;
91 /* vlog initialized? */
92 static bool vlog_inited;
94 static void format_log_message(const struct vlog_module *, enum vlog_level,
95 enum vlog_facility, unsigned int msg_num,
96 const char *message, va_list, struct ds *)
99 /* Searches the 'n_names' in 'names'. Returns the index of a match for
100 * 'target', or 'n_names' if no name matches. */
102 search_name_array(const char *target, const char **names, size_t n_names)
106 for (i = 0; i < n_names; i++) {
108 if (!strcasecmp(names[i], target)) {
115 /* Returns the name for logging level 'level'. */
117 vlog_get_level_name(enum vlog_level level)
119 assert(level < VLL_N_LEVELS);
120 return level_names[level];
123 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
124 * is not the name of a logging level. */
126 vlog_get_level_val(const char *name)
128 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
131 /* Returns the name for logging facility 'facility'. */
133 vlog_get_facility_name(enum vlog_facility facility)
135 assert(facility < VLF_N_FACILITIES);
136 return facilities[facility].name;
139 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
140 * not the name of a logging facility. */
142 vlog_get_facility_val(const char *name)
146 for (i = 0; i < VLF_N_FACILITIES; i++) {
147 if (!strcasecmp(facilities[i].name, name)) {
154 /* Returns the name for logging module 'module'. */
156 vlog_get_module_name(const struct vlog_module *module)
161 /* Returns the logging module named 'name', or NULL if 'name' is not the name
162 * of a logging module. */
164 vlog_module_from_name(const char *name)
166 struct vlog_module **mp;
168 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
169 if (!strcasecmp(name, (*mp)->name)) {
176 /* Returns the current logging level for the given 'module' and 'facility'. */
178 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
180 assert(facility < VLF_N_FACILITIES);
181 return module->levels[facility];
185 update_min_level(struct vlog_module *module)
187 enum vlog_facility facility;
189 module->min_level = VLL_OFF;
190 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
191 if (log_file || facility != VLF_FILE) {
192 enum vlog_level level = module->levels[facility];
193 if (level > module->min_level) {
194 module->min_level = level;
201 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
202 enum vlog_level level)
204 assert(facility >= 0 && facility < VLF_N_FACILITIES);
205 assert(level < VLL_N_LEVELS);
208 struct vlog_module **mp;
210 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
211 (*mp)->levels[facility] = level;
212 update_min_level(*mp);
215 module->levels[facility] = level;
216 update_min_level(module);
220 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
221 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
222 * across all modules or facilities, respectively. */
224 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
225 enum vlog_level level)
227 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
228 if (facility == VLF_ANY_FACILITY) {
229 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
230 set_facility_level(facility, module, level);
233 set_facility_level(facility, module, level);
238 do_set_pattern(enum vlog_facility facility, const char *pattern)
240 struct facility *f = &facilities[facility];
241 if (!f->default_pattern) {
244 f->default_pattern = false;
246 f->pattern = xstrdup(pattern);
249 /* Sets the pattern for the given 'facility' to 'pattern'. */
251 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
253 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
254 if (facility == VLF_ANY_FACILITY) {
255 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
256 do_set_pattern(facility, pattern);
259 do_set_pattern(facility, pattern);
263 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
264 * log file has been set. (A non-null return value does not assert that the
265 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
266 * fails, it still sets the log file name.) */
268 vlog_get_log_file(void)
270 return log_file_name;
273 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
274 * default file name if 'file_name' is null. Returns 0 if successful,
275 * otherwise a positive errno value. */
277 vlog_set_log_file(const char *file_name)
279 char *old_log_file_name;
280 struct vlog_module **mp;
283 /* Close old log file. */
285 VLOG_INFO("closing log file");
290 /* Update log file name and free old name. The ordering is important
291 * because 'file_name' might be 'log_file_name' or some suffix of it. */
292 old_log_file_name = log_file_name;
293 log_file_name = (file_name
295 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
296 free(old_log_file_name);
297 file_name = NULL; /* Might have been freed. */
299 /* Open new log file and update min_levels[] to reflect whether we actually
300 * have a log_file. */
301 log_file = fopen(log_file_name, "a");
302 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
303 update_min_level(*mp);
306 /* Log success or failure. */
308 VLOG_WARN("failed to open %s for logging: %s",
309 log_file_name, strerror(errno));
312 VLOG_INFO("opened log file %s", log_file_name);
319 /* Closes and then attempts to re-open the current log file. (This is useful
320 * just after log rotation, to ensure that the new log file starts being used.)
321 * Returns 0 if successful, otherwise a positive errno value. */
323 vlog_reopen_log_file(void)
325 return log_file_name ? vlog_set_log_file(log_file_name) : 0;
328 /* Set debugging levels:
330 * mod[:facility[:level]] mod2[:facility[:level]] ...
332 * Return null if successful, otherwise an error message that the caller must
336 vlog_set_levels_from_string(const char *s_)
338 char *save_ptr = NULL;
339 char *s = xstrdup(s_);
340 char *module, *facility;
342 for (module = strtok_r(s, ": \t", &save_ptr); module != NULL;
343 module = strtok_r(NULL, ": \t", &save_ptr)) {
344 struct vlog_module *e_module;
345 enum vlog_facility e_facility;
347 facility = strtok_r(NULL, ":", &save_ptr);
349 if (!facility || !strcmp(facility, "ANY")) {
350 e_facility = VLF_ANY_FACILITY;
352 e_facility = vlog_get_facility_val(facility);
353 if (e_facility >= VLF_N_FACILITIES) {
354 char *msg = xasprintf("unknown facility \"%s\"", facility);
360 if (!strcmp(module, "PATTERN")) {
361 vlog_set_pattern(e_facility, save_ptr);
365 enum vlog_level e_level;
367 if (!strcmp(module, "ANY")) {
370 e_module = vlog_module_from_name(module);
372 char *msg = xasprintf("unknown module \"%s\"", module);
378 level = strtok_r(NULL, ":", &save_ptr);
379 e_level = level ? vlog_get_level_val(level) : VLL_DBG;
380 if (e_level >= VLL_N_LEVELS) {
381 char *msg = xasprintf("unknown level \"%s\"", level);
386 vlog_set_levels(e_module, e_facility, e_level);
393 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
394 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
396 vlog_set_verbosity(const char *arg)
399 char *msg = vlog_set_levels_from_string(arg);
401 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
404 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
409 vlog_unixctl_set(struct unixctl_conn *conn,
410 const char *args, void *aux OVS_UNUSED)
412 char *msg = vlog_set_levels_from_string(args);
413 unixctl_command_reply(conn, msg ? 501 : 202, msg);
418 vlog_unixctl_list(struct unixctl_conn *conn,
419 const char *args OVS_UNUSED, void *aux OVS_UNUSED)
421 char *msg = vlog_get_levels();
422 unixctl_command_reply(conn, 200, msg);
427 vlog_unixctl_reopen(struct unixctl_conn *conn,
428 const char *args OVS_UNUSED, void *aux OVS_UNUSED)
431 int error = vlog_reopen_log_file();
433 unixctl_command_reply(conn, 503, strerror(errno));
435 unixctl_command_reply(conn, 202, NULL);
438 unixctl_command_reply(conn, 403, "Logging to file not configured");
442 /* Initializes the logging subsystem and registers its unixctl server
454 openlog(program_name, LOG_NDELAY, LOG_DAEMON);
456 boot_time = time_msec();
462 localtime_r(&now, &tm);
463 strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
464 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
467 unixctl_command_register("vlog/set", vlog_unixctl_set, NULL);
468 unixctl_command_register("vlog/list", vlog_unixctl_list, NULL);
469 unixctl_command_register("vlog/reopen", vlog_unixctl_reopen, NULL);
472 /* Closes the logging subsystem. */
482 /* Print the current logging level for each module. */
484 vlog_get_levels(void)
486 struct ds s = DS_EMPTY_INITIALIZER;
487 struct vlog_module **mp;
488 struct svec lines = SVEC_EMPTY_INITIALIZER;
492 ds_put_format(&s, " console syslog file\n");
493 ds_put_format(&s, " ------- ------ ------\n");
495 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
496 line = xasprintf("%-16s %4s %4s %4s\n",
497 vlog_get_module_name(*mp),
498 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
499 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
500 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
501 svec_add_nocopy(&lines, line);
505 SVEC_FOR_EACH (i, line, &lines) {
506 ds_put_cstr(&s, line);
508 svec_destroy(&lines);
513 /* Returns true if a log message emitted for the given 'module' and 'level'
514 * would cause some log output, false if that module and level are completely
517 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
519 return module->min_level >= level;
523 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
526 size_t n = strcspn(p + 1, "}");
527 size_t n_copy = MIN(n, out_size - 1);
528 memcpy(out, p + 1, n_copy);
532 ovs_strlcpy(out, def, out_size);
538 format_log_message(const struct vlog_module *module, enum vlog_level level,
539 enum vlog_facility facility, unsigned int msg_num,
540 const char *message, va_list args_, struct ds *s)
547 for (p = facilities[facility].pattern; *p != '\0'; ) {
548 enum { LEFT, RIGHT } justify = RIGHT;
550 size_t length, field, used;
553 ds_put_char(s, *p++);
567 while (isdigit((unsigned char)*p)) {
568 field = (field * 10) + (*p - '0');
575 ds_put_cstr(s, program_name);
578 p = fetch_braces(p, "", tmp, sizeof tmp);
579 ds_put_cstr(s, vlog_get_module_name(module));
582 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
583 ds_put_strftime(s, tmp, NULL);
586 /* Format user-supplied log message and trim trailing new-lines. */
588 va_copy(args, args_);
589 ds_put_format_valist(s, message, args);
591 while (s->length > length && s->string[s->length - 1] == '\n') {
596 ds_put_format(s, "%u", msg_num);
599 ds_put_char(s, '\n');
602 ds_put_cstr(s, vlog_get_level_name(level));
605 ds_put_format(s, "%ld", (long int) getpid());
608 ds_put_format(s, "%lld", time_msec() - boot_time);
611 ds_put_char(s, p[-1]);
614 used = s->length - length;
616 size_t n_pad = field - used;
617 if (justify == RIGHT) {
618 ds_put_uninit(s, n_pad);
619 memmove(&s->string[length + n_pad], &s->string[length], used);
620 memset(&s->string[length], pad, n_pad);
622 ds_put_char_multiple(s, pad, n_pad);
628 /* Writes 'message' to the log at the given 'level' and as coming from the
631 * Guaranteed to preserve errno. */
633 vlog_valist(const struct vlog_module *module, enum vlog_level level,
634 const char *message, va_list args)
636 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
637 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
638 bool log_to_file = module->levels[VLF_FILE] >= level && log_file;
639 if (log_to_console || log_to_syslog || log_to_file) {
640 int save_errno = errno;
641 static unsigned int msg_num;
647 ds_reserve(&s, 1024);
650 if (log_to_console) {
651 format_log_message(module, level, VLF_CONSOLE, msg_num,
653 ds_put_char(&s, '\n');
654 fputs(ds_cstr(&s), stderr);
658 int syslog_level = syslog_levels[level];
659 char *save_ptr = NULL;
662 format_log_message(module, level, VLF_SYSLOG, msg_num,
664 for (line = strtok_r(s.string, "\n", &save_ptr); line;
665 line = strtok_r(NULL, "\n", &save_ptr)) {
666 syslog(syslog_level, "%s", line);
671 format_log_message(module, level, VLF_FILE, msg_num,
673 ds_put_char(&s, '\n');
674 fputs(ds_cstr(&s), log_file);
684 vlog(const struct vlog_module *module, enum vlog_level level,
685 const char *message, ...)
689 va_start(args, message);
690 vlog_valist(module, level, message, args);
695 vlog_fatal_valist(const struct vlog_module *module_,
696 const char *message, va_list args)
698 struct vlog_module *module = (struct vlog_module *) module_;
700 /* Don't log this message to the console to avoid redundancy with the
701 * message written by the later ovs_fatal_valist(). */
702 module->levels[VLF_CONSOLE] = VLL_OFF;
704 vlog_valist(module, VLL_EMER, message, args);
705 ovs_fatal_valist(0, message, args);
709 vlog_fatal(const struct vlog_module *module, const char *message, ...)
713 va_start(args, message);
714 vlog_fatal_valist(module, message, args);
719 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
720 struct vlog_rate_limit *rl)
722 if (!vlog_is_enabled(module, level)) {
726 if (rl->tokens < VLOG_MSG_TOKENS) {
727 time_t now = time_now();
728 if (rl->last_fill > now) {
729 /* Last filled in the future? Time must have gone backward, or
730 * 'rl' has not been used before. */
731 rl->tokens = rl->burst;
732 } else if (rl->last_fill < now) {
733 unsigned int add = sat_mul(rl->rate, now - rl->last_fill);
734 unsigned int tokens = sat_add(rl->tokens, add);
735 rl->tokens = MIN(tokens, rl->burst);
738 if (rl->tokens < VLOG_MSG_TOKENS) {
739 if (!rl->n_dropped) {
740 rl->first_dropped = now;
742 rl->last_dropped = now;
747 rl->tokens -= VLOG_MSG_TOKENS;
750 time_t now = time_now();
751 unsigned int first_dropped_elapsed = now - rl->first_dropped;
752 unsigned int last_dropped_elapsed = now - rl->last_dropped;
755 "Dropped %u log messages in last %u seconds (most recently, "
756 "%u seconds ago) due to excessive rate",
757 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
765 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
766 struct vlog_rate_limit *rl, const char *message, ...)
768 if (!vlog_should_drop(module, level, rl)) {
771 va_start(args, message);
772 vlog_valist(module, level, message, args);
780 printf("\nLogging options:\n"
781 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
782 " -v, --verbose set maximum verbosity level\n"
783 " --log-file[=FILE] enable logging to specified FILE\n"
784 " (default: %s/%s.log)\n",
785 ovs_logdir(), program_name);