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 || !strcasecmp(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 (!strcasecmp(module, "PATTERN")) {
361 vlog_set_pattern(e_facility, save_ptr);
365 enum vlog_level e_level;
367 if (!strcasecmp(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",
468 "{module[:facility[:level]] | PATTERN:facility:pattern}",
469 vlog_unixctl_set, NULL);
470 unixctl_command_register("vlog/list", "", vlog_unixctl_list, NULL);
471 unixctl_command_register("vlog/reopen", "", vlog_unixctl_reopen, NULL);
474 /* Closes the logging subsystem. */
484 /* Print the current logging level for each module. */
486 vlog_get_levels(void)
488 struct ds s = DS_EMPTY_INITIALIZER;
489 struct vlog_module **mp;
490 struct svec lines = SVEC_EMPTY_INITIALIZER;
494 ds_put_format(&s, " console syslog file\n");
495 ds_put_format(&s, " ------- ------ ------\n");
497 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
498 line = xasprintf("%-16s %4s %4s %4s\n",
499 vlog_get_module_name(*mp),
500 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
501 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
502 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
503 svec_add_nocopy(&lines, line);
507 SVEC_FOR_EACH (i, line, &lines) {
508 ds_put_cstr(&s, line);
510 svec_destroy(&lines);
515 /* Returns true if a log message emitted for the given 'module' and 'level'
516 * would cause some log output, false if that module and level are completely
519 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
521 return module->min_level >= level;
525 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
528 size_t n = strcspn(p + 1, "}");
529 size_t n_copy = MIN(n, out_size - 1);
530 memcpy(out, p + 1, n_copy);
534 ovs_strlcpy(out, def, out_size);
540 format_log_message(const struct vlog_module *module, enum vlog_level level,
541 enum vlog_facility facility, unsigned int msg_num,
542 const char *message, va_list args_, struct ds *s)
549 for (p = facilities[facility].pattern; *p != '\0'; ) {
550 enum { LEFT, RIGHT } justify = RIGHT;
552 size_t length, field, used;
555 ds_put_char(s, *p++);
569 while (isdigit((unsigned char)*p)) {
570 field = (field * 10) + (*p - '0');
577 ds_put_cstr(s, program_name);
580 p = fetch_braces(p, "", tmp, sizeof tmp);
581 ds_put_cstr(s, vlog_get_module_name(module));
584 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
585 ds_put_strftime(s, tmp, NULL);
588 /* Format user-supplied log message and trim trailing new-lines. */
590 va_copy(args, args_);
591 ds_put_format_valist(s, message, args);
593 while (s->length > length && s->string[s->length - 1] == '\n') {
598 ds_put_format(s, "%u", msg_num);
601 ds_put_char(s, '\n');
604 ds_put_cstr(s, vlog_get_level_name(level));
607 ds_put_format(s, "%ld", (long int) getpid());
610 ds_put_format(s, "%lld", time_msec() - boot_time);
613 ds_put_char(s, p[-1]);
616 used = s->length - length;
618 size_t n_pad = field - used;
619 if (justify == RIGHT) {
620 ds_put_uninit(s, n_pad);
621 memmove(&s->string[length + n_pad], &s->string[length], used);
622 memset(&s->string[length], pad, n_pad);
624 ds_put_char_multiple(s, pad, n_pad);
630 /* Writes 'message' to the log at the given 'level' and as coming from the
633 * Guaranteed to preserve errno. */
635 vlog_valist(const struct vlog_module *module, enum vlog_level level,
636 const char *message, va_list args)
638 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
639 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
640 bool log_to_file = module->levels[VLF_FILE] >= level && log_file;
641 if (log_to_console || log_to_syslog || log_to_file) {
642 int save_errno = errno;
643 static unsigned int msg_num;
649 ds_reserve(&s, 1024);
652 if (log_to_console) {
653 format_log_message(module, level, VLF_CONSOLE, msg_num,
655 ds_put_char(&s, '\n');
656 fputs(ds_cstr(&s), stderr);
660 int syslog_level = syslog_levels[level];
661 char *save_ptr = NULL;
664 format_log_message(module, level, VLF_SYSLOG, msg_num,
666 for (line = strtok_r(s.string, "\n", &save_ptr); line;
667 line = strtok_r(NULL, "\n", &save_ptr)) {
668 syslog(syslog_level, "%s", line);
673 format_log_message(module, level, VLF_FILE, msg_num,
675 ds_put_char(&s, '\n');
676 fputs(ds_cstr(&s), log_file);
686 vlog(const struct vlog_module *module, enum vlog_level level,
687 const char *message, ...)
691 va_start(args, message);
692 vlog_valist(module, level, message, args);
697 vlog_fatal_valist(const struct vlog_module *module_,
698 const char *message, va_list args)
700 struct vlog_module *module = (struct vlog_module *) module_;
702 /* Don't log this message to the console to avoid redundancy with the
703 * message written by the later ovs_fatal_valist(). */
704 module->levels[VLF_CONSOLE] = VLL_OFF;
706 vlog_valist(module, VLL_EMER, message, args);
707 ovs_fatal_valist(0, message, args);
711 vlog_fatal(const struct vlog_module *module, const char *message, ...)
715 va_start(args, message);
716 vlog_fatal_valist(module, message, args);
721 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
722 struct vlog_rate_limit *rl)
724 if (!vlog_is_enabled(module, level)) {
728 if (rl->tokens < VLOG_MSG_TOKENS) {
729 time_t now = time_now();
730 if (rl->last_fill > now) {
731 /* Last filled in the future? Time must have gone backward, or
732 * 'rl' has not been used before. */
733 rl->tokens = rl->burst;
734 } else if (rl->last_fill < now) {
735 unsigned int add = sat_mul(rl->rate, now - rl->last_fill);
736 unsigned int tokens = sat_add(rl->tokens, add);
737 rl->tokens = MIN(tokens, rl->burst);
740 if (rl->tokens < VLOG_MSG_TOKENS) {
741 if (!rl->n_dropped) {
742 rl->first_dropped = now;
744 rl->last_dropped = now;
749 rl->tokens -= VLOG_MSG_TOKENS;
752 time_t now = time_now();
753 unsigned int first_dropped_elapsed = now - rl->first_dropped;
754 unsigned int last_dropped_elapsed = now - rl->last_dropped;
757 "Dropped %u log messages in last %u seconds (most recently, "
758 "%u seconds ago) due to excessive rate",
759 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
767 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
768 struct vlog_rate_limit *rl, const char *message, ...)
770 if (!vlog_should_drop(module, level, rl)) {
773 va_start(args, message);
774 vlog_valist(module, level, message, args);
782 printf("\nLogging options:\n"
783 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
784 " -v, --verbose set maximum verbosity level\n"
785 " --log-file[=FILE] enable logging to specified FILE\n"
786 " (default: %s/%s.log)\n",
787 ovs_logdir(), program_name);