1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include <sys/socket.h>
15 #include "sd-journal.h"
17 #include "alloc-util.h"
19 #include "format-util.h"
21 #include "hostname-util.h"
23 #include "journal-internal.h"
26 #include "logs-show.h"
28 #include "namespace-util.h"
29 #include "output-mode.h"
30 #include "parse-util.h"
31 #include "process-util.h"
32 #include "sparse-endian.h"
33 #include "stdio-util.h"
34 #include "string-table.h"
35 #include "string-util.h"
37 #include "terminal-util.h"
38 #include "time-util.h"
42 /* up to three lines (each up to 100 characters) or 300 characters, whichever is less */
43 #define PRINT_LINE_THRESHOLD 3
44 #define PRINT_CHAR_THRESHOLD 300
46 #define JSON_THRESHOLD 4096U
48 static int print_catalog(FILE *f
, sd_journal
*j
) {
50 _cleanup_free_
char *t
= NULL
, *z
= NULL
;
52 r
= sd_journal_get_catalog(j
, &t
);
56 z
= strreplace(strstrip(t
), "\n", "\n-- ");
67 static int parse_field(const void *data
, size_t length
, const char *field
, size_t field_len
, char **target
, size_t *target_len
) {
75 if (length
< field_len
)
78 if (memcmp(data
, field
, field_len
))
81 nl
= length
- field_len
;
83 buf
= newdup_suffix0(char, (const char*) data
+ field_len
, nl
);
96 typedef struct ParseFieldVec
{
103 #define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) \
104 { .field = _field, .field_len = strlen(_field), .target = _target, .target_len = _target_len }
106 static int parse_fieldv(const void *data
, size_t length
, const ParseFieldVec
*fields
, unsigned n_fields
) {
109 for (i
= 0; i
< n_fields
; i
++) {
110 const ParseFieldVec
*f
= &fields
[i
];
113 r
= parse_field(data
, length
, f
->field
, f
->field_len
, f
->target
, f
->target_len
);
123 static int field_set_test(Set
*fields
, const char *name
, size_t n
) {
129 s
= strndupa(name
, n
);
133 return set_get(fields
, s
) ? 1 : 0;
136 static bool shall_print(const char *p
, size_t l
, OutputFlags flags
) {
139 if (flags
& OUTPUT_SHOW_ALL
)
142 if (l
>= PRINT_CHAR_THRESHOLD
)
145 if (!utf8_is_printable(p
, l
))
151 static bool print_multiline(
159 size_t highlight
[2]) {
161 const char *color_on
= "", *color_off
= "", *highlight_on
= "";
162 const char *pos
, *end
;
163 bool ellipsized
= false;
166 if (flags
& OUTPUT_COLOR
) {
167 if (priority
<= LOG_ERR
) {
168 color_on
= ANSI_HIGHLIGHT_RED
;
169 color_off
= ANSI_NORMAL
;
170 highlight_on
= ANSI_HIGHLIGHT
;
171 } else if (priority
<= LOG_NOTICE
) {
172 color_on
= ANSI_HIGHLIGHT
;
173 color_off
= ANSI_NORMAL
;
174 highlight_on
= ANSI_HIGHLIGHT_RED
;
175 } else if (priority
>= LOG_DEBUG
) {
176 color_on
= ANSI_GREY
;
177 color_off
= ANSI_NORMAL
;
178 highlight_on
= ANSI_HIGHLIGHT_RED
;
182 /* A special case: make sure that we print a newline when
183 the message is empty. */
184 if (message_len
== 0)
188 pos
< message
+ message_len
;
189 pos
= end
+ 1, line
++) {
190 bool continuation
= line
> 0;
193 for (end
= pos
; end
< message
+ message_len
&& *end
!= '\n'; end
++)
198 /* We need to figure out when we are showing not-last line, *and*
199 * will skip subsequent lines. In that case, we will put the dots
200 * at the end of the line, instead of putting dots in the middle
204 line
+ 1 == PRINT_LINE_THRESHOLD
||
205 end
+ 1 >= message
+ PRINT_CHAR_THRESHOLD
;
207 if (flags
& (OUTPUT_FULL_WIDTH
| OUTPUT_SHOW_ALL
) ||
208 (prefix
+ len
+ 1 < n_columns
&& !tail_line
)) {
210 (size_t) (pos
- message
) <= highlight
[0] &&
211 highlight
[0] < (size_t) len
) {
213 fprintf(f
, "%*s%s%.*s",
214 continuation
* prefix
, "",
215 color_on
, (int) highlight
[0], pos
);
218 (int) (MIN((size_t) len
, highlight
[1]) - highlight
[0]),
220 if ((size_t) len
> highlight
[1])
223 (int) (len
- highlight
[1]),
225 fprintf(f
, "%s\n", color_off
);
228 fprintf(f
, "%*s%s%.*s%s\n",
229 continuation
* prefix
, "",
230 color_on
, len
, pos
, color_off
);
234 /* Beyond this point, ellipsization will happen. */
237 if (prefix
< n_columns
&& n_columns
- prefix
>= 3) {
238 if (n_columns
- prefix
> (unsigned) len
+ 3)
239 fprintf(f
, "%*s%s%.*s...%s\n",
240 continuation
* prefix
, "",
241 color_on
, len
, pos
, color_off
);
243 _cleanup_free_
char *e
;
245 e
= ellipsize_mem(pos
, len
, n_columns
- prefix
,
246 tail_line
? 100 : 90);
248 fprintf(f
, "%*s%s%.*s%s\n",
249 continuation
* prefix
, "",
250 color_on
, len
, pos
, color_off
);
252 fprintf(f
, "%*s%s%s%s\n",
253 continuation
* prefix
, "",
254 color_on
, e
, color_off
);
266 static int output_timestamp_monotonic(FILE *f
, sd_journal
*j
, const char *monotonic
) {
276 r
= safe_atou64(monotonic
, &t
);
278 r
= sd_journal_get_monotonic_usec(j
, &t
, &boot_id
);
280 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
282 fprintf(f
, "[%5"PRI_USEC
".%06"PRI_USEC
"]", t
/ USEC_PER_SEC
, t
% USEC_PER_SEC
);
283 return 1 + 5 + 1 + 6 + 1;
286 static int output_timestamp_realtime(FILE *f
, sd_journal
*j
, OutputMode mode
, OutputFlags flags
, const char *realtime
) {
287 char buf
[MAX(FORMAT_TIMESTAMP_MAX
, 64)];
288 struct tm
*(*gettime_r
)(const time_t *, struct tm
*);
298 r
= safe_atou64(realtime
, &x
);
299 if (!realtime
|| r
< 0 || !VALID_REALTIME(x
))
300 r
= sd_journal_get_realtime_usec(j
, &x
);
302 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
304 if (IN_SET(mode
, OUTPUT_SHORT_FULL
, OUTPUT_WITH_UNIT
)) {
307 if (flags
& OUTPUT_UTC
)
308 k
= format_timestamp_utc(buf
, sizeof(buf
), x
);
310 k
= format_timestamp(buf
, sizeof(buf
), x
);
312 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
313 "Failed to format timestamp: %" PRIu64
, x
);
318 gettime_r
= (flags
& OUTPUT_UTC
) ? gmtime_r
: localtime_r
;
319 t
= (time_t) (x
/ USEC_PER_SEC
);
323 case OUTPUT_SHORT_UNIX
:
324 xsprintf(buf
, "%10"PRI_TIME
".%06"PRIu64
, t
, x
% USEC_PER_SEC
);
327 case OUTPUT_SHORT_ISO
:
328 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t
, &tm
)) <= 0)
329 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
330 "Failed to format ISO time");
333 case OUTPUT_SHORT_ISO_PRECISE
:
334 /* No usec in strftime, so we leave space and copy over */
335 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t
, &tm
)) <= 0)
336 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
337 "Failed to format ISO-precise time");
338 xsprintf(usec
, "%06"PRI_USEC
, x
% USEC_PER_SEC
);
339 memcpy(buf
+ 20, usec
, 6);
343 case OUTPUT_SHORT_PRECISE
:
345 if (strftime(buf
, sizeof(buf
), "%b %d %H:%M:%S", gettime_r(&t
, &tm
)) <= 0)
346 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
347 "Failed to format syslog time");
349 if (mode
== OUTPUT_SHORT_PRECISE
) {
352 assert(sizeof(buf
) > strlen(buf
));
353 k
= sizeof(buf
) - strlen(buf
);
355 r
= snprintf(buf
+ strlen(buf
), k
, ".%06"PRIu64
, x
% USEC_PER_SEC
);
356 if (r
<= 0 || (size_t) r
>= k
) /* too long? */
357 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
358 "Failed to format precise time");
363 assert_not_reached("Unknown time format");
368 return (int) strlen(buf
);
371 static int output_short(
378 const size_t highlight
[2]) {
384 _cleanup_free_
char *hostname
= NULL
, *identifier
= NULL
, *comm
= NULL
, *pid
= NULL
, *fake_pid
= NULL
, *message
= NULL
, *realtime
= NULL
, *monotonic
= NULL
, *priority
= NULL
, *unit
= NULL
, *user_unit
= NULL
;
385 size_t hostname_len
= 0, identifier_len
= 0, comm_len
= 0, pid_len
= 0, fake_pid_len
= 0, message_len
= 0, realtime_len
= 0, monotonic_len
= 0, priority_len
= 0, unit_len
= 0, user_unit_len
= 0;
387 bool ellipsized
= false;
388 const ParseFieldVec fields
[] = {
389 PARSE_FIELD_VEC_ENTRY("_PID=", &pid
, &pid_len
),
390 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm
, &comm_len
),
391 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message
, &message_len
),
392 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority
, &priority_len
),
393 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname
, &hostname_len
),
394 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid
, &fake_pid_len
),
395 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier
, &identifier_len
),
396 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime
, &realtime_len
),
397 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic
, &monotonic_len
),
398 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit
, &unit_len
),
399 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit
, &user_unit_len
),
401 size_t highlight_shifted
[] = {highlight
? highlight
[0] : 0, highlight
? highlight
[1] : 0};
406 /* Set the threshold to one bigger than the actual print
407 * threshold, so that if the line is actually longer than what
408 * we're willing to print, ellipsization will occur. This way
409 * we won't output a misleading line without any indication of
412 sd_journal_set_data_threshold(j
, flags
& (OUTPUT_SHOW_ALL
|OUTPUT_FULL_WIDTH
) ? 0 : PRINT_CHAR_THRESHOLD
+ 1);
414 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
415 r
= parse_fieldv(data
, length
, fields
, ELEMENTSOF(fields
));
420 log_debug_errno(r
, "Skipping message we can't read: %m");
424 return log_error_errno(r
, "Failed to get journal fields: %m");
427 log_debug("Skipping message without MESSAGE= field.");
431 if (!(flags
& OUTPUT_SHOW_ALL
))
432 strip_tab_ansi(&message
, &message_len
, highlight_shifted
);
434 if (priority_len
== 1 && *priority
>= '0' && *priority
<= '7')
437 if (mode
== OUTPUT_SHORT_MONOTONIC
)
438 r
= output_timestamp_monotonic(f
, j
, monotonic
);
440 r
= output_timestamp_realtime(f
, j
, mode
, flags
, realtime
);
445 if (flags
& OUTPUT_NO_HOSTNAME
) {
446 /* Suppress display of the hostname if this is requested. */
447 hostname
= mfree(hostname
);
451 if (hostname
&& shall_print(hostname
, hostname_len
, flags
)) {
452 fprintf(f
, " %.*s", (int) hostname_len
, hostname
);
453 n
+= hostname_len
+ 1;
456 if (mode
== OUTPUT_WITH_UNIT
&& ((unit
&& shall_print(unit
, unit_len
, flags
)) || (user_unit
&& shall_print(user_unit
, user_unit_len
, flags
)))) {
458 fprintf(f
, " %.*s", (int) unit_len
, unit
);
463 fprintf(f
, "/%.*s", (int) user_unit_len
, user_unit
);
465 fprintf(f
, " %.*s", (int) user_unit_len
, user_unit
);
468 } else if (identifier
&& shall_print(identifier
, identifier_len
, flags
)) {
469 fprintf(f
, " %.*s", (int) identifier_len
, identifier
);
470 n
+= identifier_len
+ 1;
471 } else if (comm
&& shall_print(comm
, comm_len
, flags
)) {
472 fprintf(f
, " %.*s", (int) comm_len
, comm
);
475 fputs(" unknown", f
);
477 if (pid
&& shall_print(pid
, pid_len
, flags
)) {
478 fprintf(f
, "[%.*s]", (int) pid_len
, pid
);
480 } else if (fake_pid
&& shall_print(fake_pid
, fake_pid_len
, flags
)) {
481 fprintf(f
, "[%.*s]", (int) fake_pid_len
, fake_pid
);
482 n
+= fake_pid_len
+ 2;
485 if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(message
, message_len
)) {
486 char bytes
[FORMAT_BYTES_MAX
];
487 fprintf(f
, ": [%s blob data]\n", format_bytes(bytes
, sizeof(bytes
), message_len
));
491 print_multiline(f
, n
+ 2, n_columns
, flags
, p
,
492 message
, message_len
,
496 if (flags
& OUTPUT_CATALOG
)
502 static int output_verbose(
509 const size_t highlight
[2]) {
513 _cleanup_free_
char *cursor
= NULL
;
514 uint64_t realtime
= 0;
515 char ts
[FORMAT_TIMESTAMP_MAX
+ 7];
516 const char *timestamp
;
522 sd_journal_set_data_threshold(j
, 0);
524 r
= sd_journal_get_data(j
, "_SOURCE_REALTIME_TIMESTAMP", &data
, &length
);
526 log_debug("Source realtime timestamp not found");
528 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get source realtime timestamp: %m");
530 _cleanup_free_
char *value
= NULL
;
532 r
= parse_field(data
, length
, "_SOURCE_REALTIME_TIMESTAMP=",
533 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value
,
539 r
= safe_atou64(value
, &realtime
);
541 log_debug_errno(r
, "Failed to parse realtime timestamp: %m");
545 r
= sd_journal_get_realtime_usec(j
, &realtime
);
547 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get realtime timestamp: %m");
550 r
= sd_journal_get_cursor(j
, &cursor
);
552 return log_error_errno(r
, "Failed to get cursor: %m");
554 timestamp
= flags
& OUTPUT_UTC
? format_timestamp_us_utc(ts
, sizeof ts
, realtime
)
555 : format_timestamp_us(ts
, sizeof ts
, realtime
);
556 fprintf(f
, "%s [%s]\n",
557 timestamp
?: "(no timestamp)",
560 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
563 const char *on
= "", *off
= "";
565 c
= memchr(data
, '=', length
);
567 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
569 fieldlen
= c
- (const char*) data
;
571 r
= field_set_test(output_fields
, data
, fieldlen
);
577 if (flags
& OUTPUT_COLOR
&& startswith(data
, "MESSAGE=")) {
582 if ((flags
& OUTPUT_SHOW_ALL
) ||
583 (((length
< PRINT_CHAR_THRESHOLD
) || flags
& OUTPUT_FULL_WIDTH
)
584 && utf8_is_printable(data
, length
))) {
585 fprintf(f
, " %s%.*s=", on
, fieldlen
, (const char*)data
);
586 print_multiline(f
, 4 + fieldlen
+ 1, 0, OUTPUT_FULL_WIDTH
, 0, c
+ 1, length
- fieldlen
- 1, NULL
);
589 char bytes
[FORMAT_BYTES_MAX
];
591 fprintf(f
, " %s%.*s=[%s blob data]%s\n",
593 (int) (c
- (const char*) data
),
595 format_bytes(bytes
, sizeof(bytes
), length
- (c
- (const char *) data
) - 1),
603 if (flags
& OUTPUT_CATALOG
)
609 static int output_export(
616 const size_t highlight
[2]) {
621 usec_t realtime
, monotonic
;
622 _cleanup_free_
char *cursor
= NULL
;
628 sd_journal_set_data_threshold(j
, 0);
630 r
= sd_journal_get_realtime_usec(j
, &realtime
);
632 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
634 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
636 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
638 r
= sd_journal_get_cursor(j
, &cursor
);
640 return log_error_errno(r
, "Failed to get cursor: %m");
644 "__REALTIME_TIMESTAMP="USEC_FMT
"\n"
645 "__MONOTONIC_TIMESTAMP="USEC_FMT
"\n"
650 sd_id128_to_string(boot_id
, sid
));
652 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
655 /* We already printed the boot id from the data in the header, hence let's suppress it here */
656 if (memory_startswith(data
, length
, "_BOOT_ID="))
659 c
= memchr(data
, '=', length
);
661 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
664 r
= field_set_test(output_fields
, data
, c
- (const char *) data
);
670 if (utf8_is_printable_newline(data
, length
, false))
671 fwrite(data
, length
, 1, f
);
675 fwrite(data
, c
- (const char*) data
, 1, f
);
677 le64
= htole64(length
- (c
- (const char*) data
) - 1);
678 fwrite(&le64
, sizeof(le64
), 1, f
);
679 fwrite(c
+ 1, length
- (c
- (const char*) data
) - 1, 1, f
);
685 log_debug_errno(r
, "Skipping message we can't read: %m");
706 if (!(flags
& OUTPUT_SHOW_ALL
) && l
>= JSON_THRESHOLD
)
709 else if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(p
, l
)) {
710 bool not_first
= false;
716 fprintf(f
, ", %u", (uint8_t) *p
);
719 fprintf(f
, "%u", (uint8_t) *p
);
731 if (IN_SET(*p
, '"', '\\')) {
734 } else if (*p
== '\n')
736 else if ((uint8_t) *p
< ' ')
737 fprintf(f
, "\\u%04x", (uint8_t) *p
);
752 JsonVariant
* values
[];
755 static int update_json_data(
762 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
766 if (!(flags
& OUTPUT_SHOW_ALL
) && strlen(name
) + 1 + size
>= JSON_THRESHOLD
)
767 r
= json_variant_new_null(&v
);
768 else if (utf8_is_printable(value
, size
))
769 r
= json_variant_new_stringn(&v
, value
, size
);
771 r
= json_variant_new_array_bytes(&v
, value
, size
);
773 return log_error_errno(r
, "Failed to allocate JSON data: %m");
775 d
= hashmap_get(h
, name
);
779 w
= realloc(d
, offsetof(struct json_data
, values
) + sizeof(JsonVariant
*) * (d
->n_values
+ 1));
784 assert_se(hashmap_update(h
, json_variant_string(d
->name
), d
) >= 0);
786 _cleanup_(json_variant_unrefp
) JsonVariant
*n
= NULL
;
788 r
= json_variant_new_string(&n
, name
);
790 return log_error_errno(r
, "Failed to allocate JSON name variant: %m");
792 d
= malloc0(offsetof(struct json_data
, values
) + sizeof(JsonVariant
*));
796 r
= hashmap_put(h
, json_variant_string(n
), d
);
799 return log_error_errno(r
, "Failed to insert JSON name into hashmap: %m");
802 d
->name
= TAKE_PTR(n
);
805 d
->values
[d
->n_values
++] = TAKE_PTR(v
);
809 static int update_json_data_split(
820 assert(data
|| size
== 0);
822 if (memory_startswith(data
, size
, "_BOOT_ID="))
825 eq
= memchr(data
, '=', MIN(size
, JSON_THRESHOLD
));
832 name
= strndupa(data
, eq
- (const char*) data
);
833 if (output_fields
&& !set_get(output_fields
, name
))
836 return update_json_data(h
, flags
, name
, eq
+ 1, size
- (eq
- (const char*) data
) - 1);
839 static int output_json(
846 const size_t highlight
[2]) {
848 char sid
[SD_ID128_STRING_MAX
], usecbuf
[DECIMAL_STR_MAX(usec_t
)];
849 _cleanup_(json_variant_unrefp
) JsonVariant
*object
= NULL
;
850 _cleanup_free_
char *cursor
= NULL
;
851 uint64_t realtime
, monotonic
;
852 JsonVariant
**array
= NULL
;
862 (void) sd_journal_set_data_threshold(j
, flags
& OUTPUT_SHOW_ALL
? 0 : JSON_THRESHOLD
);
864 r
= sd_journal_get_realtime_usec(j
, &realtime
);
866 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
868 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
870 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
872 r
= sd_journal_get_cursor(j
, &cursor
);
874 return log_error_errno(r
, "Failed to get cursor: %m");
876 h
= hashmap_new(&string_hash_ops
);
880 r
= update_json_data(h
, flags
, "__CURSOR", cursor
, strlen(cursor
));
884 xsprintf(usecbuf
, USEC_FMT
, realtime
);
885 r
= update_json_data(h
, flags
, "__REALTIME_TIMESTAMP", usecbuf
, strlen(usecbuf
));
889 xsprintf(usecbuf
, USEC_FMT
, monotonic
);
890 r
= update_json_data(h
, flags
, "__MONOTONIC_TIMESTAMP", usecbuf
, strlen(usecbuf
));
894 sd_id128_to_string(boot_id
, sid
);
895 r
= update_json_data(h
, flags
, "_BOOT_ID", sid
, strlen(sid
));
903 r
= sd_journal_enumerate_data(j
, &data
, &size
);
905 log_debug_errno(r
, "Skipping message we can't read: %m");
910 log_error_errno(r
, "Failed to read journal: %m");
916 r
= update_json_data_split(h
, flags
, output_fields
, data
, size
);
921 array
= new(JsonVariant
*, hashmap_size(h
)*2);
927 HASHMAP_FOREACH(d
, h
, i
) {
928 assert(d
->n_values
> 0);
930 array
[n
++] = json_variant_ref(d
->name
);
932 if (d
->n_values
== 1)
933 array
[n
++] = json_variant_ref(d
->values
[0]);
935 _cleanup_(json_variant_unrefp
) JsonVariant
*q
= NULL
;
937 r
= json_variant_new_array(&q
, d
->values
, d
->n_values
);
939 log_error_errno(r
, "Failed to create JSON array: %m");
943 array
[n
++] = TAKE_PTR(q
);
947 r
= json_variant_new_object(&object
, array
, n
);
949 log_error_errno(r
, "Failed to allocate JSON object: %m");
953 json_variant_dump(object
,
954 output_mode_to_json_format_flags(mode
) |
955 (FLAGS_SET(flags
, OUTPUT_COLOR
) ? JSON_FORMAT_COLOR
: 0),
961 while ((d
= hashmap_steal_first(h
))) {
964 json_variant_unref(d
->name
);
965 for (k
= 0; k
< d
->n_values
; k
++)
966 json_variant_unref(d
->values
[k
]);
973 json_variant_unref_many(array
, n
);
979 static int output_cat(
986 const size_t highlight
[2]) {
991 const char *highlight_on
= "", *highlight_off
= "";
996 if (flags
& OUTPUT_COLOR
) {
997 highlight_on
= ANSI_HIGHLIGHT_RED
;
998 highlight_off
= ANSI_NORMAL
;
1001 sd_journal_set_data_threshold(j
, 0);
1003 r
= sd_journal_get_data(j
, "MESSAGE", &data
, &l
);
1004 if (r
== -EBADMSG
) {
1005 log_debug_errno(r
, "Skipping message we can't read: %m");
1009 /* An entry without MESSAGE=? */
1013 return log_error_errno(r
, "Failed to get data: %m");
1018 if (highlight
&& (flags
& OUTPUT_COLOR
)) {
1019 assert(highlight
[0] <= highlight
[1]);
1020 assert(highlight
[1] <= l
- 8);
1022 fwrite((const char*) data
+ 8, 1, highlight
[0], f
);
1023 fwrite(highlight_on
, 1, strlen(highlight_on
), f
);
1024 fwrite((const char*) data
+ 8 + highlight
[0], 1, highlight
[1] - highlight
[0], f
);
1025 fwrite(highlight_off
, 1, strlen(highlight_off
), f
);
1026 fwrite((const char*) data
+ 8 + highlight
[1], 1, l
- 8 - highlight
[1], f
);
1028 fwrite((const char*) data
+ 8, 1, l
- 8, f
);
1034 static int (*output_funcs
[_OUTPUT_MODE_MAX
])(
1041 const size_t highlight
[2]) = {
1043 [OUTPUT_SHORT
] = output_short
,
1044 [OUTPUT_SHORT_ISO
] = output_short
,
1045 [OUTPUT_SHORT_ISO_PRECISE
] = output_short
,
1046 [OUTPUT_SHORT_PRECISE
] = output_short
,
1047 [OUTPUT_SHORT_MONOTONIC
] = output_short
,
1048 [OUTPUT_SHORT_UNIX
] = output_short
,
1049 [OUTPUT_SHORT_FULL
] = output_short
,
1050 [OUTPUT_VERBOSE
] = output_verbose
,
1051 [OUTPUT_EXPORT
] = output_export
,
1052 [OUTPUT_JSON
] = output_json
,
1053 [OUTPUT_JSON_PRETTY
] = output_json
,
1054 [OUTPUT_JSON_SSE
] = output_json
,
1055 [OUTPUT_JSON_SEQ
] = output_json
,
1056 [OUTPUT_CAT
] = output_cat
,
1057 [OUTPUT_WITH_UNIT
] = output_short
,
1060 int show_journal_entry(
1066 char **output_fields
,
1067 const size_t highlight
[2],
1071 _cleanup_set_free_free_ Set
*fields
= NULL
;
1073 assert(mode
< _OUTPUT_MODE_MAX
);
1076 n_columns
= columns();
1078 if (output_fields
) {
1079 fields
= set_new(&string_hash_ops
);
1083 ret
= set_put_strdupv(fields
, output_fields
);
1088 ret
= output_funcs
[mode
](f
, j
, mode
, n_columns
, flags
, fields
, highlight
);
1090 if (ellipsized
&& ret
> 0)
1096 static int maybe_print_begin_newline(FILE *f
, OutputFlags
*flags
) {
1100 if (!(*flags
& OUTPUT_BEGIN_NEWLINE
))
1103 /* Print a beginning new line if that's request, but only once
1104 * on the first line we print. */
1107 *flags
&= ~OUTPUT_BEGIN_NEWLINE
;
1123 bool need_seek
= false;
1124 int warn_cutoff
= flags
& OUTPUT_WARN_CUTOFF
;
1128 assert(mode
< _OUTPUT_MODE_MAX
);
1130 if (how_many
== (unsigned) -1)
1134 r
= sd_journal_seek_tail(j
);
1136 return log_error_errno(r
, "Failed to seek to tail: %m");
1138 r
= sd_journal_previous_skip(j
, how_many
);
1140 return log_error_errno(r
, "Failed to skip previous: %m");
1148 r
= sd_journal_next(j
);
1150 return log_error_errno(r
, "Failed to iterate through journal: %m");
1158 if (not_before
> 0) {
1159 r
= sd_journal_get_monotonic_usec(j
, &usec
, NULL
);
1161 /* -ESTALE is returned if the
1162 timestamp is not from this boot */
1166 return log_error_errno(r
, "Failed to get journal time: %m");
1168 if (usec
< not_before
)
1173 maybe_print_begin_newline(f
, &flags
);
1175 r
= show_journal_entry(f
, j
, mode
, n_columns
, flags
, NULL
, NULL
, ellipsized
);
1180 if (warn_cutoff
&& line
< how_many
&& not_before
> 0) {
1184 /* Check whether the cutoff line is too early */
1186 r
= sd_id128_get_boot(&boot_id
);
1188 return log_error_errno(r
, "Failed to get boot id: %m");
1190 r
= sd_journal_get_cutoff_monotonic_usec(j
, boot_id
, &cutoff
, NULL
);
1192 return log_error_errno(r
, "Failed to get journal cutoff time: %m");
1194 if (r
> 0 && not_before
< cutoff
) {
1195 maybe_print_begin_newline(f
, &flags
);
1196 fprintf(f
, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
1199 warn_cutoff
= false;
1202 if (!(flags
& OUTPUT_FOLLOW
))
1205 r
= sd_journal_wait(j
, USEC_INFINITY
);
1207 return log_error_errno(r
, "Failed to wait for journal: %m");
1214 int add_matches_for_unit(sd_journal
*j
, const char *unit
) {
1215 const char *m1
, *m2
, *m3
, *m4
;
1221 m1
= strjoina("_SYSTEMD_UNIT=", unit
);
1222 m2
= strjoina("COREDUMP_UNIT=", unit
);
1223 m3
= strjoina("UNIT=", unit
);
1224 m4
= strjoina("OBJECT_SYSTEMD_UNIT=", unit
);
1227 /* Look for messages from the service itself */
1228 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1230 /* Look for coredumps of the service */
1231 (r
= sd_journal_add_disjunction(j
)) ||
1232 (r
= sd_journal_add_match(j
, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1233 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1234 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1236 /* Look for messages from PID 1 about this service */
1237 (r
= sd_journal_add_disjunction(j
)) ||
1238 (r
= sd_journal_add_match(j
, "_PID=1", 0)) ||
1239 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1241 /* Look for messages from authorized daemons about this service */
1242 (r
= sd_journal_add_disjunction(j
)) ||
1243 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1244 (r
= sd_journal_add_match(j
, m4
, 0))
1247 if (r
== 0 && endswith(unit
, ".slice")) {
1250 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1252 /* Show all messages belonging to a slice */
1254 (r
= sd_journal_add_disjunction(j
)) ||
1255 (r
= sd_journal_add_match(j
, m5
, 0))
1262 int add_matches_for_user_unit(sd_journal
*j
, const char *unit
, uid_t uid
) {
1264 char *m1
, *m2
, *m3
, *m4
;
1265 char muid
[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t
)];
1270 m1
= strjoina("_SYSTEMD_USER_UNIT=", unit
);
1271 m2
= strjoina("USER_UNIT=", unit
);
1272 m3
= strjoina("COREDUMP_USER_UNIT=", unit
);
1273 m4
= strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit
);
1274 sprintf(muid
, "_UID="UID_FMT
, uid
);
1277 /* Look for messages from the user service itself */
1278 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1279 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1281 /* Look for messages from systemd about this service */
1282 (r
= sd_journal_add_disjunction(j
)) ||
1283 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1284 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1286 /* Look for coredumps of the service */
1287 (r
= sd_journal_add_disjunction(j
)) ||
1288 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1289 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1290 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1292 /* Look for messages from authorized daemons about this service */
1293 (r
= sd_journal_add_disjunction(j
)) ||
1294 (r
= sd_journal_add_match(j
, m4
, 0)) ||
1295 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1296 (r
= sd_journal_add_match(j
, "_UID=0", 0))
1299 if (r
== 0 && endswith(unit
, ".slice")) {
1302 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1304 /* Show all messages belonging to a slice */
1306 (r
= sd_journal_add_disjunction(j
)) ||
1307 (r
= sd_journal_add_match(j
, m5
, 0)) ||
1308 (r
= sd_journal_add_match(j
, muid
, 0))
1315 static int get_boot_id_for_machine(const char *machine
, sd_id128_t
*boot_id
) {
1316 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1317 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
1326 if (!machine_name_is_valid(machine
))
1329 r
= container_get_leader(machine
, &pid
);
1333 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, NULL
, &rootfd
);
1337 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1340 r
= namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1341 pidnsfd
, mntnsfd
, -1, -1, rootfd
, &child
);
1347 pair
[0] = safe_close(pair
[0]);
1349 fd
= open("/proc/sys/kernel/random/boot_id", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1351 _exit(EXIT_FAILURE
);
1353 r
= loop_read_exact(fd
, buf
, 36, false);
1356 _exit(EXIT_FAILURE
);
1358 k
= send(pair
[1], buf
, 36, MSG_NOSIGNAL
);
1360 _exit(EXIT_FAILURE
);
1362 _exit(EXIT_SUCCESS
);
1365 pair
[1] = safe_close(pair
[1]);
1367 r
= wait_for_terminate_and_check("(sd-bootidns)", child
, 0);
1370 if (r
!= EXIT_SUCCESS
)
1373 k
= recv(pair
[0], buf
, 36, 0);
1378 r
= sd_id128_from_string(buf
, boot_id
);
1385 int add_match_this_boot(sd_journal
*j
, const char *machine
) {
1386 char match
[9+32+1] = "_BOOT_ID=";
1393 r
= get_boot_id_for_machine(machine
, &boot_id
);
1395 return log_error_errno(r
, "Failed to get boot id of container %s: %m", machine
);
1397 r
= sd_id128_get_boot(&boot_id
);
1399 return log_error_errno(r
, "Failed to get boot id: %m");
1402 sd_id128_to_string(boot_id
, match
+ 9);
1403 r
= sd_journal_add_match(j
, match
, strlen(match
));
1405 return log_error_errno(r
, "Failed to add match: %m");
1407 r
= sd_journal_add_conjunction(j
);
1409 return log_error_errno(r
, "Failed to add conjunction: %m");
1414 int show_journal_by_unit(
1423 int journal_open_flags
,
1427 _cleanup_(sd_journal_closep
) sd_journal
*j
= NULL
;
1431 assert(mode
< _OUTPUT_MODE_MAX
);
1437 r
= sd_journal_open(&j
, journal_open_flags
);
1439 return log_error_errno(r
, "Failed to open journal: %m");
1441 r
= add_match_this_boot(j
, NULL
);
1446 r
= add_matches_for_unit(j
, unit
);
1448 r
= add_matches_for_user_unit(j
, unit
, uid
);
1450 return log_error_errno(r
, "Failed to add unit matches: %m");
1452 if (DEBUG_LOGGING
) {
1453 _cleanup_free_
char *filter
;
1455 filter
= journal_make_match_string(j
);
1459 log_debug("Journal filter: %s", filter
);
1462 return show_journal(f
, j
, mode
, n_columns
, not_before
, how_many
, flags
, ellipsized
);