1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <sys/signalfd.h>
10 #include "sd-messages.h"
12 #include "alloc-util.h"
13 #include "ansi-color.h"
14 #include "argv-util.h"
16 #include "errno-util.h"
17 #include "extract-word.h"
19 #include "format-util.h"
20 #include "iovec-util.h"
23 #include "log-context.h"
24 #include "parse-util.h"
25 #include "proc-cmdline.h"
26 #include "process-util.h"
27 #include "ratelimit.h"
28 #include "signal-util.h"
29 #include "socket-util.h"
30 #include "stdio-util.h"
31 #include "string-table.h"
32 #include "string-util.h"
34 #include "syslog-util.h"
35 #include "terminal-util.h"
36 #include "time-util.h"
39 #define SNDBUF_SIZE (8*1024*1024)
40 #define IOVEC_MAX 256U
42 static log_syntax_callback_t log_syntax_callback
= NULL
;
43 static void *log_syntax_callback_userdata
= NULL
;
45 static LogTarget log_target
= LOG_TARGET_CONSOLE
;
46 static int log_max_level
= LOG_INFO
;
47 static int log_target_max_level
[_LOG_TARGET_SINGLE_MAX
] = {
48 [LOG_TARGET_CONSOLE
] = INT_MAX
,
49 [LOG_TARGET_KMSG
] = INT_MAX
,
50 [LOG_TARGET_SYSLOG
] = INT_MAX
,
51 [LOG_TARGET_JOURNAL
] = INT_MAX
,
53 static int log_facility
= LOG_DAEMON
;
54 static bool ratelimit_kmsg
= true;
56 static int console_fd
= STDERR_FILENO
;
57 static int console_fd_is_tty
= -1; /* tri-state: -1 means don't know */
58 static int syslog_fd
= -EBADF
;
59 static int kmsg_fd
= -EBADF
;
60 static int journal_fd
= -EBADF
;
62 static bool syslog_is_stream
= false;
64 static int show_color
= -1; /* tristate */
65 static bool show_location
= false;
66 static bool show_time
= false;
67 static bool show_tid
= false;
69 static bool upgrade_syslog_to_journal
= false;
70 static bool always_reopen_console
= false;
71 static bool open_when_needed
= false;
72 static bool prohibit_ipc
= false;
74 static thread_local
const char *log_prefix
= NULL
;
76 #if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
77 bool _log_message_dummy
= false; /* Always false */
80 /* An assert to use in logging functions that does not call recursively
81 * into our logging functions (since that might lead to a loop). */
82 #define assert_raw(expr) \
84 if (_unlikely_(!(expr))) { \
85 fputs(#expr "\n", stderr); \
90 static void log_close_console(void) {
91 /* See comment in log_close_journal() */
92 (void) safe_close_above_stdio(TAKE_FD(console_fd
));
93 console_fd_is_tty
= -1;
96 static int log_open_console(void) {
98 if (!always_reopen_console
) {
99 console_fd
= STDERR_FILENO
;
100 console_fd_is_tty
= -1;
104 if (console_fd
< 3) {
107 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
111 console_fd
= fd_move_above_stdio(fd
);
112 console_fd_is_tty
= true;
118 static void log_close_kmsg(void) {
119 /* See comment in log_close_journal() */
120 (void) safe_close(TAKE_FD(kmsg_fd
));
123 static int log_open_kmsg(void) {
128 kmsg_fd
= open("/dev/kmsg", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
132 kmsg_fd
= fd_move_above_stdio(kmsg_fd
);
136 static void log_close_syslog(void) {
137 /* See comment in log_close_journal() */
138 (void) safe_close(TAKE_FD(syslog_fd
));
141 static int create_log_socket(int type
) {
145 fd
= socket(AF_UNIX
, type
|SOCK_CLOEXEC
, 0);
149 fd
= fd_move_above_stdio(fd
);
150 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
152 /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
153 * in the unlikely case of a deadlock. */
154 if (getpid_cached() == 1)
155 timeval_store(&tv
, 10 * USEC_PER_MSEC
);
157 timeval_store(&tv
, 10 * USEC_PER_SEC
);
158 (void) setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
163 static int log_open_syslog(void) {
169 syslog_fd
= create_log_socket(SOCK_DGRAM
);
175 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
177 safe_close(syslog_fd
);
179 /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
181 syslog_fd
= create_log_socket(SOCK_STREAM
);
187 r
= connect_unix_path(syslog_fd
, AT_FDCWD
, "/dev/log");
191 syslog_is_stream
= true;
193 syslog_is_stream
= false;
202 static void log_close_journal(void) {
203 /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
204 * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
205 * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
207 (void) safe_close(TAKE_FD(journal_fd
));
210 static int log_open_journal(void) {
216 journal_fd
= create_log_socket(SOCK_DGRAM
);
217 if (journal_fd
< 0) {
222 r
= connect_unix_path(journal_fd
, AT_FDCWD
, "/run/systemd/journal/socket");
233 bool stderr_is_journal(void) {
234 _cleanup_free_
char *w
= NULL
;
239 e
= getenv("JOURNAL_STREAM");
243 if (extract_first_word(&e
, &w
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
) <= 0)
248 if (safe_atou64(w
, &dev
) < 0)
250 if (safe_atou64(e
, &ino
) < 0)
253 if (fstat(STDERR_FILENO
, &st
) < 0)
256 return st
.st_dev
== dev
&& st
.st_ino
== ino
;
262 /* Do not call from library code. */
264 /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
265 * so that a call to a logging function immediately following a log_open() call can still easily
266 * reference an error that happened immediately before the log_open() call. */
269 /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
270 * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
271 * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
272 * because there is no reason to close it. */
274 if (log_target
== LOG_TARGET_NULL
) {
281 if (getpid_cached() == 1 ||
282 stderr_is_journal() ||
286 LOG_TARGET_JOURNAL_OR_KMSG
,
288 LOG_TARGET_SYSLOG_OR_KMSG
)) {
291 if (IN_SET(log_target
,
293 LOG_TARGET_JOURNAL_OR_KMSG
,
294 LOG_TARGET_JOURNAL
)) {
296 r
= log_open_journal();
304 if (IN_SET(log_target
,
305 LOG_TARGET_SYSLOG_OR_KMSG
,
306 LOG_TARGET_SYSLOG
)) {
308 r
= log_open_syslog();
317 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
318 LOG_TARGET_JOURNAL_OR_KMSG
,
319 LOG_TARGET_SYSLOG_OR_KMSG
,
334 return log_open_console();
337 void log_set_target(LogTarget target
) {
339 assert(target
< _LOG_TARGET_MAX
);
341 if (upgrade_syslog_to_journal
) {
342 if (target
== LOG_TARGET_SYSLOG
)
343 target
= LOG_TARGET_JOURNAL
;
344 else if (target
== LOG_TARGET_SYSLOG_OR_KMSG
)
345 target
= LOG_TARGET_JOURNAL_OR_KMSG
;
351 void log_set_target_and_open(LogTarget target
) {
352 log_set_target(target
);
356 void log_close(void) {
357 /* Do not call from library code. */
365 void log_forget_fds(void) {
366 /* Do not call from library code. */
368 console_fd
= kmsg_fd
= syslog_fd
= journal_fd
= -EBADF
;
369 console_fd_is_tty
= -1;
372 int log_set_max_level(int level
) {
373 assert(level
== LOG_NULL
|| log_level_is_valid(level
));
375 int old
= log_max_level
;
376 log_max_level
= level
;
378 /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
379 * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
380 * libc has the same functionality. This has multiple reasons, first and foremost that we want to
381 * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
382 * current log mask from glibc without changing it, but that's useful for testing the current log
383 * level before even entering the log functions like we do in our macros. */
384 setlogmask(LOG_UPTO(level
));
386 /* Ensure that our own LOG_NULL define maps sanely to the log mask */
387 assert_cc(LOG_UPTO(LOG_NULL
) == 0);
392 void log_set_facility(int facility
) {
393 log_facility
= facility
;
396 static bool check_console_fd_is_tty(void) {
400 if (console_fd_is_tty
< 0)
401 console_fd_is_tty
= isatty_safe(console_fd
);
403 return console_fd_is_tty
;
406 static int write_to_console(
412 const char *buffer
) {
414 static int dumb
= -1;
417 header_time
[FORMAT_TIMESTAMP_MAX
],
418 prefix
[1 + DECIMAL_STR_MAX(int) + 2],
419 tid_string
[3 + DECIMAL_STR_MAX(pid_t
) + 1];
420 struct iovec iovec
[11];
421 const char *on
= NULL
, *off
= NULL
;
428 dumb
= getenv_terminal_is_dumb();
430 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_CONSOLE
])
433 if (log_target
== LOG_TARGET_CONSOLE_PREFIXED
) {
434 xsprintf(prefix
, "<%i>", level
);
435 iovec
[n
++] = IOVEC_MAKE_STRING(prefix
);
439 format_timestamp(header_time
, sizeof(header_time
), now(CLOCK_REALTIME
))) {
440 iovec
[n
++] = IOVEC_MAKE_STRING(header_time
);
441 iovec
[n
++] = IOVEC_MAKE_STRING(" ");
445 xsprintf(tid_string
, "(" PID_FMT
") ", gettid());
446 iovec
[n
++] = IOVEC_MAKE_STRING(tid_string
);
449 if (log_get_show_color())
450 get_log_colors(LOG_PRI(level
), &on
, &off
, NULL
);
453 const char *lon
= "", *loff
= "";
454 if (log_get_show_color()) {
455 lon
= ansi_highlight_yellow4();
456 loff
= ansi_normal();
459 (void) snprintf(location
, sizeof location
, "%s%s:%i%s: ", lon
, file
, line
, loff
);
460 iovec
[n
++] = IOVEC_MAKE_STRING(location
);
464 iovec
[n
++] = IOVEC_MAKE_STRING(on
);
466 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
467 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
469 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
471 iovec
[n
++] = IOVEC_MAKE_STRING(off
);
473 /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
474 * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
475 * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
476 * again, after all. If the TTY is not in raw mode the extra CR should not hurt. If we're writing to
477 * a dumb terminal, only write NL as CRNL might be interpreted as a double newline. */
478 iovec
[n
++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() && !dumb
? "\r\n" : "\n");
480 if (writev(console_fd
, iovec
, n
) < 0) {
482 if (errno
== EIO
&& getpid_cached() == 1) {
484 /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
488 (void) log_open_console();
492 if (writev(console_fd
, iovec
, n
) < 0)
501 static int write_to_syslog(
507 const char *buffer
) {
509 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
511 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
518 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_SYSLOG
])
521 xsprintf(header_priority
, "<%i>", level
);
523 r
= localtime_or_gmtime_usec(now(CLOCK_REALTIME
), /* utc= */ false, &tm
);
527 if (strftime(header_time
, sizeof(header_time
), "%h %e %T ", &tm
) <= 0)
530 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
532 struct iovec iovec
[] = {
533 IOVEC_MAKE_STRING(header_priority
),
534 IOVEC_MAKE_STRING(header_time
),
535 IOVEC_MAKE_STRING(program_invocation_short_name
),
536 IOVEC_MAKE_STRING(header_pid
),
537 IOVEC_MAKE_STRING(strempty(log_prefix
)),
538 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
539 IOVEC_MAKE_STRING(buffer
),
541 const struct msghdr msghdr
= {
543 .msg_iovlen
= ELEMENTSOF(iovec
),
546 /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
547 if (syslog_is_stream
)
548 iovec
[ELEMENTSOF(iovec
) - 1].iov_len
++;
553 n
= sendmsg(syslog_fd
, &msghdr
, MSG_NOSIGNAL
);
557 if (!syslog_is_stream
)
560 if (iovec_increment(iovec
, ELEMENTSOF(iovec
), n
))
567 static int write_to_kmsg(
573 const char *buffer
) {
575 /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
576 * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
577 * where we log excessively, but not in a tight loop.
579 * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
582 static thread_local RateLimit ratelimit
= { 5 * USEC_PER_SEC
, 200 };
584 char header_priority
[2 + DECIMAL_STR_MAX(int) + 1],
585 header_pid
[4 + DECIMAL_STR_MAX(pid_t
) + 1];
590 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_KMSG
])
593 if (ratelimit_kmsg
&& !ratelimit_below(&ratelimit
)) {
594 if (ratelimit_num_dropped(&ratelimit
) > 1)
597 buffer
= "Too many messages being logged to kmsg, ignoring";
600 xsprintf(header_priority
, "<%i>", level
);
601 xsprintf(header_pid
, "["PID_FMT
"]: ", getpid_cached());
603 const struct iovec iovec
[] = {
604 IOVEC_MAKE_STRING(header_priority
),
605 IOVEC_MAKE_STRING(program_invocation_short_name
),
606 IOVEC_MAKE_STRING(header_pid
),
607 IOVEC_MAKE_STRING(strempty(log_prefix
)),
608 IOVEC_MAKE_STRING(log_prefix
? ": " : ""),
609 IOVEC_MAKE_STRING(buffer
),
610 IOVEC_MAKE_STRING("\n"),
613 if (writev(kmsg_fd
, iovec
, ELEMENTSOF(iovec
)) < 0)
619 static int log_do_header(
624 const char *file
, int line
, const char *func
,
625 const char *object_field
, const char *object
,
626 const char *extra_field
, const char *extra
) {
629 error
= IS_SYNTHETIC_ERRNO(error
) ? 0 : ERRNO_VALUE(error
);
631 r
= snprintf(header
, size
,
633 "SYSLOG_FACILITY=%i\n"
635 "%s%.256s%s" /* CODE_FILE */
636 "%s%.*i%s" /* CODE_LINE */
637 "%s%.256s%s" /* CODE_FUNC */
638 "%s%.*i%s" /* ERRNO */
639 "%s%.256s%s" /* object */
640 "%s%.256s%s" /* extra */
641 "SYSLOG_IDENTIFIER=%.256s\n",
645 isempty(file
) ? "" : "CODE_FILE=",
646 isempty(file
) ? "" : file
,
647 isempty(file
) ? "" : "\n",
648 line
? "CODE_LINE=" : "",
649 line
? 1 : 0, line
, /* %.0d means no output too, special case for 0 */
651 isempty(func
) ? "" : "CODE_FUNC=",
652 isempty(func
) ? "" : func
,
653 isempty(func
) ? "" : "\n",
654 error
? "ERRNO=" : "",
655 error
? 1 : 0, error
,
657 isempty(object
) ? "" : ASSERT_PTR(object_field
),
658 isempty(object
) ? "" : object
,
659 isempty(object
) ? "" : "\n",
660 isempty(extra
) ? "" : ASSERT_PTR(extra_field
),
661 isempty(extra
) ? "" : extra
,
662 isempty(extra
) ? "" : "\n",
663 program_invocation_short_name
);
664 assert_raw((size_t) r
< size
);
669 static void log_do_context(struct iovec
*iovec
, size_t iovec_len
, size_t *n
) {
673 LIST_FOREACH(ll
, c
, log_context_head()) {
674 STRV_FOREACH(s
, c
->fields
) {
675 if (*n
+ 2 >= iovec_len
)
678 iovec
[(*n
)++] = IOVEC_MAKE_STRING(*s
);
679 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
682 for (size_t i
= 0; i
< c
->n_input_iovec
; i
++) {
683 if (*n
+ 2 >= iovec_len
)
686 iovec
[(*n
)++] = c
->input_iovec
[i
];
687 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
690 if (c
->key
&& c
->value
) {
691 if (*n
+ 3 >= iovec_len
)
694 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->key
);
695 iovec
[(*n
)++] = IOVEC_MAKE_STRING(c
->value
);
696 iovec
[(*n
)++] = IOVEC_MAKE_STRING("\n");
701 static int write_to_journal(
707 const char *object_field
,
709 const char *extra_field
,
711 const char *buffer
) {
713 char header
[LINE_MAX
];
714 size_t n
= 0, iovec_len
;
720 if (LOG_PRI(level
) > log_target_max_level
[LOG_TARGET_JOURNAL
])
723 iovec_len
= MIN(6 + log_context_num_fields() * 3, IOVEC_MAX
);
724 iovec
= newa(struct iovec
, iovec_len
);
726 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
);
728 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
729 iovec
[n
++] = IOVEC_MAKE_STRING("MESSAGE=");
731 iovec
[n
++] = IOVEC_MAKE_STRING(log_prefix
);
732 iovec
[n
++] = IOVEC_MAKE_STRING(": ");
734 iovec
[n
++] = IOVEC_MAKE_STRING(buffer
);
735 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
737 log_do_context(iovec
, iovec_len
, &n
);
739 const struct msghdr msghdr
= {
744 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) < 0)
750 int log_dispatch_internal(
756 const char *object_field
,
758 const char *extra_field
,
764 if (log_target
== LOG_TARGET_NULL
)
765 return -ERRNO_VALUE(error
);
767 /* Patch in LOG_DAEMON facility if necessary */
768 if (LOG_FAC(level
) == 0)
769 level
|= log_facility
;
771 if (open_when_needed
)
778 buffer
+= strspn(buffer
, NEWLINE
);
783 if ((e
= strpbrk(buffer
, NEWLINE
)))
786 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
787 LOG_TARGET_JOURNAL_OR_KMSG
,
788 LOG_TARGET_JOURNAL
)) {
790 k
= write_to_journal(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, buffer
);
791 if (k
< 0 && k
!= -EAGAIN
)
795 if (IN_SET(log_target
, LOG_TARGET_SYSLOG_OR_KMSG
,
796 LOG_TARGET_SYSLOG
)) {
798 k
= write_to_syslog(level
, error
, file
, line
, func
, buffer
);
799 if (k
< 0 && k
!= -EAGAIN
)
804 IN_SET(log_target
, LOG_TARGET_AUTO
,
805 LOG_TARGET_SYSLOG_OR_KMSG
,
806 LOG_TARGET_JOURNAL_OR_KMSG
,
812 k
= write_to_kmsg(level
, error
, file
, line
, func
, buffer
);
815 (void) log_open_console();
820 (void) write_to_console(level
, error
, file
, line
, func
, buffer
);
825 if (open_when_needed
)
828 return -ERRNO_VALUE(error
);
831 int log_dump_internal(
841 /* This modifies the buffer... */
843 if (_likely_(LOG_PRI(level
) > log_max_level
))
844 return -ERRNO_VALUE(error
);
846 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
858 if (_likely_(LOG_PRI(level
) > log_max_level
))
859 return -ERRNO_VALUE(error
);
861 /* Make sure that %m maps to the specified error (or "Success"). */
862 char buffer
[LINE_MAX
];
863 LOCAL_ERRNO(ERRNO_VALUE(error
));
865 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
867 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buffer
);
876 const char *format
, ...) {
881 va_start(ap
, format
);
882 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
888 int log_object_internalv(
894 const char *object_field
,
896 const char *extra_field
,
903 if (_likely_(LOG_PRI(level
) > log_max_level
))
904 return -ERRNO_VALUE(error
);
906 /* Make sure that %m maps to the specified error (or "Success"). */
907 LOCAL_ERRNO(ERRNO_VALUE(error
));
909 LOG_SET_PREFIX(object
);
911 b
= buffer
= newa(char, LINE_MAX
);
912 (void) vsnprintf(b
, LINE_MAX
, format
, ap
);
914 return log_dispatch_internal(level
, error
, file
, line
, func
,
915 object_field
, object
, extra_field
, extra
, buffer
);
918 int log_object_internal(
924 const char *object_field
,
926 const char *extra_field
,
928 const char *format
, ...) {
933 va_start(ap
, format
);
934 r
= log_object_internalv(level
, error
, file
, line
, func
, object_field
, object
, extra_field
, extra
, format
, ap
);
940 int log_oom_internal(int level
, const char *file
, int line
, const char *func
) {
941 return log_internal(level
, ENOMEM
, file
, line
, func
, "Out of memory.");
944 int log_format_iovec(
948 bool newline_separator
,
953 static const char nl
= '\n';
955 while (format
&& *n
+ 1 < iovec_len
) {
960 /* We need to copy the va_list structure,
961 * since vasprintf() leaves it afterwards at
962 * an undefined location */
964 errno
= ERRNO_VALUE(error
);
967 r
= vasprintf(&m
, format
, aq
);
972 /* Now, jump enough ahead, so that we point to
973 * the next format string */
974 VA_FORMAT_ADVANCE(format
, ap
);
976 iovec
[(*n
)++] = IOVEC_MAKE_STRING(m
);
977 if (newline_separator
)
978 iovec
[(*n
)++] = IOVEC_MAKE((char *)&nl
, 1);
980 format
= va_arg(ap
, char *);
985 int log_struct_internal(
991 const char *format
, ...) {
998 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
999 log_target
== LOG_TARGET_NULL
)
1000 return -ERRNO_VALUE(error
);
1002 if (LOG_FAC(level
) == 0)
1003 level
|= log_facility
;
1005 if (IN_SET(log_target
,
1007 LOG_TARGET_JOURNAL_OR_KMSG
,
1008 LOG_TARGET_JOURNAL
)) {
1010 if (open_when_needed
)
1013 if (journal_fd
>= 0) {
1014 char header
[LINE_MAX
];
1015 struct iovec
*iovec
;
1016 size_t n
= 0, m
, iovec_len
;
1018 bool fallback
= false;
1020 iovec_len
= MIN(17 + log_context_num_fields() * 3, IOVEC_MAX
);
1021 iovec
= newa(struct iovec
, iovec_len
);
1023 /* If the journal is available do structured logging.
1024 * Do not report the errno if it is synthetic. */
1025 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1026 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1028 va_start(ap
, format
);
1029 DISABLE_WARNING_FORMAT_NONLITERAL
;
1030 r
= log_format_iovec(iovec
, iovec_len
, &n
, true, error
, format
, ap
);
1036 log_do_context(iovec
, iovec_len
, &n
);
1038 const struct msghdr msghdr
= {
1043 (void) sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
);
1047 for (size_t i
= 1; i
< m
; i
+= 2)
1048 free(iovec
[i
].iov_base
);
1051 if (open_when_needed
)
1054 return -ERRNO_VALUE(error
);
1059 /* Fallback if journal logging is not available or didn't work. */
1061 va_start(ap
, format
);
1065 errno
= ERRNO_VALUE(error
);
1068 DISABLE_WARNING_FORMAT_NONLITERAL
;
1069 (void) vsnprintf(buf
, sizeof buf
, format
, aq
);
1073 if (startswith(buf
, "MESSAGE=")) {
1078 VA_FORMAT_ADVANCE(format
, ap
);
1080 format
= va_arg(ap
, char *);
1085 if (open_when_needed
)
1088 return -ERRNO_VALUE(error
);
1091 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, buf
+ 8);
1094 int log_struct_iovec_internal(
1100 const struct iovec input_iovec
[],
1101 size_t n_input_iovec
) {
1105 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1106 log_target
== LOG_TARGET_NULL
)
1107 return -ERRNO_VALUE(error
);
1109 if (LOG_FAC(level
) == 0)
1110 level
|= log_facility
;
1112 if (IN_SET(log_target
, LOG_TARGET_AUTO
,
1113 LOG_TARGET_JOURNAL_OR_KMSG
,
1114 LOG_TARGET_JOURNAL
) &&
1117 char header
[LINE_MAX
];
1118 struct iovec
*iovec
;
1119 size_t n
= 0, iovec_len
;
1121 iovec_len
= MIN(1 + n_input_iovec
* 2 + log_context_num_fields() * 3, IOVEC_MAX
);
1122 iovec
= newa(struct iovec
, iovec_len
);
1124 log_do_header(header
, sizeof(header
), level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
);
1126 iovec
[n
++] = IOVEC_MAKE_STRING(header
);
1127 for (size_t i
= 0; i
< n_input_iovec
; i
++) {
1128 iovec
[n
++] = input_iovec
[i
];
1129 iovec
[n
++] = IOVEC_MAKE_STRING("\n");
1132 log_do_context(iovec
, iovec_len
, &n
);
1134 const struct msghdr msghdr
= {
1139 if (sendmsg(journal_fd
, &msghdr
, MSG_NOSIGNAL
) >= 0)
1140 return -ERRNO_VALUE(error
);
1143 for (size_t i
= 0; i
< n_input_iovec
; i
++)
1144 if (memory_startswith(input_iovec
[i
].iov_base
, input_iovec
[i
].iov_len
, "MESSAGE=")) {
1147 m
= strndupa_safe((char*) input_iovec
[i
].iov_base
+ STRLEN("MESSAGE="),
1148 input_iovec
[i
].iov_len
- STRLEN("MESSAGE="));
1150 return log_dispatch_internal(level
, error
, file
, line
, func
, NULL
, NULL
, NULL
, NULL
, m
);
1153 /* Couldn't find MESSAGE=. */
1154 return -ERRNO_VALUE(error
);
1157 int log_set_target_from_string(const char *e
) {
1160 t
= log_target_from_string(e
);
1168 int log_set_max_level_from_string(const char *e
) {
1172 _cleanup_free_
char *word
= NULL
, *prefix
= NULL
;
1176 r
= extract_first_word(&e
, &word
, ",", 0);
1182 colon
= strchr(word
, ':');
1184 r
= log_level_from_string(word
);
1188 log_set_max_level(r
);
1192 prefix
= strndup(word
, colon
- word
);
1196 target
= log_target_from_string(prefix
);
1200 if (target
>= _LOG_TARGET_SINGLE_MAX
)
1203 r
= log_level_from_string(colon
+ 1);
1207 log_target_max_level
[target
] = r
;
1213 int log_max_levels_to_string(int level
, char **ret
) {
1214 _cleanup_free_
char *s
= NULL
;
1219 r
= log_level_to_string_alloc(level
, &s
);
1223 for (LogTarget target
= 0; target
< _LOG_TARGET_SINGLE_MAX
; target
++) {
1224 _cleanup_free_
char *l
= NULL
;
1226 if (log_target_max_level
[target
] == INT_MAX
)
1229 r
= log_level_to_string_alloc(log_target_max_level
[target
], &l
);
1233 r
= strextendf_with_separator(&s
, ",", "%s:%s", log_target_to_string(target
), l
);
1242 static int log_set_ratelimit_kmsg_from_string(const char *e
) {
1245 r
= parse_boolean(e
);
1253 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
1256 * The systemd.log_xyz= settings are parsed by all tools, and
1259 * However, "quiet" is only parsed by PID 1, and only turns of
1260 * status output to /dev/console, but does not alter the log
1264 if (streq(key
, "debug") && !value
)
1265 log_set_max_level(LOG_DEBUG
);
1267 else if (proc_cmdline_key_streq(key
, "systemd.log_target")) {
1269 if (proc_cmdline_value_missing(key
, value
))
1272 if (log_set_target_from_string(value
) < 0)
1273 log_warning("Failed to parse log target '%s', ignoring.", value
);
1275 } else if (proc_cmdline_key_streq(key
, "systemd.log_level")) {
1277 if (proc_cmdline_value_missing(key
, value
))
1280 if (log_set_max_level_from_string(value
) < 0)
1281 log_warning("Failed to parse log level setting '%s', ignoring.", value
);
1283 } else if (proc_cmdline_key_streq(key
, "systemd.log_color")) {
1285 if (log_show_color_from_string(value
?: "1") < 0)
1286 log_warning("Failed to parse log color setting '%s', ignoring.", value
);
1288 } else if (proc_cmdline_key_streq(key
, "systemd.log_location")) {
1290 if (log_show_location_from_string(value
?: "1") < 0)
1291 log_warning("Failed to parse log location setting '%s', ignoring.", value
);
1293 } else if (proc_cmdline_key_streq(key
, "systemd.log_tid")) {
1295 if (log_show_tid_from_string(value
?: "1") < 0)
1296 log_warning("Failed to parse log tid setting '%s', ignoring.", value
);
1298 } else if (proc_cmdline_key_streq(key
, "systemd.log_time")) {
1300 if (log_show_time_from_string(value
?: "1") < 0)
1301 log_warning("Failed to parse log time setting '%s', ignoring.", value
);
1303 } else if (proc_cmdline_key_streq(key
, "systemd.log_ratelimit_kmsg")) {
1305 if (log_set_ratelimit_kmsg_from_string(value
?: "1") < 0)
1306 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value
);
1312 static bool should_parse_proc_cmdline(void) {
1313 /* PID1 always reads the kernel command line. */
1314 if (getpid_cached() == 1)
1317 /* Otherwise, parse the command line if invoked directly by systemd. */
1318 return invoked_by_systemd();
1321 void log_parse_environment_variables(void) {
1325 e
= getenv("SYSTEMD_LOG_TARGET");
1326 if (e
&& log_set_target_from_string(e
) < 0)
1327 log_warning("Failed to parse log target '%s', ignoring.", e
);
1329 e
= getenv("SYSTEMD_LOG_LEVEL");
1331 r
= log_set_max_level_from_string(e
);
1333 log_warning_errno(r
, "Failed to parse log level '%s', ignoring: %m", e
);
1335 /* If no explicit log level is specified then let's see if this is a debug invocation, and if
1336 * so raise the log level to debug too. Note that this is not symmetric: just because
1337 * DEBUG_INVOCATION is explicitly set to 0 we won't lower the log level below debug. This
1338 * follows the logic that debug logging is an opt-in thing anyway, and if there's any reason
1339 * to enable it we should not disable it here automatically. */
1340 r
= getenv_bool("DEBUG_INVOCATION");
1341 if (r
< 0 && r
!= -ENXIO
)
1342 log_warning_errno(r
, "Failed to parse $DEBUG_INVOCATION value, ignoring: %m");
1344 log_set_max_level(LOG_DEBUG
);
1347 e
= getenv("SYSTEMD_LOG_COLOR");
1348 if (e
&& log_show_color_from_string(e
) < 0)
1349 log_warning("Failed to parse log color '%s', ignoring.", e
);
1351 e
= getenv("SYSTEMD_LOG_LOCATION");
1352 if (e
&& log_show_location_from_string(e
) < 0)
1353 log_warning("Failed to parse log location '%s', ignoring.", e
);
1355 e
= getenv("SYSTEMD_LOG_TIME");
1356 if (e
&& log_show_time_from_string(e
) < 0)
1357 log_warning("Failed to parse log time '%s', ignoring.", e
);
1359 e
= getenv("SYSTEMD_LOG_TID");
1360 if (e
&& log_show_tid_from_string(e
) < 0)
1361 log_warning("Failed to parse log tid '%s', ignoring.", e
);
1363 e
= getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
1364 if (e
&& log_set_ratelimit_kmsg_from_string(e
) < 0)
1365 log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e
);
1368 void log_parse_environment(void) {
1369 /* Do not call from library code. */
1371 if (should_parse_proc_cmdline())
1372 (void) proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, PROC_CMDLINE_STRIP_RD_PREFIX
);
1374 log_parse_environment_variables();
1377 LogTarget
log_get_target(void) {
1381 void log_settle_target(void) {
1383 /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1384 * stderr is attached to the journal every single log call. However, if we then close all file
1385 * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1386 * problem, this function is used to permanently change the log target depending on whether stderr is
1387 * connected to the journal or not. */
1389 LogTarget t
= log_get_target();
1391 if (t
!= LOG_TARGET_AUTO
)
1394 t
= getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc
? LOG_TARGET_KMSG
: LOG_TARGET_JOURNAL_OR_KMSG
)
1395 : LOG_TARGET_CONSOLE
;
1399 int log_get_max_level(void) {
1400 return log_max_level
;
1403 int log_get_target_max_level(LogTarget target
) {
1404 assert(target
>= 0);
1405 assert(target
< _LOG_TARGET_SINGLE_MAX
);
1406 return log_target_max_level
[target
];
1409 void log_show_color(bool b
) {
1413 bool log_get_show_color(void) {
1414 return show_color
> 0; /* Defaults to false. */
1417 void log_show_location(bool b
) {
1421 bool log_get_show_location(void) {
1422 return show_location
;
1425 void log_show_time(bool b
) {
1429 bool log_get_show_time(void) {
1433 void log_show_tid(bool b
) {
1437 bool log_get_show_tid(void) {
1441 int log_show_color_from_string(const char *e
) {
1444 r
= parse_boolean(e
);
1452 int log_show_location_from_string(const char *e
) {
1455 r
= parse_boolean(e
);
1459 log_show_location(r
);
1463 int log_show_time_from_string(const char *e
) {
1466 r
= parse_boolean(e
);
1474 int log_show_tid_from_string(const char *e
) {
1477 r
= parse_boolean(e
);
1485 bool log_on_console(void) {
1486 if (IN_SET(log_target
, LOG_TARGET_CONSOLE
,
1487 LOG_TARGET_CONSOLE_PREFIXED
))
1490 return syslog_fd
< 0 && kmsg_fd
< 0 && journal_fd
< 0;
1493 static const char *const log_target_table
[_LOG_TARGET_MAX
] = {
1494 [LOG_TARGET_CONSOLE
] = "console",
1495 [LOG_TARGET_CONSOLE_PREFIXED
] = "console-prefixed",
1496 [LOG_TARGET_KMSG
] = "kmsg",
1497 [LOG_TARGET_JOURNAL
] = "journal",
1498 [LOG_TARGET_JOURNAL_OR_KMSG
] = "journal-or-kmsg",
1499 [LOG_TARGET_SYSLOG
] = "syslog",
1500 [LOG_TARGET_SYSLOG_OR_KMSG
] = "syslog-or-kmsg",
1501 [LOG_TARGET_AUTO
] = "auto",
1502 [LOG_TARGET_NULL
] = "null",
1505 DEFINE_STRING_TABLE_LOOKUP(log_target
, LogTarget
);
1507 void log_received_signal(int level
, const struct signalfd_siginfo
*si
) {
1510 if (si_code_from_process(si
->ssi_code
) && pid_is_valid(si
->ssi_pid
)) {
1511 _cleanup_free_
char *p
= NULL
;
1513 (void) pid_get_comm(si
->ssi_pid
, &p
);
1516 "Received SIG%s from PID %"PRIu32
" (%s).",
1517 signal_to_string(si
->ssi_signo
),
1518 si
->ssi_pid
, strna(p
));
1522 signal_to_string(si
->ssi_signo
));
1525 void set_log_syntax_callback(log_syntax_callback_t cb
, void *userdata
) {
1526 assert(!log_syntax_callback
|| !cb
);
1527 assert(!log_syntax_callback_userdata
|| !userdata
);
1529 log_syntax_callback
= cb
;
1530 log_syntax_callback_userdata
= userdata
;
1533 int log_syntax_internal(
1536 const char *config_file
,
1537 unsigned config_line
,
1542 const char *format
, ...) {
1546 if (log_syntax_callback
)
1547 log_syntax_callback(unit
, level
, log_syntax_callback_userdata
);
1549 if (_likely_(LOG_PRI(level
) > log_max_level
) ||
1550 log_target
== LOG_TARGET_NULL
)
1551 return -ERRNO_VALUE(error
);
1553 char buffer
[LINE_MAX
];
1555 const char *unit_fmt
= NULL
;
1557 errno
= ERRNO_VALUE(error
);
1559 va_start(ap
, format
);
1560 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
1564 unit_fmt
= getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1567 if (config_line
> 0)
1568 return log_struct_internal(
1572 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR
),
1573 LOG_ITEM("CONFIG_FILE=%s", config_file
),
1574 LOG_ITEM("CONFIG_LINE=%u", config_line
),
1575 LOG_MESSAGE("%s:%u: %s", config_file
, config_line
, buffer
),
1579 return log_struct_internal(
1583 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR
),
1584 LOG_ITEM("CONFIG_FILE=%s", config_file
),
1585 LOG_MESSAGE("%s: %s", config_file
, buffer
),
1589 return log_struct_internal(
1593 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR
),
1594 LOG_MESSAGE("%s: %s", unit
, buffer
),
1598 return log_struct_internal(
1602 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR
),
1603 LOG_MESSAGE("%s", buffer
),
1607 int log_syntax_invalid_utf8_internal(
1610 const char *config_file
,
1611 unsigned config_line
,
1615 const char *rvalue
) {
1618 _cleanup_free_
char *p
= NULL
;
1621 p
= utf8_escape_invalid(rvalue
);
1623 return log_syntax_internal(unit
, level
, config_file
, config_line
,
1624 SYNTHETIC_ERRNO(EINVAL
), file
, line
, func
,
1625 "String is not UTF-8 clean, ignoring assignment: %s", strna(p
));
1628 int log_syntax_parse_error_internal(
1630 const char *config_file
,
1631 unsigned config_line
,
1638 const char *rvalue
) {
1641 _cleanup_free_
char *escaped
= NULL
;
1643 /* OOM is always handled as critical. */
1644 if (ERRNO_VALUE(error
) == ENOMEM
)
1645 return log_oom_internal(LOG_ERR
, file
, line
, func
);
1647 if (rvalue
&& !utf8_is_valid(rvalue
)) {
1648 escaped
= utf8_escape_invalid(rvalue
);
1652 rvalue
= " (escaped)";
1655 log_syntax_internal(unit
, critical
? LOG_ERR
: LOG_WARNING
, config_file
, config_line
, error
,
1657 "Failed to parse %s=%s%s%s%s%s",
1658 strna(lvalue
), strempty(escaped
), strempty(rvalue
),
1659 critical
? "" : ", ignoring",
1660 error
== 0 ? "." : ": ",
1661 error
== 0 ? "" : STRERROR(error
));
1663 return critical
? -ERRNO_VALUE(error
) : 0;
1666 void log_set_upgrade_syslog_to_journal(bool b
) {
1667 upgrade_syslog_to_journal
= b
;
1669 /* Make the change effective immediately */
1671 if (log_target
== LOG_TARGET_SYSLOG
)
1672 log_target
= LOG_TARGET_JOURNAL
;
1673 else if (log_target
== LOG_TARGET_SYSLOG_OR_KMSG
)
1674 log_target
= LOG_TARGET_JOURNAL_OR_KMSG
;
1678 void log_set_always_reopen_console(bool b
) {
1679 always_reopen_console
= b
;
1682 void log_set_open_when_needed(bool b
) {
1683 open_when_needed
= b
;
1686 void log_set_prohibit_ipc(bool b
) {
1690 int log_emergency_level(void) {
1691 /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1692 * then the system of the whole system is obviously affected. */
1694 return getpid_cached() == 1 ? LOG_EMERG
: LOG_ERR
;
1697 int log_dup_console(void) {
1700 /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1701 * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1703 if (console_fd
< 0 || console_fd
>= 3)
1706 copy
= fcntl(console_fd
, F_DUPFD_CLOEXEC
, 3);
1714 void log_setup(void) {
1715 log_set_target(LOG_TARGET_AUTO
);
1716 log_parse_environment();
1718 if (log_on_console() && show_color
< 0)
1719 log_show_color(true);
1722 const char* _log_set_prefix(const char *prefix
, bool force
) {
1723 const char *old
= log_prefix
;
1725 if (prefix
|| force
)
1726 log_prefix
= prefix
;