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 "output-mode.h"
29 #include "parse-util.h"
30 #include "process-util.h"
31 #include "sparse-endian.h"
32 #include "stdio-util.h"
33 #include "string-table.h"
34 #include "string-util.h"
36 #include "terminal-util.h"
37 #include "time-util.h"
41 /* up to three lines (each up to 100 characters) or 300 characters, whichever is less */
42 #define PRINT_LINE_THRESHOLD 3
43 #define PRINT_CHAR_THRESHOLD 300
45 #define JSON_THRESHOLD 4096U
47 static int print_catalog(FILE *f
, sd_journal
*j
) {
49 _cleanup_free_
char *t
= NULL
, *z
= NULL
;
51 r
= sd_journal_get_catalog(j
, &t
);
55 z
= strreplace(strstrip(t
), "\n", "\n-- ");
66 static int parse_field(const void *data
, size_t length
, const char *field
, size_t field_len
, char **target
, size_t *target_len
) {
74 if (length
< field_len
)
77 if (memcmp(data
, field
, field_len
))
80 nl
= length
- field_len
;
82 buf
= newdup_suffix0(char, (const char*) data
+ field_len
, nl
);
95 typedef struct ParseFieldVec
{
102 #define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) \
103 { .field = _field, .field_len = strlen(_field), .target = _target, .target_len = _target_len }
105 static int parse_fieldv(const void *data
, size_t length
, const ParseFieldVec
*fields
, unsigned n_fields
) {
108 for (i
= 0; i
< n_fields
; i
++) {
109 const ParseFieldVec
*f
= &fields
[i
];
112 r
= parse_field(data
, length
, f
->field
, f
->field_len
, f
->target
, f
->target_len
);
122 static int field_set_test(Set
*fields
, const char *name
, size_t n
) {
128 s
= strndupa(name
, n
);
132 return set_get(fields
, s
) ? 1 : 0;
135 static bool shall_print(const char *p
, size_t l
, OutputFlags flags
) {
138 if (flags
& OUTPUT_SHOW_ALL
)
141 if (l
>= PRINT_CHAR_THRESHOLD
)
144 if (!utf8_is_printable(p
, l
))
150 static bool print_multiline(
158 size_t highlight
[2]) {
160 const char *color_on
= "", *color_off
= "", *highlight_on
= "";
161 const char *pos
, *end
;
162 bool ellipsized
= false;
165 if (flags
& OUTPUT_COLOR
) {
166 if (priority
<= LOG_ERR
) {
167 color_on
= ANSI_HIGHLIGHT_RED
;
168 color_off
= ANSI_NORMAL
;
169 highlight_on
= ANSI_HIGHLIGHT
;
170 } else if (priority
<= LOG_NOTICE
) {
171 color_on
= ANSI_HIGHLIGHT
;
172 color_off
= ANSI_NORMAL
;
173 highlight_on
= ANSI_HIGHLIGHT_RED
;
174 } else if (priority
>= LOG_DEBUG
) {
175 color_on
= ANSI_GREY
;
176 color_off
= ANSI_NORMAL
;
177 highlight_on
= ANSI_HIGHLIGHT_RED
;
181 /* A special case: make sure that we print a newline when
182 the message is empty. */
183 if (message_len
== 0)
187 pos
< message
+ message_len
;
188 pos
= end
+ 1, line
++) {
189 bool continuation
= line
> 0;
192 for (end
= pos
; end
< message
+ message_len
&& *end
!= '\n'; end
++)
197 /* We need to figure out when we are showing not-last line, *and*
198 * will skip subsequent lines. In that case, we will put the dots
199 * at the end of the line, instead of putting dots in the middle
203 line
+ 1 == PRINT_LINE_THRESHOLD
||
204 end
+ 1 >= message
+ PRINT_CHAR_THRESHOLD
;
206 if (flags
& (OUTPUT_FULL_WIDTH
| OUTPUT_SHOW_ALL
) ||
207 (prefix
+ len
+ 1 < n_columns
&& !tail_line
)) {
209 (size_t) (pos
- message
) <= highlight
[0] &&
210 highlight
[0] < (size_t) len
) {
212 fprintf(f
, "%*s%s%.*s",
213 continuation
* prefix
, "",
214 color_on
, (int) highlight
[0], pos
);
217 (int) (MIN((size_t) len
, highlight
[1]) - highlight
[0]),
219 if ((size_t) len
> highlight
[1])
222 (int) (len
- highlight
[1]),
224 fprintf(f
, "%s\n", color_off
);
227 fprintf(f
, "%*s%s%.*s%s\n",
228 continuation
* prefix
, "",
229 color_on
, len
, pos
, color_off
);
233 /* Beyond this point, ellipsization will happen. */
236 if (prefix
< n_columns
&& n_columns
- prefix
>= 3) {
237 if (n_columns
- prefix
> (unsigned) len
+ 3)
238 fprintf(f
, "%*s%s%.*s...%s\n",
239 continuation
* prefix
, "",
240 color_on
, len
, pos
, color_off
);
242 _cleanup_free_
char *e
;
244 e
= ellipsize_mem(pos
, len
, n_columns
- prefix
,
245 tail_line
? 100 : 90);
247 fprintf(f
, "%*s%s%.*s%s\n",
248 continuation
* prefix
, "",
249 color_on
, len
, pos
, color_off
);
251 fprintf(f
, "%*s%s%s%s\n",
252 continuation
* prefix
, "",
253 color_on
, e
, color_off
);
265 static int output_timestamp_monotonic(FILE *f
, sd_journal
*j
, const char *monotonic
) {
275 r
= safe_atou64(monotonic
, &t
);
277 r
= sd_journal_get_monotonic_usec(j
, &t
, &boot_id
);
279 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
281 fprintf(f
, "[%5"PRI_USEC
".%06"PRI_USEC
"]", t
/ USEC_PER_SEC
, t
% USEC_PER_SEC
);
282 return 1 + 5 + 1 + 6 + 1;
285 static int output_timestamp_realtime(FILE *f
, sd_journal
*j
, OutputMode mode
, OutputFlags flags
, const char *realtime
) {
286 char buf
[MAX(FORMAT_TIMESTAMP_MAX
, 64)];
287 struct tm
*(*gettime_r
)(const time_t *, struct tm
*);
297 r
= safe_atou64(realtime
, &x
);
298 if (!realtime
|| r
< 0 || !VALID_REALTIME(x
))
299 r
= sd_journal_get_realtime_usec(j
, &x
);
301 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
303 if (IN_SET(mode
, OUTPUT_SHORT_FULL
, OUTPUT_WITH_UNIT
)) {
306 if (flags
& OUTPUT_UTC
)
307 k
= format_timestamp_utc(buf
, sizeof(buf
), x
);
309 k
= format_timestamp(buf
, sizeof(buf
), x
);
311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
312 "Failed to format timestamp: %" PRIu64
, x
);
317 gettime_r
= (flags
& OUTPUT_UTC
) ? gmtime_r
: localtime_r
;
318 t
= (time_t) (x
/ USEC_PER_SEC
);
322 case OUTPUT_SHORT_UNIX
:
323 xsprintf(buf
, "%10"PRI_TIME
".%06"PRIu64
, t
, x
% USEC_PER_SEC
);
326 case OUTPUT_SHORT_ISO
:
327 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t
, &tm
)) <= 0)
328 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
329 "Failed to format ISO time");
332 case OUTPUT_SHORT_ISO_PRECISE
:
333 /* No usec in strftime, so we leave space and copy over */
334 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t
, &tm
)) <= 0)
335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
336 "Failed to format ISO-precise time");
337 xsprintf(usec
, "%06"PRI_USEC
, x
% USEC_PER_SEC
);
338 memcpy(buf
+ 20, usec
, 6);
342 case OUTPUT_SHORT_PRECISE
:
344 if (strftime(buf
, sizeof(buf
), "%b %d %H:%M:%S", gettime_r(&t
, &tm
)) <= 0)
345 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
346 "Failed to format syslog time");
348 if (mode
== OUTPUT_SHORT_PRECISE
) {
351 assert(sizeof(buf
) > strlen(buf
));
352 k
= sizeof(buf
) - strlen(buf
);
354 r
= snprintf(buf
+ strlen(buf
), k
, ".%06"PRIu64
, x
% USEC_PER_SEC
);
355 if (r
<= 0 || (size_t) r
>= k
) /* too long? */
356 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
357 "Failed to format precise time");
362 assert_not_reached("Unknown time format");
367 return (int) strlen(buf
);
370 static int output_short(
377 const size_t highlight
[2]) {
383 _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
;
384 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;
386 bool ellipsized
= false;
387 const ParseFieldVec fields
[] = {
388 PARSE_FIELD_VEC_ENTRY("_PID=", &pid
, &pid_len
),
389 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm
, &comm_len
),
390 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message
, &message_len
),
391 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority
, &priority_len
),
392 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname
, &hostname_len
),
393 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid
, &fake_pid_len
),
394 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier
, &identifier_len
),
395 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime
, &realtime_len
),
396 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic
, &monotonic_len
),
397 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit
, &unit_len
),
398 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit
, &user_unit_len
),
400 size_t highlight_shifted
[] = {highlight
? highlight
[0] : 0, highlight
? highlight
[1] : 0};
405 /* Set the threshold to one bigger than the actual print
406 * threshold, so that if the line is actually longer than what
407 * we're willing to print, ellipsization will occur. This way
408 * we won't output a misleading line without any indication of
411 sd_journal_set_data_threshold(j
, flags
& (OUTPUT_SHOW_ALL
|OUTPUT_FULL_WIDTH
) ? 0 : PRINT_CHAR_THRESHOLD
+ 1);
413 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
414 r
= parse_fieldv(data
, length
, fields
, ELEMENTSOF(fields
));
419 log_debug_errno(r
, "Skipping message we can't read: %m");
423 return log_error_errno(r
, "Failed to get journal fields: %m");
426 log_debug("Skipping message without MESSAGE= field.");
430 if (!(flags
& OUTPUT_SHOW_ALL
))
431 strip_tab_ansi(&message
, &message_len
, highlight_shifted
);
433 if (priority_len
== 1 && *priority
>= '0' && *priority
<= '7')
436 if (mode
== OUTPUT_SHORT_MONOTONIC
)
437 r
= output_timestamp_monotonic(f
, j
, monotonic
);
439 r
= output_timestamp_realtime(f
, j
, mode
, flags
, realtime
);
444 if (flags
& OUTPUT_NO_HOSTNAME
) {
445 /* Suppress display of the hostname if this is requested. */
446 hostname
= mfree(hostname
);
450 if (hostname
&& shall_print(hostname
, hostname_len
, flags
)) {
451 fprintf(f
, " %.*s", (int) hostname_len
, hostname
);
452 n
+= hostname_len
+ 1;
455 if (mode
== OUTPUT_WITH_UNIT
&& ((unit
&& shall_print(unit
, unit_len
, flags
)) || (user_unit
&& shall_print(user_unit
, user_unit_len
, flags
)))) {
457 fprintf(f
, " %.*s", (int) unit_len
, unit
);
462 fprintf(f
, "/%.*s", (int) user_unit_len
, user_unit
);
464 fprintf(f
, " %.*s", (int) user_unit_len
, user_unit
);
467 } else if (identifier
&& shall_print(identifier
, identifier_len
, flags
)) {
468 fprintf(f
, " %.*s", (int) identifier_len
, identifier
);
469 n
+= identifier_len
+ 1;
470 } else if (comm
&& shall_print(comm
, comm_len
, flags
)) {
471 fprintf(f
, " %.*s", (int) comm_len
, comm
);
474 fputs(" unknown", f
);
476 if (pid
&& shall_print(pid
, pid_len
, flags
)) {
477 fprintf(f
, "[%.*s]", (int) pid_len
, pid
);
479 } else if (fake_pid
&& shall_print(fake_pid
, fake_pid_len
, flags
)) {
480 fprintf(f
, "[%.*s]", (int) fake_pid_len
, fake_pid
);
481 n
+= fake_pid_len
+ 2;
484 if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(message
, message_len
)) {
485 char bytes
[FORMAT_BYTES_MAX
];
486 fprintf(f
, ": [%s blob data]\n", format_bytes(bytes
, sizeof(bytes
), message_len
));
490 print_multiline(f
, n
+ 2, n_columns
, flags
, p
,
491 message
, message_len
,
495 if (flags
& OUTPUT_CATALOG
)
501 static int output_verbose(
508 const size_t highlight
[2]) {
512 _cleanup_free_
char *cursor
= NULL
;
513 uint64_t realtime
= 0;
514 char ts
[FORMAT_TIMESTAMP_MAX
+ 7];
515 const char *timestamp
;
521 sd_journal_set_data_threshold(j
, 0);
523 r
= sd_journal_get_data(j
, "_SOURCE_REALTIME_TIMESTAMP", &data
, &length
);
525 log_debug("Source realtime timestamp not found");
527 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get source realtime timestamp: %m");
529 _cleanup_free_
char *value
= NULL
;
531 r
= parse_field(data
, length
, "_SOURCE_REALTIME_TIMESTAMP=",
532 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value
,
538 r
= safe_atou64(value
, &realtime
);
540 log_debug_errno(r
, "Failed to parse realtime timestamp: %m");
544 r
= sd_journal_get_realtime_usec(j
, &realtime
);
546 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get realtime timestamp: %m");
549 r
= sd_journal_get_cursor(j
, &cursor
);
551 return log_error_errno(r
, "Failed to get cursor: %m");
553 timestamp
= flags
& OUTPUT_UTC
? format_timestamp_us_utc(ts
, sizeof ts
, realtime
)
554 : format_timestamp_us(ts
, sizeof ts
, realtime
);
555 fprintf(f
, "%s [%s]\n",
556 timestamp
?: "(no timestamp)",
559 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
562 const char *on
= "", *off
= "";
564 c
= memchr(data
, '=', length
);
566 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
568 fieldlen
= c
- (const char*) data
;
570 r
= field_set_test(output_fields
, data
, fieldlen
);
576 if (flags
& OUTPUT_COLOR
&& startswith(data
, "MESSAGE=")) {
581 if ((flags
& OUTPUT_SHOW_ALL
) ||
582 (((length
< PRINT_CHAR_THRESHOLD
) || flags
& OUTPUT_FULL_WIDTH
)
583 && utf8_is_printable(data
, length
))) {
584 fprintf(f
, " %s%.*s=", on
, fieldlen
, (const char*)data
);
585 print_multiline(f
, 4 + fieldlen
+ 1, 0, OUTPUT_FULL_WIDTH
, 0, c
+ 1, length
- fieldlen
- 1, NULL
);
588 char bytes
[FORMAT_BYTES_MAX
];
590 fprintf(f
, " %s%.*s=[%s blob data]%s\n",
592 (int) (c
- (const char*) data
),
594 format_bytes(bytes
, sizeof(bytes
), length
- (c
- (const char *) data
) - 1),
602 if (flags
& OUTPUT_CATALOG
)
608 static int output_export(
615 const size_t highlight
[2]) {
620 usec_t realtime
, monotonic
;
621 _cleanup_free_
char *cursor
= NULL
;
627 sd_journal_set_data_threshold(j
, 0);
629 r
= sd_journal_get_realtime_usec(j
, &realtime
);
631 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
633 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
635 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
637 r
= sd_journal_get_cursor(j
, &cursor
);
639 return log_error_errno(r
, "Failed to get cursor: %m");
643 "__REALTIME_TIMESTAMP="USEC_FMT
"\n"
644 "__MONOTONIC_TIMESTAMP="USEC_FMT
"\n"
649 sd_id128_to_string(boot_id
, sid
));
651 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
654 /* We already printed the boot id from the data in the header, hence let's suppress it here */
655 if (memory_startswith(data
, length
, "_BOOT_ID="))
658 c
= memchr(data
, '=', length
);
660 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
663 r
= field_set_test(output_fields
, data
, c
- (const char *) data
);
669 if (utf8_is_printable_newline(data
, length
, false))
670 fwrite(data
, length
, 1, f
);
674 fwrite(data
, c
- (const char*) data
, 1, f
);
676 le64
= htole64(length
- (c
- (const char*) data
) - 1);
677 fwrite(&le64
, sizeof(le64
), 1, f
);
678 fwrite(c
+ 1, length
- (c
- (const char*) data
) - 1, 1, f
);
684 log_debug_errno(r
, "Skipping message we can't read: %m");
705 if (!(flags
& OUTPUT_SHOW_ALL
) && l
>= JSON_THRESHOLD
)
708 else if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(p
, l
)) {
709 bool not_first
= false;
715 fprintf(f
, ", %u", (uint8_t) *p
);
718 fprintf(f
, "%u", (uint8_t) *p
);
730 if (IN_SET(*p
, '"', '\\')) {
733 } else if (*p
== '\n')
735 else if ((uint8_t) *p
< ' ')
736 fprintf(f
, "\\u%04x", (uint8_t) *p
);
751 JsonVariant
* values
[];
754 static int update_json_data(
761 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
765 if (!(flags
& OUTPUT_SHOW_ALL
) && strlen(name
) + 1 + size
>= JSON_THRESHOLD
)
766 r
= json_variant_new_null(&v
);
767 else if (utf8_is_printable(value
, size
))
768 r
= json_variant_new_stringn(&v
, value
, size
);
770 r
= json_variant_new_array_bytes(&v
, value
, size
);
772 return log_error_errno(r
, "Failed to allocate JSON data: %m");
774 d
= hashmap_get(h
, name
);
778 w
= realloc(d
, offsetof(struct json_data
, values
) + sizeof(JsonVariant
*) * (d
->n_values
+ 1));
783 assert_se(hashmap_update(h
, json_variant_string(d
->name
), d
) >= 0);
785 _cleanup_(json_variant_unrefp
) JsonVariant
*n
= NULL
;
787 r
= json_variant_new_string(&n
, name
);
789 return log_error_errno(r
, "Failed to allocate JSON name variant: %m");
791 d
= malloc0(offsetof(struct json_data
, values
) + sizeof(JsonVariant
*));
795 r
= hashmap_put(h
, json_variant_string(n
), d
);
798 return log_error_errno(r
, "Failed to insert JSON name into hashmap: %m");
801 d
->name
= TAKE_PTR(n
);
804 d
->values
[d
->n_values
++] = TAKE_PTR(v
);
808 static int update_json_data_split(
819 assert(data
|| size
== 0);
821 if (memory_startswith(data
, size
, "_BOOT_ID="))
824 eq
= memchr(data
, '=', MIN(size
, JSON_THRESHOLD
));
831 name
= strndupa(data
, eq
- (const char*) data
);
832 if (output_fields
&& !set_get(output_fields
, name
))
835 return update_json_data(h
, flags
, name
, eq
+ 1, size
- (eq
- (const char*) data
) - 1);
838 static int output_json(
845 const size_t highlight
[2]) {
847 char sid
[SD_ID128_STRING_MAX
], usecbuf
[DECIMAL_STR_MAX(usec_t
)];
848 _cleanup_(json_variant_unrefp
) JsonVariant
*object
= NULL
;
849 _cleanup_free_
char *cursor
= NULL
;
850 uint64_t realtime
, monotonic
;
851 JsonVariant
**array
= NULL
;
861 (void) sd_journal_set_data_threshold(j
, flags
& OUTPUT_SHOW_ALL
? 0 : JSON_THRESHOLD
);
863 r
= sd_journal_get_realtime_usec(j
, &realtime
);
865 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
867 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
869 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
871 r
= sd_journal_get_cursor(j
, &cursor
);
873 return log_error_errno(r
, "Failed to get cursor: %m");
875 h
= hashmap_new(&string_hash_ops
);
879 r
= update_json_data(h
, flags
, "__CURSOR", cursor
, strlen(cursor
));
883 xsprintf(usecbuf
, USEC_FMT
, realtime
);
884 r
= update_json_data(h
, flags
, "__REALTIME_TIMESTAMP", usecbuf
, strlen(usecbuf
));
888 xsprintf(usecbuf
, USEC_FMT
, monotonic
);
889 r
= update_json_data(h
, flags
, "__MONOTONIC_TIMESTAMP", usecbuf
, strlen(usecbuf
));
893 sd_id128_to_string(boot_id
, sid
);
894 r
= update_json_data(h
, flags
, "_BOOT_ID", sid
, strlen(sid
));
902 r
= sd_journal_enumerate_data(j
, &data
, &size
);
904 log_debug_errno(r
, "Skipping message we can't read: %m");
909 log_error_errno(r
, "Failed to read journal: %m");
915 r
= update_json_data_split(h
, flags
, output_fields
, data
, size
);
920 array
= new(JsonVariant
*, hashmap_size(h
)*2);
926 HASHMAP_FOREACH(d
, h
, i
) {
927 assert(d
->n_values
> 0);
929 array
[n
++] = json_variant_ref(d
->name
);
931 if (d
->n_values
== 1)
932 array
[n
++] = json_variant_ref(d
->values
[0]);
934 _cleanup_(json_variant_unrefp
) JsonVariant
*q
= NULL
;
936 r
= json_variant_new_array(&q
, d
->values
, d
->n_values
);
938 log_error_errno(r
, "Failed to create JSON array: %m");
942 array
[n
++] = TAKE_PTR(q
);
946 r
= json_variant_new_object(&object
, array
, n
);
948 log_error_errno(r
, "Failed to allocate JSON object: %m");
952 json_variant_dump(object
,
953 output_mode_to_json_format_flags(mode
) |
954 (FLAGS_SET(flags
, OUTPUT_COLOR
) ? JSON_FORMAT_COLOR
: 0),
960 while ((d
= hashmap_steal_first(h
))) {
963 json_variant_unref(d
->name
);
964 for (k
= 0; k
< d
->n_values
; k
++)
965 json_variant_unref(d
->values
[k
]);
972 json_variant_unref_many(array
, n
);
978 static int output_cat(
985 const size_t highlight
[2]) {
990 const char *highlight_on
= "", *highlight_off
= "";
995 if (flags
& OUTPUT_COLOR
) {
996 highlight_on
= ANSI_HIGHLIGHT_RED
;
997 highlight_off
= ANSI_NORMAL
;
1000 sd_journal_set_data_threshold(j
, 0);
1002 r
= sd_journal_get_data(j
, "MESSAGE", &data
, &l
);
1003 if (r
== -EBADMSG
) {
1004 log_debug_errno(r
, "Skipping message we can't read: %m");
1008 /* An entry without MESSAGE=? */
1012 return log_error_errno(r
, "Failed to get data: %m");
1017 if (highlight
&& (flags
& OUTPUT_COLOR
)) {
1018 assert(highlight
[0] <= highlight
[1]);
1019 assert(highlight
[1] <= l
- 8);
1021 fwrite((const char*) data
+ 8, 1, highlight
[0], f
);
1022 fwrite(highlight_on
, 1, strlen(highlight_on
), f
);
1023 fwrite((const char*) data
+ 8 + highlight
[0], 1, highlight
[1] - highlight
[0], f
);
1024 fwrite(highlight_off
, 1, strlen(highlight_off
), f
);
1025 fwrite((const char*) data
+ 8 + highlight
[1], 1, l
- 8 - highlight
[1], f
);
1027 fwrite((const char*) data
+ 8, 1, l
- 8, f
);
1033 static int (*output_funcs
[_OUTPUT_MODE_MAX
])(
1040 const size_t highlight
[2]) = {
1042 [OUTPUT_SHORT
] = output_short
,
1043 [OUTPUT_SHORT_ISO
] = output_short
,
1044 [OUTPUT_SHORT_ISO_PRECISE
] = output_short
,
1045 [OUTPUT_SHORT_PRECISE
] = output_short
,
1046 [OUTPUT_SHORT_MONOTONIC
] = output_short
,
1047 [OUTPUT_SHORT_UNIX
] = output_short
,
1048 [OUTPUT_SHORT_FULL
] = output_short
,
1049 [OUTPUT_VERBOSE
] = output_verbose
,
1050 [OUTPUT_EXPORT
] = output_export
,
1051 [OUTPUT_JSON
] = output_json
,
1052 [OUTPUT_JSON_PRETTY
] = output_json
,
1053 [OUTPUT_JSON_SSE
] = output_json
,
1054 [OUTPUT_JSON_SEQ
] = output_json
,
1055 [OUTPUT_CAT
] = output_cat
,
1056 [OUTPUT_WITH_UNIT
] = output_short
,
1059 int show_journal_entry(
1065 char **output_fields
,
1066 const size_t highlight
[2],
1070 _cleanup_set_free_free_ Set
*fields
= NULL
;
1072 assert(mode
< _OUTPUT_MODE_MAX
);
1075 n_columns
= columns();
1077 if (output_fields
) {
1078 fields
= set_new(&string_hash_ops
);
1082 ret
= set_put_strdupv(fields
, output_fields
);
1087 ret
= output_funcs
[mode
](f
, j
, mode
, n_columns
, flags
, fields
, highlight
);
1089 if (ellipsized
&& ret
> 0)
1095 static int maybe_print_begin_newline(FILE *f
, OutputFlags
*flags
) {
1099 if (!(*flags
& OUTPUT_BEGIN_NEWLINE
))
1102 /* Print a beginning new line if that's request, but only once
1103 * on the first line we print. */
1106 *flags
&= ~OUTPUT_BEGIN_NEWLINE
;
1122 bool need_seek
= false;
1123 int warn_cutoff
= flags
& OUTPUT_WARN_CUTOFF
;
1127 assert(mode
< _OUTPUT_MODE_MAX
);
1129 if (how_many
== (unsigned) -1)
1133 r
= sd_journal_seek_tail(j
);
1135 return log_error_errno(r
, "Failed to seek to tail: %m");
1137 r
= sd_journal_previous_skip(j
, how_many
);
1139 return log_error_errno(r
, "Failed to skip previous: %m");
1147 r
= sd_journal_next(j
);
1149 return log_error_errno(r
, "Failed to iterate through journal: %m");
1157 if (not_before
> 0) {
1158 r
= sd_journal_get_monotonic_usec(j
, &usec
, NULL
);
1160 /* -ESTALE is returned if the
1161 timestamp is not from this boot */
1165 return log_error_errno(r
, "Failed to get journal time: %m");
1167 if (usec
< not_before
)
1172 maybe_print_begin_newline(f
, &flags
);
1174 r
= show_journal_entry(f
, j
, mode
, n_columns
, flags
, NULL
, NULL
, ellipsized
);
1179 if (warn_cutoff
&& line
< how_many
&& not_before
> 0) {
1183 /* Check whether the cutoff line is too early */
1185 r
= sd_id128_get_boot(&boot_id
);
1187 return log_error_errno(r
, "Failed to get boot id: %m");
1189 r
= sd_journal_get_cutoff_monotonic_usec(j
, boot_id
, &cutoff
, NULL
);
1191 return log_error_errno(r
, "Failed to get journal cutoff time: %m");
1193 if (r
> 0 && not_before
< cutoff
) {
1194 maybe_print_begin_newline(f
, &flags
);
1195 fprintf(f
, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
1198 warn_cutoff
= false;
1201 if (!(flags
& OUTPUT_FOLLOW
))
1204 r
= sd_journal_wait(j
, USEC_INFINITY
);
1206 return log_error_errno(r
, "Failed to wait for journal: %m");
1213 int add_matches_for_unit(sd_journal
*j
, const char *unit
) {
1214 const char *m1
, *m2
, *m3
, *m4
;
1220 m1
= strjoina("_SYSTEMD_UNIT=", unit
);
1221 m2
= strjoina("COREDUMP_UNIT=", unit
);
1222 m3
= strjoina("UNIT=", unit
);
1223 m4
= strjoina("OBJECT_SYSTEMD_UNIT=", unit
);
1226 /* Look for messages from the service itself */
1227 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1229 /* Look for coredumps of the service */
1230 (r
= sd_journal_add_disjunction(j
)) ||
1231 (r
= sd_journal_add_match(j
, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1232 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1233 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1235 /* Look for messages from PID 1 about this service */
1236 (r
= sd_journal_add_disjunction(j
)) ||
1237 (r
= sd_journal_add_match(j
, "_PID=1", 0)) ||
1238 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1240 /* Look for messages from authorized daemons about this service */
1241 (r
= sd_journal_add_disjunction(j
)) ||
1242 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1243 (r
= sd_journal_add_match(j
, m4
, 0))
1246 if (r
== 0 && endswith(unit
, ".slice")) {
1249 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1251 /* Show all messages belonging to a slice */
1253 (r
= sd_journal_add_disjunction(j
)) ||
1254 (r
= sd_journal_add_match(j
, m5
, 0))
1261 int add_matches_for_user_unit(sd_journal
*j
, const char *unit
, uid_t uid
) {
1263 char *m1
, *m2
, *m3
, *m4
;
1264 char muid
[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t
)];
1269 m1
= strjoina("_SYSTEMD_USER_UNIT=", unit
);
1270 m2
= strjoina("USER_UNIT=", unit
);
1271 m3
= strjoina("COREDUMP_USER_UNIT=", unit
);
1272 m4
= strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit
);
1273 sprintf(muid
, "_UID="UID_FMT
, uid
);
1276 /* Look for messages from the user service itself */
1277 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1278 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1280 /* Look for messages from systemd about this service */
1281 (r
= sd_journal_add_disjunction(j
)) ||
1282 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1283 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1285 /* Look for coredumps of the service */
1286 (r
= sd_journal_add_disjunction(j
)) ||
1287 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1288 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1289 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1291 /* Look for messages from authorized daemons about this service */
1292 (r
= sd_journal_add_disjunction(j
)) ||
1293 (r
= sd_journal_add_match(j
, m4
, 0)) ||
1294 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1295 (r
= sd_journal_add_match(j
, "_UID=0", 0))
1298 if (r
== 0 && endswith(unit
, ".slice")) {
1301 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1303 /* Show all messages belonging to a slice */
1305 (r
= sd_journal_add_disjunction(j
)) ||
1306 (r
= sd_journal_add_match(j
, m5
, 0)) ||
1307 (r
= sd_journal_add_match(j
, muid
, 0))
1314 static int get_boot_id_for_machine(const char *machine
, sd_id128_t
*boot_id
) {
1315 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1316 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
1325 if (!machine_name_is_valid(machine
))
1328 r
= container_get_leader(machine
, &pid
);
1332 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, NULL
, &rootfd
);
1336 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1339 r
= namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1340 pidnsfd
, mntnsfd
, -1, -1, rootfd
, &child
);
1346 pair
[0] = safe_close(pair
[0]);
1348 fd
= open("/proc/sys/kernel/random/boot_id", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1350 _exit(EXIT_FAILURE
);
1352 r
= loop_read_exact(fd
, buf
, 36, false);
1355 _exit(EXIT_FAILURE
);
1357 k
= send(pair
[1], buf
, 36, MSG_NOSIGNAL
);
1359 _exit(EXIT_FAILURE
);
1361 _exit(EXIT_SUCCESS
);
1364 pair
[1] = safe_close(pair
[1]);
1366 r
= wait_for_terminate_and_check("(sd-bootidns)", child
, 0);
1369 if (r
!= EXIT_SUCCESS
)
1372 k
= recv(pair
[0], buf
, 36, 0);
1377 r
= sd_id128_from_string(buf
, boot_id
);
1384 int add_match_this_boot(sd_journal
*j
, const char *machine
) {
1385 char match
[9+32+1] = "_BOOT_ID=";
1392 r
= get_boot_id_for_machine(machine
, &boot_id
);
1394 return log_error_errno(r
, "Failed to get boot id of container %s: %m", machine
);
1396 r
= sd_id128_get_boot(&boot_id
);
1398 return log_error_errno(r
, "Failed to get boot id: %m");
1401 sd_id128_to_string(boot_id
, match
+ 9);
1402 r
= sd_journal_add_match(j
, match
, strlen(match
));
1404 return log_error_errno(r
, "Failed to add match: %m");
1406 r
= sd_journal_add_conjunction(j
);
1408 return log_error_errno(r
, "Failed to add conjunction: %m");
1413 int show_journal_by_unit(
1422 int journal_open_flags
,
1426 _cleanup_(sd_journal_closep
) sd_journal
*j
= NULL
;
1430 assert(mode
< _OUTPUT_MODE_MAX
);
1436 r
= sd_journal_open(&j
, journal_open_flags
);
1438 return log_error_errno(r
, "Failed to open journal: %m");
1440 r
= add_match_this_boot(j
, NULL
);
1445 r
= add_matches_for_unit(j
, unit
);
1447 r
= add_matches_for_user_unit(j
, unit
, uid
);
1449 return log_error_errno(r
, "Failed to add unit matches: %m");
1451 if (DEBUG_LOGGING
) {
1452 _cleanup_free_
char *filter
;
1454 filter
= journal_make_match_string(j
);
1458 log_debug("Journal filter: %s", filter
);
1461 return show_journal(f
, j
, mode
, n_columns
, not_before
, how_many
, flags
, ellipsized
);