]> git.proxmox.com Git - mirror_ovs.git/blame - lib/vlog.c
util: Make subprogram_name thread-specific.
[mirror_ovs.git] / lib / vlog.c
CommitLineData
064af421 1/*
4958e3ee 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
064af421 3 *
a14bc59f
BP
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:
064af421 7 *
a14bc59f
BP
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
064af421
BP
15 */
16
17#include <config.h>
18#include "vlog.h"
19#include <assert.h>
20#include <ctype.h>
21#include <errno.h>
9eb94563 22#include <fcntl.h>
064af421
BP
23#include <stdarg.h>
24#include <stdlib.h>
25#include <string.h>
68cb8aaf 26#include <sys/stat.h>
064af421
BP
27#include <sys/types.h>
28#include <syslog.h>
29#include <time.h>
30#include <unistd.h>
4958e3ee 31#include "coverage.h"
064af421
BP
32#include "dirs.h"
33#include "dynamic-string.h"
cbb13e8e 34#include "ofpbuf.h"
064af421 35#include "sat-math.h"
8628b0b7 36#include "svec.h"
064af421
BP
37#include "timeval.h"
38#include "unixctl.h"
39#include "util.h"
40
d98e6007 41VLOG_DEFINE_THIS_MODULE(vlog);
064af421 42
4958e3ee
BP
43COVERAGE_DEFINE(vlog_recursive);
44
45/* ovs_assert() logs the assertion message, so using ovs_assert() in this
46 * source file could cause recursion. */
47#undef ovs_assert
48#define ovs_assert use_assert_instead_of_ovs_assert_in_this_module
49
064af421 50/* Name for each logging level. */
4b5f1d2c 51static const char *const level_names[VLL_N_LEVELS] = {
064af421
BP
52#define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
53 VLOG_LEVELS
54#undef VLOG_LEVEL
55};
56
57/* Syslog value for each logging level. */
4b5f1d2c 58static const int syslog_levels[VLL_N_LEVELS] = {
064af421
BP
59#define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
60 VLOG_LEVELS
61#undef VLOG_LEVEL
62};
63
480ce8ab
BP
64/* The log modules. */
65#if USE_LINKER_SECTIONS
66extern struct vlog_module *__start_vlog_modules[];
67extern struct vlog_module *__stop_vlog_modules[];
68#define vlog_modules __start_vlog_modules
69#define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
70#else
71#define VLOG_MODULE VLOG_DEFINE_MODULE__
72#include "vlog-modules.def"
73#undef VLOG_MODULE
74
75struct vlog_module *vlog_modules[] = {
76#define VLOG_MODULE(NAME) &VLM_##NAME,
064af421
BP
77#include "vlog-modules.def"
78#undef VLOG_MODULE
79};
480ce8ab
BP
80#define n_vlog_modules ARRAY_SIZE(vlog_modules)
81#endif
064af421
BP
82
83/* Information about each facility. */
84struct facility {
85 const char *name; /* Name. */
86 char *pattern; /* Current pattern. */
87 bool default_pattern; /* Whether current pattern is the default. */
88};
89static struct facility facilities[VLF_N_FACILITIES] = {
90#define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
91 VLOG_FACILITIES
92#undef VLOG_FACILITY
93};
94
064af421
BP
95/* VLF_FILE configuration. */
96static char *log_file_name;
9eb94563 97static int log_fd = -1;
064af421 98
1e8cf0f7
BP
99/* vlog initialized? */
100static bool vlog_inited;
101
480ce8ab 102static void format_log_message(const struct vlog_module *, enum vlog_level,
064af421
BP
103 enum vlog_facility, unsigned int msg_num,
104 const char *message, va_list, struct ds *)
105 PRINTF_FORMAT(5, 0);
106
107/* Searches the 'n_names' in 'names'. Returns the index of a match for
108 * 'target', or 'n_names' if no name matches. */
109static size_t
4b5f1d2c 110search_name_array(const char *target, const char *const *names, size_t n_names)
064af421
BP
111{
112 size_t i;
113
114 for (i = 0; i < n_names; i++) {
115 assert(names[i]);
116 if (!strcasecmp(names[i], target)) {
117 break;
118 }
119 }
120 return i;
121}
122
123/* Returns the name for logging level 'level'. */
124const char *
125vlog_get_level_name(enum vlog_level level)
126{
127 assert(level < VLL_N_LEVELS);
128 return level_names[level];
129}
130
131/* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
132 * is not the name of a logging level. */
133enum vlog_level
d295e8e9 134vlog_get_level_val(const char *name)
064af421
BP
135{
136 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
137}
138
139/* Returns the name for logging facility 'facility'. */
140const char *
d295e8e9 141vlog_get_facility_name(enum vlog_facility facility)
064af421
BP
142{
143 assert(facility < VLF_N_FACILITIES);
144 return facilities[facility].name;
145}
146
147/* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
148 * not the name of a logging facility. */
149enum vlog_facility
d295e8e9 150vlog_get_facility_val(const char *name)
064af421
BP
151{
152 size_t i;
153
154 for (i = 0; i < VLF_N_FACILITIES; i++) {
155 if (!strcasecmp(facilities[i].name, name)) {
156 break;
157 }
158 }
159 return i;
160}
161
162/* Returns the name for logging module 'module'. */
480ce8ab
BP
163const char *
164vlog_get_module_name(const struct vlog_module *module)
064af421 165{
480ce8ab 166 return module->name;
064af421
BP
167}
168
480ce8ab
BP
169/* Returns the logging module named 'name', or NULL if 'name' is not the name
170 * of a logging module. */
171struct vlog_module *
172vlog_module_from_name(const char *name)
064af421 173{
480ce8ab
BP
174 struct vlog_module **mp;
175
176 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
177 if (!strcasecmp(name, (*mp)->name)) {
178 return *mp;
179 }
180 }
181 return NULL;
064af421
BP
182}
183
184/* Returns the current logging level for the given 'module' and 'facility'. */
185enum vlog_level
d295e8e9 186vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
064af421 187{
064af421 188 assert(facility < VLF_N_FACILITIES);
480ce8ab 189 return module->levels[facility];
064af421
BP
190}
191
192static void
480ce8ab 193update_min_level(struct vlog_module *module)
064af421 194{
064af421
BP
195 enum vlog_facility facility;
196
c1a543a8 197 module->min_level = VLL_OFF;
064af421 198 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
9eb94563 199 if (log_fd >= 0 || facility != VLF_FILE) {
480ce8ab 200 enum vlog_level level = module->levels[facility];
56cee53b 201 if (level > module->min_level) {
480ce8ab
BP
202 module->min_level = level;
203 }
064af421
BP
204 }
205 }
064af421
BP
206}
207
208static void
480ce8ab 209set_facility_level(enum vlog_facility facility, struct vlog_module *module,
064af421
BP
210 enum vlog_level level)
211{
212 assert(facility >= 0 && facility < VLF_N_FACILITIES);
213 assert(level < VLL_N_LEVELS);
214
480ce8ab
BP
215 if (!module) {
216 struct vlog_module **mp;
217
218 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
219 (*mp)->levels[facility] = level;
220 update_min_level(*mp);
064af421
BP
221 }
222 } else {
480ce8ab 223 module->levels[facility] = level;
064af421
BP
224 update_min_level(module);
225 }
226}
227
480ce8ab
BP
228/* Sets the logging level for the given 'module' and 'facility' to 'level'. A
229 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
230 * across all modules or facilities, respectively. */
064af421 231void
480ce8ab 232vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
d295e8e9 233 enum vlog_level level)
064af421
BP
234{
235 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
236 if (facility == VLF_ANY_FACILITY) {
237 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
238 set_facility_level(facility, module, level);
239 }
240 } else {
241 set_facility_level(facility, module, level);
242 }
243}
244
245static void
d295e8e9 246do_set_pattern(enum vlog_facility facility, const char *pattern)
064af421
BP
247{
248 struct facility *f = &facilities[facility];
249 if (!f->default_pattern) {
250 free(f->pattern);
251 } else {
252 f->default_pattern = false;
253 }
254 f->pattern = xstrdup(pattern);
255}
256
257/* Sets the pattern for the given 'facility' to 'pattern'. */
258void
259vlog_set_pattern(enum vlog_facility facility, const char *pattern)
260{
261 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
262 if (facility == VLF_ANY_FACILITY) {
263 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
264 do_set_pattern(facility, pattern);
265 }
266 } else {
267 do_set_pattern(facility, pattern);
268 }
269}
270
271/* Returns the name of the log file used by VLF_FILE, or a null pointer if no
272 * log file has been set. (A non-null return value does not assert that the
273 * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
274 * fails, it still sets the log file name.) */
275const char *
276vlog_get_log_file(void)
277{
278 return log_file_name;
279}
280
281/* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
282 * default file name if 'file_name' is null. Returns 0 if successful,
283 * otherwise a positive errno value. */
284int
285vlog_set_log_file(const char *file_name)
286{
287 char *old_log_file_name;
480ce8ab 288 struct vlog_module **mp;
064af421
BP
289 int error;
290
291 /* Close old log file. */
9eb94563 292 if (log_fd >= 0) {
064af421 293 VLOG_INFO("closing log file");
9eb94563
BP
294 close(log_fd);
295 log_fd = -1;
064af421
BP
296 }
297
298 /* Update log file name and free old name. The ordering is important
299 * because 'file_name' might be 'log_file_name' or some suffix of it. */
300 old_log_file_name = log_file_name;
301 log_file_name = (file_name
302 ? xstrdup(file_name)
b43c6fe2 303 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
064af421
BP
304 free(old_log_file_name);
305 file_name = NULL; /* Might have been freed. */
306
307 /* Open new log file and update min_levels[] to reflect whether we actually
308 * have a log_file. */
9eb94563 309 log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
480ce8ab
BP
310 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
311 update_min_level(*mp);
064af421
BP
312 }
313
314 /* Log success or failure. */
9eb94563 315 if (log_fd < 0) {
064af421 316 VLOG_WARN("failed to open %s for logging: %s",
10a89ef0 317 log_file_name, ovs_strerror(errno));
064af421
BP
318 error = errno;
319 } else {
320 VLOG_INFO("opened log file %s", log_file_name);
321 error = 0;
322 }
323
324 return error;
325}
326
327/* Closes and then attempts to re-open the current log file. (This is useful
328 * just after log rotation, to ensure that the new log file starts being used.)
329 * Returns 0 if successful, otherwise a positive errno value. */
330int
331vlog_reopen_log_file(void)
332{
68cb8aaf
BP
333 struct stat old, new;
334
335 /* Skip re-opening if there's nothing to reopen. */
336 if (!log_file_name) {
337 return 0;
338 }
339
340 /* Skip re-opening if it would be a no-op because the old and new files are
341 * the same. (This avoids writing "closing log file" followed immediately
342 * by "opened log file".) */
9eb94563
BP
343 if (log_fd >= 0
344 && !fstat(log_fd, &old)
68cb8aaf
BP
345 && !stat(log_file_name, &new)
346 && old.st_dev == new.st_dev
347 && old.st_ino == new.st_ino) {
348 return 0;
349 }
350
351 return vlog_set_log_file(log_file_name);
064af421
BP
352}
353
2a3e30b2
BP
354/* Set debugging levels. Returns null if successful, otherwise an error
355 * message that the caller must free(). */
064af421
BP
356char *
357vlog_set_levels_from_string(const char *s_)
358{
064af421 359 char *s = xstrdup(s_);
2a3e30b2
BP
360 char *save_ptr = NULL;
361 char *msg = NULL;
362 char *word;
064af421 363
2a3e30b2
BP
364 word = strtok_r(s, " ,:\t", &save_ptr);
365 if (word && !strcasecmp(word, "PATTERN")) {
366 enum vlog_facility facility;
064af421 367
2a3e30b2
BP
368 word = strtok_r(NULL, " ,:\t", &save_ptr);
369 if (!word) {
370 msg = xstrdup("missing facility");
371 goto exit;
064af421
BP
372 }
373
2a3e30b2
BP
374 facility = (!strcasecmp(word, "ANY")
375 ? VLF_ANY_FACILITY
376 : vlog_get_facility_val(word));
377 if (facility == VLF_N_FACILITIES) {
378 msg = xasprintf("unknown facility \"%s\"", word);
379 goto exit;
380 }
381 vlog_set_pattern(facility, save_ptr);
382 } else {
383 struct vlog_module *module = NULL;
384 enum vlog_level level = VLL_N_LEVELS;
385 enum vlog_facility facility = VLF_N_FACILITIES;
386
387 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
388 if (!strcasecmp(word, "ANY")) {
389 continue;
390 } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
391 if (facility != VLF_N_FACILITIES) {
392 msg = xstrdup("cannot specify multiple facilities");
393 goto exit;
064af421 394 }
2a3e30b2
BP
395 facility = vlog_get_facility_val(word);
396 } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
397 if (level != VLL_N_LEVELS) {
398 msg = xstrdup("cannot specify multiple levels");
399 goto exit;
400 }
401 level = vlog_get_level_val(word);
402 } else if (vlog_module_from_name(word)) {
403 if (module) {
404 msg = xstrdup("cannot specify multiple modules");
405 goto exit;
406 }
407 module = vlog_module_from_name(word);
408 } else {
409 msg = xasprintf("no facility, level, or module \"%s\"", word);
410 goto exit;
064af421 411 }
2a3e30b2 412 }
064af421 413
2a3e30b2
BP
414 if (facility == VLF_N_FACILITIES) {
415 facility = VLF_ANY_FACILITY;
416 }
417 if (level == VLL_N_LEVELS) {
418 level = VLL_DBG;
064af421 419 }
2a3e30b2 420 vlog_set_levels(module, facility, level);
064af421 421 }
2a3e30b2
BP
422
423exit:
064af421 424 free(s);
2a3e30b2 425 return msg;
064af421
BP
426}
427
316bd0f8
BP
428/* Set debugging levels. Abort with an error message if 's' is invalid. */
429void
430vlog_set_levels_from_string_assert(const char *s)
431{
432 char *error = vlog_set_levels_from_string(s);
433 if (error) {
434 ovs_fatal(0, "%s", error);
435 }
436}
437
064af421
BP
438/* If 'arg' is null, configure maximum verbosity. Otherwise, sets
439 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
440void
441vlog_set_verbosity(const char *arg)
442{
443 if (arg) {
444 char *msg = vlog_set_levels_from_string(arg);
445 if (msg) {
446 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
447 }
448 } else {
480ce8ab 449 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
064af421
BP
450 }
451}
452
453static void
0e15264f
BP
454vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
455 void *aux OVS_UNUSED)
064af421 456{
0e15264f
BP
457 int i;
458
459 for (i = 1; i < argc; i++) {
460 char *msg = vlog_set_levels_from_string(argv[i]);
461 if (msg) {
bde9f75d 462 unixctl_command_reply_error(conn, msg);
0e15264f
BP
463 free(msg);
464 return;
465 }
466 }
bde9f75d 467 unixctl_command_reply(conn, NULL);
064af421
BP
468}
469
470static void
0e15264f
BP
471vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
472 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
064af421
BP
473{
474 char *msg = vlog_get_levels();
bde9f75d 475 unixctl_command_reply(conn, msg);
064af421
BP
476 free(msg);
477}
478
479static void
0e15264f
BP
480vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
481 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
064af421
BP
482{
483 if (log_file_name) {
484 int error = vlog_reopen_log_file();
485 if (error) {
10a89ef0 486 unixctl_command_reply_error(conn, ovs_strerror(errno));
064af421 487 } else {
bde9f75d 488 unixctl_command_reply(conn, NULL);
064af421
BP
489 }
490 } else {
bde9f75d 491 unixctl_command_reply_error(conn, "Logging to file not configured");
064af421
BP
492 }
493}
494
4958e3ee
BP
495static void
496set_all_rate_limits(bool enable)
497{
498 struct vlog_module **mp;
499
500 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
501 (*mp)->honor_rate_limits = enable;
502 }
503}
504
505static void
506set_rate_limits(struct unixctl_conn *conn, int argc,
507 const char *argv[], bool enable)
508{
509 if (argc > 1) {
510 int i;
511
512 for (i = 1; i < argc; i++) {
513 if (!strcasecmp(argv[i], "ANY")) {
514 set_all_rate_limits(enable);
515 } else {
516 struct vlog_module *module = vlog_module_from_name(argv[i]);
517 if (!module) {
518 unixctl_command_reply_error(conn, "unknown module");
519 return;
520 }
521 module->honor_rate_limits = enable;
522 }
523 }
524 } else {
525 set_all_rate_limits(enable);
526 }
527 unixctl_command_reply(conn, NULL);
528}
529
530static void
531vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
532 const char *argv[], void *aux OVS_UNUSED)
533{
534 set_rate_limits(conn, argc, argv, true);
535}
536
537static void
538vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
539 const char *argv[], void *aux OVS_UNUSED)
540{
541 set_rate_limits(conn, argc, argv, false);
542}
543
df5d2ed9
BP
544/* Initializes the logging subsystem and registers its unixctl server
545 * commands. */
064af421 546void
d295e8e9 547vlog_init(void)
064af421 548{
487657b2 549 static char *program_name_copy;
064af421
BP
550 time_t now;
551
1e8cf0f7
BP
552 if (vlog_inited) {
553 return;
554 }
555 vlog_inited = true;
556
487657b2
BP
557 /* openlog() is allowed to keep the pointer passed in, without making a
558 * copy. The daemonize code sometimes frees and replaces 'program_name',
559 * so make a private copy just for openlog(). (We keep a pointer to the
560 * private copy to suppress memory leak warnings in case openlog() does
561 * make its own copy.) */
562 program_name_copy = program_name ? xstrdup(program_name) : NULL;
563 openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
064af421 564
c73814a3 565 now = time_wall();
064af421 566 if (now < 0) {
3e78870d 567 char *s = xastrftime("%a, %d %b %Y %H:%M:%S", now, true);
064af421 568 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
3e78870d 569 free(s);
064af421
BP
570 }
571
0e15264f 572 unixctl_command_register(
2a3e30b2 573 "vlog/set", "{spec | PATTERN:facility:pattern}",
0e15264f
BP
574 1, INT_MAX, vlog_unixctl_set, NULL);
575 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
4958e3ee
BP
576 unixctl_command_register("vlog/enable-rate-limit", "[module]...",
577 0, INT_MAX, vlog_enable_rate_limit, NULL);
578 unixctl_command_register("vlog/disable-rate-limit", "[module]...",
579 0, INT_MAX, vlog_disable_rate_limit, NULL);
0e15264f
BP
580 unixctl_command_register("vlog/reopen", "", 0, 0,
581 vlog_unixctl_reopen, NULL);
064af421
BP
582}
583
584/* Closes the logging subsystem. */
585void
d295e8e9 586vlog_exit(void)
064af421 587{
1e8cf0f7
BP
588 if (vlog_inited) {
589 closelog();
590 vlog_inited = false;
591 }
064af421
BP
592}
593
594/* Print the current logging level for each module. */
595char *
596vlog_get_levels(void)
597{
598 struct ds s = DS_EMPTY_INITIALIZER;
480ce8ab 599 struct vlog_module **mp;
8628b0b7
JP
600 struct svec lines = SVEC_EMPTY_INITIALIZER;
601 char *line;
602 size_t i;
064af421
BP
603
604 ds_put_format(&s, " console syslog file\n");
605 ds_put_format(&s, " ------- ------ ------\n");
606
480ce8ab 607 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
4958e3ee
BP
608 struct ds line;
609
610 ds_init(&line);
611 ds_put_format(&line, "%-16s %4s %4s %4s",
612 vlog_get_module_name(*mp),
613 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
614 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
615 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
616 if (!(*mp)->honor_rate_limits) {
617 ds_put_cstr(&line, " (rate limiting disabled)");
618 }
619 ds_put_char(&line, '\n');
620
621 svec_add_nocopy(&lines, ds_steal_cstr(&line));
8628b0b7
JP
622 }
623
624 svec_sort(&lines);
625 SVEC_FOR_EACH (i, line, &lines) {
626 ds_put_cstr(&s, line);
064af421 627 }
8628b0b7 628 svec_destroy(&lines);
064af421
BP
629
630 return ds_cstr(&s);
631}
632
633/* Returns true if a log message emitted for the given 'module' and 'level'
634 * would cause some log output, false if that module and level are completely
635 * disabled. */
636bool
480ce8ab 637vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
064af421 638{
480ce8ab 639 return module->min_level >= level;
064af421
BP
640}
641
642static const char *
643fetch_braces(const char *p, const char *def, char *out, size_t out_size)
644{
645 if (*p == '{') {
646 size_t n = strcspn(p + 1, "}");
647 size_t n_copy = MIN(n, out_size - 1);
648 memcpy(out, p + 1, n_copy);
649 out[n_copy] = '\0';
650 p += n + 2;
651 } else {
652 ovs_strlcpy(out, def, out_size);
653 }
654 return p;
655}
656
657static void
480ce8ab 658format_log_message(const struct vlog_module *module, enum vlog_level level,
064af421
BP
659 enum vlog_facility facility, unsigned int msg_num,
660 const char *message, va_list args_, struct ds *s)
661{
662 char tmp[128];
663 va_list args;
664 const char *p;
665
666 ds_clear(s);
667 for (p = facilities[facility].pattern; *p != '\0'; ) {
bc9fb3a9 668 const char *subprogram_name;
064af421
BP
669 enum { LEFT, RIGHT } justify = RIGHT;
670 int pad = '0';
671 size_t length, field, used;
672
673 if (*p != '%') {
674 ds_put_char(s, *p++);
675 continue;
676 }
677
678 p++;
679 if (*p == '-') {
680 justify = LEFT;
681 p++;
682 }
683 if (*p == '0') {
684 pad = '0';
685 p++;
686 }
687 field = 0;
be2c418b 688 while (isdigit((unsigned char)*p)) {
064af421
BP
689 field = (field * 10) + (*p - '0');
690 p++;
691 }
692
693 length = s->length;
694 switch (*p++) {
695 case 'A':
696 ds_put_cstr(s, program_name);
697 break;
698 case 'c':
699 p = fetch_braces(p, "", tmp, sizeof tmp);
700 ds_put_cstr(s, vlog_get_module_name(module));
701 break;
702 case 'd':
703 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
3e78870d 704 ds_put_strftime(s, tmp, time_wall(), false);
b5d29991
GS
705 break;
706 case 'D':
707 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
3e78870d 708 ds_put_strftime(s, tmp, time_wall(), true);
064af421
BP
709 break;
710 case 'm':
711 /* Format user-supplied log message and trim trailing new-lines. */
712 length = s->length;
713 va_copy(args, args_);
714 ds_put_format_valist(s, message, args);
715 va_end(args);
716 while (s->length > length && s->string[s->length - 1] == '\n') {
717 s->length--;
718 }
719 break;
720 case 'N':
721 ds_put_format(s, "%u", msg_num);
722 break;
723 case 'n':
724 ds_put_char(s, '\n');
725 break;
726 case 'p':
727 ds_put_cstr(s, vlog_get_level_name(level));
728 break;
729 case 'P':
730 ds_put_format(s, "%ld", (long int) getpid());
731 break;
732 case 'r':
4ae90ff9 733 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
064af421 734 break;
781dee08 735 case 't':
bc9fb3a9 736 subprogram_name = get_subprogram_name();
781dee08
BP
737 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
738 break;
739 case 'T':
bc9fb3a9 740 subprogram_name = get_subprogram_name();
781dee08
BP
741 if (subprogram_name[0]) {
742 ds_put_format(s, "(%s)", subprogram_name);
743 }
744 break;
064af421
BP
745 default:
746 ds_put_char(s, p[-1]);
747 break;
748 }
749 used = s->length - length;
750 if (used < field) {
751 size_t n_pad = field - used;
752 if (justify == RIGHT) {
753 ds_put_uninit(s, n_pad);
754 memmove(&s->string[length + n_pad], &s->string[length], used);
755 memset(&s->string[length], pad, n_pad);
756 } else {
757 ds_put_char_multiple(s, pad, n_pad);
758 }
759 }
760 }
761}
762
763/* Writes 'message' to the log at the given 'level' and as coming from the
764 * given 'module'.
765 *
766 * Guaranteed to preserve errno. */
767void
480ce8ab 768vlog_valist(const struct vlog_module *module, enum vlog_level level,
064af421
BP
769 const char *message, va_list args)
770{
480ce8ab
BP
771 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
772 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
9eb94563 773 bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
064af421
BP
774 if (log_to_console || log_to_syslog || log_to_file) {
775 int save_errno = errno;
776 static unsigned int msg_num;
777 struct ds s;
778
1e8cf0f7
BP
779 vlog_init();
780
064af421
BP
781 ds_init(&s);
782 ds_reserve(&s, 1024);
783 msg_num++;
784
785 if (log_to_console) {
786 format_log_message(module, level, VLF_CONSOLE, msg_num,
787 message, args, &s);
788 ds_put_char(&s, '\n');
789 fputs(ds_cstr(&s), stderr);
790 }
791
792 if (log_to_syslog) {
793 int syslog_level = syslog_levels[level];
794 char *save_ptr = NULL;
795 char *line;
796
797 format_log_message(module, level, VLF_SYSLOG, msg_num,
798 message, args, &s);
799 for (line = strtok_r(s.string, "\n", &save_ptr); line;
800 line = strtok_r(NULL, "\n", &save_ptr)) {
801 syslog(syslog_level, "%s", line);
802 }
803 }
804
805 if (log_to_file) {
806 format_log_message(module, level, VLF_FILE, msg_num,
807 message, args, &s);
808 ds_put_char(&s, '\n');
0a04ad85 809 ignore(write(log_fd, s.string, s.length));
064af421
BP
810 }
811
812 ds_destroy(&s);
813 errno = save_errno;
814 }
815}
816
817void
480ce8ab
BP
818vlog(const struct vlog_module *module, enum vlog_level level,
819 const char *message, ...)
064af421
BP
820{
821 va_list args;
822
823 va_start(args, message);
824 vlog_valist(module, level, message, args);
825 va_end(args);
826}
827
d41d4b71
BP
828/* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
829 * exit code. Always writes the message to stderr, even if the console
830 * facility is disabled.
831 *
832 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
833 * facility shouldn't automatically restart the current daemon. */
279c9e03 834void
c1a543a8 835vlog_fatal_valist(const struct vlog_module *module_,
279c9e03
BP
836 const char *message, va_list args)
837{
ebc56baa 838 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
279c9e03
BP
839
840 /* Don't log this message to the console to avoid redundancy with the
841 * message written by the later ovs_fatal_valist(). */
c1a543a8 842 module->levels[VLF_CONSOLE] = VLL_OFF;
279c9e03 843
c1a543a8 844 vlog_valist(module, VLL_EMER, message, args);
279c9e03
BP
845 ovs_fatal_valist(0, message, args);
846}
847
d41d4b71
BP
848/* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
849 * exit code. Always writes the message to stderr, even if the console
850 * facility is disabled.
851 *
852 * Choose this function instead of vlog_abort() if the daemon monitoring
853 * facility shouldn't automatically restart the current daemon. */
279c9e03 854void
c1a543a8 855vlog_fatal(const struct vlog_module *module, const char *message, ...)
279c9e03
BP
856{
857 va_list args;
858
859 va_start(args, message);
c1a543a8 860 vlog_fatal_valist(module, message, args);
279c9e03
BP
861 va_end(args);
862}
863
d41d4b71
BP
864/* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
865 * writes the message to stderr, even if the console facility is disabled.
866 *
867 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
868 * facility should automatically restart the current daemon. */
869void
870vlog_abort_valist(const struct vlog_module *module_,
871 const char *message, va_list args)
872{
873 struct vlog_module *module = (struct vlog_module *) module_;
874
875 /* Don't log this message to the console to avoid redundancy with the
876 * message written by the later ovs_abort_valist(). */
877 module->levels[VLF_CONSOLE] = VLL_OFF;
878
879 vlog_valist(module, VLL_EMER, message, args);
880 ovs_abort_valist(0, message, args);
881}
882
883/* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
884 * writes the message to stderr, even if the console facility is disabled.
885 *
886 * Choose this function instead of vlog_fatal() if the daemon monitoring
887 * facility should automatically restart the current daemon. */
888void
889vlog_abort(const struct vlog_module *module, const char *message, ...)
890{
891 va_list args;
892
893 va_start(args, message);
894 vlog_abort_valist(module, message, args);
895 va_end(args);
896}
897
064af421 898bool
480ce8ab 899vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
064af421
BP
900 struct vlog_rate_limit *rl)
901{
4958e3ee
BP
902 if (!module->honor_rate_limits) {
903 return false;
904 }
905
064af421
BP
906 if (!vlog_is_enabled(module, level)) {
907 return true;
908 }
909
648f4f1f 910 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
064af421 911 time_t now = time_now();
648f4f1f
BP
912 if (!rl->n_dropped) {
913 rl->first_dropped = now;
064af421 914 }
648f4f1f
BP
915 rl->last_dropped = now;
916 rl->n_dropped++;
917 return true;
064af421 918 }
064af421
BP
919
920 if (rl->n_dropped) {
e2eed6a7
BP
921 time_t now = time_now();
922 unsigned int first_dropped_elapsed = now - rl->first_dropped;
923 unsigned int last_dropped_elapsed = now - rl->last_dropped;
924
064af421 925 vlog(module, level,
e2eed6a7
BP
926 "Dropped %u log messages in last %u seconds (most recently, "
927 "%u seconds ago) due to excessive rate",
928 rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
929
064af421
BP
930 rl->n_dropped = 0;
931 }
932 return false;
933}
934
935void
480ce8ab 936vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
064af421
BP
937 struct vlog_rate_limit *rl, const char *message, ...)
938{
939 if (!vlog_should_drop(module, level, rl)) {
940 va_list args;
941
942 va_start(args, message);
943 vlog_valist(module, level, message, args);
944 va_end(args);
945 }
946}
947
948void
d295e8e9 949vlog_usage(void)
064af421
BP
950{
951 printf("\nLogging options:\n"
2a3e30b2 952 " -v, --verbose=[SPEC] set logging levels\n"
064af421
BP
953 " -v, --verbose set maximum verbosity level\n"
954 " --log-file[=FILE] enable logging to specified FILE\n"
955 " (default: %s/%s.log)\n",
b43c6fe2 956 ovs_logdir(), program_name);
064af421 957}