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
;
177 /* A special case: make sure that we print a newline when
178 the message is empty. */
179 if (message_len
== 0)
183 pos
< message
+ message_len
;
184 pos
= end
+ 1, line
++) {
185 bool continuation
= line
> 0;
188 for (end
= pos
; end
< message
+ message_len
&& *end
!= '\n'; end
++)
193 /* We need to figure out when we are showing not-last line, *and*
194 * will skip subsequent lines. In that case, we will put the dots
195 * at the end of the line, instead of putting dots in the middle
199 line
+ 1 == PRINT_LINE_THRESHOLD
||
200 end
+ 1 >= message
+ PRINT_CHAR_THRESHOLD
;
202 if (flags
& (OUTPUT_FULL_WIDTH
| OUTPUT_SHOW_ALL
) ||
203 (prefix
+ len
+ 1 < n_columns
&& !tail_line
)) {
205 (size_t) (pos
- message
) <= highlight
[0] &&
206 highlight
[0] < (size_t) len
) {
208 fprintf(f
, "%*s%s%.*s",
209 continuation
* prefix
, "",
210 color_on
, (int) highlight
[0], pos
);
213 (int) (MIN((size_t) len
, highlight
[1]) - highlight
[0]),
215 if ((size_t) len
> highlight
[1])
218 (int) (len
- highlight
[1]),
220 fprintf(f
, "%s\n", color_off
);
223 fprintf(f
, "%*s%s%.*s%s\n",
224 continuation
* prefix
, "",
225 color_on
, len
, pos
, color_off
);
229 /* Beyond this point, ellipsization will happen. */
232 if (prefix
< n_columns
&& n_columns
- prefix
>= 3) {
233 if (n_columns
- prefix
> (unsigned) len
+ 3)
234 fprintf(f
, "%*s%s%.*s...%s\n",
235 continuation
* prefix
, "",
236 color_on
, len
, pos
, color_off
);
238 _cleanup_free_
char *e
;
240 e
= ellipsize_mem(pos
, len
, n_columns
- prefix
,
241 tail_line
? 100 : 90);
243 fprintf(f
, "%*s%s%.*s%s\n",
244 continuation
* prefix
, "",
245 color_on
, len
, pos
, color_off
);
247 fprintf(f
, "%*s%s%s%s\n",
248 continuation
* prefix
, "",
249 color_on
, e
, color_off
);
261 static int output_timestamp_monotonic(FILE *f
, sd_journal
*j
, const char *monotonic
) {
271 r
= safe_atou64(monotonic
, &t
);
273 r
= sd_journal_get_monotonic_usec(j
, &t
, &boot_id
);
275 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
277 fprintf(f
, "[%5"PRI_USEC
".%06"PRI_USEC
"]", t
/ USEC_PER_SEC
, t
% USEC_PER_SEC
);
278 return 1 + 5 + 1 + 6 + 1;
281 static int output_timestamp_realtime(FILE *f
, sd_journal
*j
, OutputMode mode
, OutputFlags flags
, const char *realtime
) {
282 char buf
[MAX(FORMAT_TIMESTAMP_MAX
, 64)];
283 struct tm
*(*gettime_r
)(const time_t *, struct tm
*);
293 r
= safe_atou64(realtime
, &x
);
294 if (!realtime
|| r
< 0 || !VALID_REALTIME(x
))
295 r
= sd_journal_get_realtime_usec(j
, &x
);
297 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
299 if (IN_SET(mode
, OUTPUT_SHORT_FULL
, OUTPUT_WITH_UNIT
)) {
302 if (flags
& OUTPUT_UTC
)
303 k
= format_timestamp_utc(buf
, sizeof(buf
), x
);
305 k
= format_timestamp(buf
, sizeof(buf
), x
);
307 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
308 "Failed to format timestamp: %" PRIu64
, x
);
313 gettime_r
= (flags
& OUTPUT_UTC
) ? gmtime_r
: localtime_r
;
314 t
= (time_t) (x
/ USEC_PER_SEC
);
318 case OUTPUT_SHORT_UNIX
:
319 xsprintf(buf
, "%10"PRI_TIME
".%06"PRIu64
, t
, x
% USEC_PER_SEC
);
322 case OUTPUT_SHORT_ISO
:
323 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t
, &tm
)) <= 0)
324 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
325 "Failed to format ISO time");
328 case OUTPUT_SHORT_ISO_PRECISE
:
329 /* No usec in strftime, so we leave space and copy over */
330 if (strftime(buf
, sizeof(buf
), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t
, &tm
)) <= 0)
331 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
332 "Failed to format ISO-precise time");
333 xsprintf(usec
, "%06"PRI_USEC
, x
% USEC_PER_SEC
);
334 memcpy(buf
+ 20, usec
, 6);
338 case OUTPUT_SHORT_PRECISE
:
340 if (strftime(buf
, sizeof(buf
), "%b %d %H:%M:%S", gettime_r(&t
, &tm
)) <= 0)
341 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
342 "Failed to format syslog time");
344 if (mode
== OUTPUT_SHORT_PRECISE
) {
347 assert(sizeof(buf
) > strlen(buf
));
348 k
= sizeof(buf
) - strlen(buf
);
350 r
= snprintf(buf
+ strlen(buf
), k
, ".%06"PRIu64
, x
% USEC_PER_SEC
);
351 if (r
<= 0 || (size_t) r
>= k
) /* too long? */
352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
353 "Failed to format precise time");
358 assert_not_reached("Unknown time format");
363 return (int) strlen(buf
);
366 static int output_short(
373 const size_t highlight
[2]) {
379 _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
;
380 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;
382 bool ellipsized
= false;
383 const ParseFieldVec fields
[] = {
384 PARSE_FIELD_VEC_ENTRY("_PID=", &pid
, &pid_len
),
385 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm
, &comm_len
),
386 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message
, &message_len
),
387 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority
, &priority_len
),
388 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname
, &hostname_len
),
389 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid
, &fake_pid_len
),
390 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier
, &identifier_len
),
391 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime
, &realtime_len
),
392 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic
, &monotonic_len
),
393 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit
, &unit_len
),
394 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit
, &user_unit_len
),
396 size_t highlight_shifted
[] = {highlight
? highlight
[0] : 0, highlight
? highlight
[1] : 0};
401 /* Set the threshold to one bigger than the actual print
402 * threshold, so that if the line is actually longer than what
403 * we're willing to print, ellipsization will occur. This way
404 * we won't output a misleading line without any indication of
407 sd_journal_set_data_threshold(j
, flags
& (OUTPUT_SHOW_ALL
|OUTPUT_FULL_WIDTH
) ? 0 : PRINT_CHAR_THRESHOLD
+ 1);
409 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
410 r
= parse_fieldv(data
, length
, fields
, ELEMENTSOF(fields
));
415 log_debug_errno(r
, "Skipping message we can't read: %m");
419 return log_error_errno(r
, "Failed to get journal fields: %m");
422 log_debug("Skipping message without MESSAGE= field.");
426 if (!(flags
& OUTPUT_SHOW_ALL
))
427 strip_tab_ansi(&message
, &message_len
, highlight_shifted
);
429 if (priority_len
== 1 && *priority
>= '0' && *priority
<= '7')
432 if (mode
== OUTPUT_SHORT_MONOTONIC
)
433 r
= output_timestamp_monotonic(f
, j
, monotonic
);
435 r
= output_timestamp_realtime(f
, j
, mode
, flags
, realtime
);
440 if (flags
& OUTPUT_NO_HOSTNAME
) {
441 /* Suppress display of the hostname if this is requested. */
442 hostname
= mfree(hostname
);
446 if (hostname
&& shall_print(hostname
, hostname_len
, flags
)) {
447 fprintf(f
, " %.*s", (int) hostname_len
, hostname
);
448 n
+= hostname_len
+ 1;
451 if (mode
== OUTPUT_WITH_UNIT
&& ((unit
&& shall_print(unit
, unit_len
, flags
)) || (user_unit
&& shall_print(user_unit
, user_unit_len
, flags
)))) {
453 fprintf(f
, " %.*s", (int) unit_len
, unit
);
458 fprintf(f
, "/%.*s", (int) user_unit_len
, user_unit
);
460 fprintf(f
, " %.*s", (int) user_unit_len
, user_unit
);
463 } else if (identifier
&& shall_print(identifier
, identifier_len
, flags
)) {
464 fprintf(f
, " %.*s", (int) identifier_len
, identifier
);
465 n
+= identifier_len
+ 1;
466 } else if (comm
&& shall_print(comm
, comm_len
, flags
)) {
467 fprintf(f
, " %.*s", (int) comm_len
, comm
);
470 fputs(" unknown", f
);
472 if (pid
&& shall_print(pid
, pid_len
, flags
)) {
473 fprintf(f
, "[%.*s]", (int) pid_len
, pid
);
475 } else if (fake_pid
&& shall_print(fake_pid
, fake_pid_len
, flags
)) {
476 fprintf(f
, "[%.*s]", (int) fake_pid_len
, fake_pid
);
477 n
+= fake_pid_len
+ 2;
480 if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(message
, message_len
)) {
481 char bytes
[FORMAT_BYTES_MAX
];
482 fprintf(f
, ": [%s blob data]\n", format_bytes(bytes
, sizeof(bytes
), message_len
));
486 print_multiline(f
, n
+ 2, n_columns
, flags
, p
,
487 message
, message_len
,
491 if (flags
& OUTPUT_CATALOG
)
497 static int output_verbose(
504 const size_t highlight
[2]) {
508 _cleanup_free_
char *cursor
= NULL
;
509 uint64_t realtime
= 0;
510 char ts
[FORMAT_TIMESTAMP_MAX
+ 7];
511 const char *timestamp
;
517 sd_journal_set_data_threshold(j
, 0);
519 r
= sd_journal_get_data(j
, "_SOURCE_REALTIME_TIMESTAMP", &data
, &length
);
521 log_debug("Source realtime timestamp not found");
523 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get source realtime timestamp: %m");
525 _cleanup_free_
char *value
= NULL
;
527 r
= parse_field(data
, length
, "_SOURCE_REALTIME_TIMESTAMP=",
528 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value
,
534 r
= safe_atou64(value
, &realtime
);
536 log_debug_errno(r
, "Failed to parse realtime timestamp: %m");
540 r
= sd_journal_get_realtime_usec(j
, &realtime
);
542 return log_full_errno(r
== -EADDRNOTAVAIL
? LOG_DEBUG
: LOG_ERR
, r
, "Failed to get realtime timestamp: %m");
545 r
= sd_journal_get_cursor(j
, &cursor
);
547 return log_error_errno(r
, "Failed to get cursor: %m");
549 timestamp
= flags
& OUTPUT_UTC
? format_timestamp_us_utc(ts
, sizeof ts
, realtime
)
550 : format_timestamp_us(ts
, sizeof ts
, realtime
);
551 fprintf(f
, "%s [%s]\n",
552 timestamp
?: "(no timestamp)",
555 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
558 const char *on
= "", *off
= "";
560 c
= memchr(data
, '=', length
);
562 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
564 fieldlen
= c
- (const char*) data
;
566 r
= field_set_test(output_fields
, data
, fieldlen
);
572 if (flags
& OUTPUT_COLOR
&& startswith(data
, "MESSAGE=")) {
577 if ((flags
& OUTPUT_SHOW_ALL
) ||
578 (((length
< PRINT_CHAR_THRESHOLD
) || flags
& OUTPUT_FULL_WIDTH
)
579 && utf8_is_printable(data
, length
))) {
580 fprintf(f
, " %s%.*s=", on
, fieldlen
, (const char*)data
);
581 print_multiline(f
, 4 + fieldlen
+ 1, 0, OUTPUT_FULL_WIDTH
, 0, c
+ 1, length
- fieldlen
- 1, NULL
);
584 char bytes
[FORMAT_BYTES_MAX
];
586 fprintf(f
, " %s%.*s=[%s blob data]%s\n",
588 (int) (c
- (const char*) data
),
590 format_bytes(bytes
, sizeof(bytes
), length
- (c
- (const char *) data
) - 1),
598 if (flags
& OUTPUT_CATALOG
)
604 static int output_export(
611 const size_t highlight
[2]) {
616 usec_t realtime
, monotonic
;
617 _cleanup_free_
char *cursor
= NULL
;
623 sd_journal_set_data_threshold(j
, 0);
625 r
= sd_journal_get_realtime_usec(j
, &realtime
);
627 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
629 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
631 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
633 r
= sd_journal_get_cursor(j
, &cursor
);
635 return log_error_errno(r
, "Failed to get cursor: %m");
639 "__REALTIME_TIMESTAMP="USEC_FMT
"\n"
640 "__MONOTONIC_TIMESTAMP="USEC_FMT
"\n"
645 sd_id128_to_string(boot_id
, sid
));
647 JOURNAL_FOREACH_DATA_RETVAL(j
, data
, length
, r
) {
650 /* We already printed the boot id from the data in the header, hence let's suppress it here */
651 if (memory_startswith(data
, length
, "_BOOT_ID="))
654 c
= memchr(data
, '=', length
);
656 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
659 r
= field_set_test(output_fields
, data
, c
- (const char *) data
);
665 if (utf8_is_printable_newline(data
, length
, false))
666 fwrite(data
, length
, 1, f
);
670 fwrite(data
, c
- (const char*) data
, 1, f
);
672 le64
= htole64(length
- (c
- (const char*) data
) - 1);
673 fwrite(&le64
, sizeof(le64
), 1, f
);
674 fwrite(c
+ 1, length
- (c
- (const char*) data
) - 1, 1, f
);
680 log_debug_errno(r
, "Skipping message we can't read: %m");
701 if (!(flags
& OUTPUT_SHOW_ALL
) && l
>= JSON_THRESHOLD
)
704 else if (!(flags
& OUTPUT_SHOW_ALL
) && !utf8_is_printable(p
, l
)) {
705 bool not_first
= false;
711 fprintf(f
, ", %u", (uint8_t) *p
);
714 fprintf(f
, "%u", (uint8_t) *p
);
726 if (IN_SET(*p
, '"', '\\')) {
729 } else if (*p
== '\n')
731 else if ((uint8_t) *p
< ' ')
732 fprintf(f
, "\\u%04x", (uint8_t) *p
);
747 JsonVariant
* values
[];
750 static int update_json_data(
757 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
761 if (!(flags
& OUTPUT_SHOW_ALL
) && strlen(name
) + 1 + size
>= JSON_THRESHOLD
)
762 r
= json_variant_new_null(&v
);
763 else if (utf8_is_printable(value
, size
))
764 r
= json_variant_new_stringn(&v
, value
, size
);
766 r
= json_variant_new_array_bytes(&v
, value
, size
);
768 return log_error_errno(r
, "Failed to allocate JSON data: %m");
770 d
= hashmap_get(h
, name
);
774 w
= realloc(d
, offsetof(struct json_data
, values
) + sizeof(JsonVariant
*) * (d
->n_values
+ 1));
779 assert_se(hashmap_update(h
, json_variant_string(d
->name
), d
) >= 0);
781 _cleanup_(json_variant_unrefp
) JsonVariant
*n
= NULL
;
783 r
= json_variant_new_string(&n
, name
);
785 return log_error_errno(r
, "Failed to allocate JSON name variant: %m");
787 d
= malloc0(offsetof(struct json_data
, values
) + sizeof(JsonVariant
*));
791 r
= hashmap_put(h
, json_variant_string(n
), d
);
794 return log_error_errno(r
, "Failed to insert JSON name into hashmap: %m");
797 d
->name
= TAKE_PTR(n
);
800 d
->values
[d
->n_values
++] = TAKE_PTR(v
);
804 static int update_json_data_split(
815 assert(data
|| size
== 0);
817 if (memory_startswith(data
, size
, "_BOOT_ID="))
820 eq
= memchr(data
, '=', MIN(size
, JSON_THRESHOLD
));
827 name
= strndupa(data
, eq
- (const char*) data
);
828 if (output_fields
&& !set_get(output_fields
, name
))
831 return update_json_data(h
, flags
, name
, eq
+ 1, size
- (eq
- (const char*) data
) - 1);
834 static int output_json(
841 const size_t highlight
[2]) {
843 char sid
[SD_ID128_STRING_MAX
], usecbuf
[DECIMAL_STR_MAX(usec_t
)];
844 _cleanup_(json_variant_unrefp
) JsonVariant
*object
= NULL
;
845 _cleanup_free_
char *cursor
= NULL
;
846 uint64_t realtime
, monotonic
;
847 JsonVariant
**array
= NULL
;
857 (void) sd_journal_set_data_threshold(j
, flags
& OUTPUT_SHOW_ALL
? 0 : JSON_THRESHOLD
);
859 r
= sd_journal_get_realtime_usec(j
, &realtime
);
861 return log_error_errno(r
, "Failed to get realtime timestamp: %m");
863 r
= sd_journal_get_monotonic_usec(j
, &monotonic
, &boot_id
);
865 return log_error_errno(r
, "Failed to get monotonic timestamp: %m");
867 r
= sd_journal_get_cursor(j
, &cursor
);
869 return log_error_errno(r
, "Failed to get cursor: %m");
871 h
= hashmap_new(&string_hash_ops
);
875 r
= update_json_data(h
, flags
, "__CURSOR", cursor
, strlen(cursor
));
879 xsprintf(usecbuf
, USEC_FMT
, realtime
);
880 r
= update_json_data(h
, flags
, "__REALTIME_TIMESTAMP", usecbuf
, strlen(usecbuf
));
884 xsprintf(usecbuf
, USEC_FMT
, monotonic
);
885 r
= update_json_data(h
, flags
, "__MONOTONIC_TIMESTAMP", usecbuf
, strlen(usecbuf
));
889 sd_id128_to_string(boot_id
, sid
);
890 r
= update_json_data(h
, flags
, "_BOOT_ID", sid
, strlen(sid
));
898 r
= sd_journal_enumerate_data(j
, &data
, &size
);
900 log_debug_errno(r
, "Skipping message we can't read: %m");
905 log_error_errno(r
, "Failed to read journal: %m");
911 r
= update_json_data_split(h
, flags
, output_fields
, data
, size
);
916 array
= new(JsonVariant
*, hashmap_size(h
)*2);
922 HASHMAP_FOREACH(d
, h
, i
) {
923 assert(d
->n_values
> 0);
925 array
[n
++] = json_variant_ref(d
->name
);
927 if (d
->n_values
== 1)
928 array
[n
++] = json_variant_ref(d
->values
[0]);
930 _cleanup_(json_variant_unrefp
) JsonVariant
*q
= NULL
;
932 r
= json_variant_new_array(&q
, d
->values
, d
->n_values
);
934 log_error_errno(r
, "Failed to create JSON array: %m");
938 array
[n
++] = TAKE_PTR(q
);
942 r
= json_variant_new_object(&object
, array
, n
);
944 log_error_errno(r
, "Failed to allocate JSON object: %m");
948 json_variant_dump(object
,
949 output_mode_to_json_format_flags(mode
) |
950 (FLAGS_SET(flags
, OUTPUT_COLOR
) ? JSON_FORMAT_COLOR
: 0),
956 while ((d
= hashmap_steal_first(h
))) {
959 json_variant_unref(d
->name
);
960 for (k
= 0; k
< d
->n_values
; k
++)
961 json_variant_unref(d
->values
[k
]);
968 json_variant_unref_many(array
, n
);
974 static int output_cat(
981 const size_t highlight
[2]) {
986 const char *highlight_on
= "", *highlight_off
= "";
991 if (flags
& OUTPUT_COLOR
) {
992 highlight_on
= ANSI_HIGHLIGHT_RED
;
993 highlight_off
= ANSI_NORMAL
;
996 sd_journal_set_data_threshold(j
, 0);
998 r
= sd_journal_get_data(j
, "MESSAGE", &data
, &l
);
1000 log_debug_errno(r
, "Skipping message we can't read: %m");
1004 /* An entry without MESSAGE=? */
1008 return log_error_errno(r
, "Failed to get data: %m");
1013 if (highlight
&& (flags
& OUTPUT_COLOR
)) {
1014 assert(highlight
[0] <= highlight
[1]);
1015 assert(highlight
[1] <= l
- 8);
1017 fwrite((const char*) data
+ 8, 1, highlight
[0], f
);
1018 fwrite(highlight_on
, 1, strlen(highlight_on
), f
);
1019 fwrite((const char*) data
+ 8 + highlight
[0], 1, highlight
[1] - highlight
[0], f
);
1020 fwrite(highlight_off
, 1, strlen(highlight_off
), f
);
1021 fwrite((const char*) data
+ 8 + highlight
[1], 1, l
- 8 - highlight
[1], f
);
1023 fwrite((const char*) data
+ 8, 1, l
- 8, f
);
1029 static int (*output_funcs
[_OUTPUT_MODE_MAX
])(
1036 const size_t highlight
[2]) = {
1038 [OUTPUT_SHORT
] = output_short
,
1039 [OUTPUT_SHORT_ISO
] = output_short
,
1040 [OUTPUT_SHORT_ISO_PRECISE
] = output_short
,
1041 [OUTPUT_SHORT_PRECISE
] = output_short
,
1042 [OUTPUT_SHORT_MONOTONIC
] = output_short
,
1043 [OUTPUT_SHORT_UNIX
] = output_short
,
1044 [OUTPUT_SHORT_FULL
] = output_short
,
1045 [OUTPUT_VERBOSE
] = output_verbose
,
1046 [OUTPUT_EXPORT
] = output_export
,
1047 [OUTPUT_JSON
] = output_json
,
1048 [OUTPUT_JSON_PRETTY
] = output_json
,
1049 [OUTPUT_JSON_SSE
] = output_json
,
1050 [OUTPUT_JSON_SEQ
] = output_json
,
1051 [OUTPUT_CAT
] = output_cat
,
1052 [OUTPUT_WITH_UNIT
] = output_short
,
1055 int show_journal_entry(
1061 char **output_fields
,
1062 const size_t highlight
[2],
1066 _cleanup_set_free_free_ Set
*fields
= NULL
;
1068 assert(mode
< _OUTPUT_MODE_MAX
);
1071 n_columns
= columns();
1073 if (output_fields
) {
1074 fields
= set_new(&string_hash_ops
);
1078 ret
= set_put_strdupv(fields
, output_fields
);
1083 ret
= output_funcs
[mode
](f
, j
, mode
, n_columns
, flags
, fields
, highlight
);
1085 if (ellipsized
&& ret
> 0)
1091 static int maybe_print_begin_newline(FILE *f
, OutputFlags
*flags
) {
1095 if (!(*flags
& OUTPUT_BEGIN_NEWLINE
))
1098 /* Print a beginning new line if that's request, but only once
1099 * on the first line we print. */
1102 *flags
&= ~OUTPUT_BEGIN_NEWLINE
;
1118 bool need_seek
= false;
1119 int warn_cutoff
= flags
& OUTPUT_WARN_CUTOFF
;
1123 assert(mode
< _OUTPUT_MODE_MAX
);
1125 if (how_many
== (unsigned) -1)
1129 r
= sd_journal_seek_tail(j
);
1131 return log_error_errno(r
, "Failed to seek to tail: %m");
1133 r
= sd_journal_previous_skip(j
, how_many
);
1135 return log_error_errno(r
, "Failed to skip previous: %m");
1143 r
= sd_journal_next(j
);
1145 return log_error_errno(r
, "Failed to iterate through journal: %m");
1153 if (not_before
> 0) {
1154 r
= sd_journal_get_monotonic_usec(j
, &usec
, NULL
);
1156 /* -ESTALE is returned if the
1157 timestamp is not from this boot */
1161 return log_error_errno(r
, "Failed to get journal time: %m");
1163 if (usec
< not_before
)
1168 maybe_print_begin_newline(f
, &flags
);
1170 r
= show_journal_entry(f
, j
, mode
, n_columns
, flags
, NULL
, NULL
, ellipsized
);
1175 if (warn_cutoff
&& line
< how_many
&& not_before
> 0) {
1179 /* Check whether the cutoff line is too early */
1181 r
= sd_id128_get_boot(&boot_id
);
1183 return log_error_errno(r
, "Failed to get boot id: %m");
1185 r
= sd_journal_get_cutoff_monotonic_usec(j
, boot_id
, &cutoff
, NULL
);
1187 return log_error_errno(r
, "Failed to get journal cutoff time: %m");
1189 if (r
> 0 && not_before
< cutoff
) {
1190 maybe_print_begin_newline(f
, &flags
);
1191 fprintf(f
, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
1194 warn_cutoff
= false;
1197 if (!(flags
& OUTPUT_FOLLOW
))
1200 r
= sd_journal_wait(j
, USEC_INFINITY
);
1202 return log_error_errno(r
, "Failed to wait for journal: %m");
1209 int add_matches_for_unit(sd_journal
*j
, const char *unit
) {
1210 const char *m1
, *m2
, *m3
, *m4
;
1216 m1
= strjoina("_SYSTEMD_UNIT=", unit
);
1217 m2
= strjoina("COREDUMP_UNIT=", unit
);
1218 m3
= strjoina("UNIT=", unit
);
1219 m4
= strjoina("OBJECT_SYSTEMD_UNIT=", unit
);
1222 /* Look for messages from the service itself */
1223 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1225 /* Look for coredumps of the service */
1226 (r
= sd_journal_add_disjunction(j
)) ||
1227 (r
= sd_journal_add_match(j
, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1228 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1229 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1231 /* Look for messages from PID 1 about this service */
1232 (r
= sd_journal_add_disjunction(j
)) ||
1233 (r
= sd_journal_add_match(j
, "_PID=1", 0)) ||
1234 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1236 /* Look for messages from authorized daemons about this service */
1237 (r
= sd_journal_add_disjunction(j
)) ||
1238 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1239 (r
= sd_journal_add_match(j
, m4
, 0))
1242 if (r
== 0 && endswith(unit
, ".slice")) {
1245 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1247 /* Show all messages belonging to a slice */
1249 (r
= sd_journal_add_disjunction(j
)) ||
1250 (r
= sd_journal_add_match(j
, m5
, 0))
1257 int add_matches_for_user_unit(sd_journal
*j
, const char *unit
, uid_t uid
) {
1259 char *m1
, *m2
, *m3
, *m4
;
1260 char muid
[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t
)];
1265 m1
= strjoina("_SYSTEMD_USER_UNIT=", unit
);
1266 m2
= strjoina("USER_UNIT=", unit
);
1267 m3
= strjoina("COREDUMP_USER_UNIT=", unit
);
1268 m4
= strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit
);
1269 sprintf(muid
, "_UID="UID_FMT
, uid
);
1272 /* Look for messages from the user service itself */
1273 (r
= sd_journal_add_match(j
, m1
, 0)) ||
1274 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1276 /* Look for messages from systemd about this service */
1277 (r
= sd_journal_add_disjunction(j
)) ||
1278 (r
= sd_journal_add_match(j
, m2
, 0)) ||
1279 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1281 /* Look for coredumps of the service */
1282 (r
= sd_journal_add_disjunction(j
)) ||
1283 (r
= sd_journal_add_match(j
, m3
, 0)) ||
1284 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1285 (r
= sd_journal_add_match(j
, "_UID=0", 0)) ||
1287 /* Look for messages from authorized daemons about this service */
1288 (r
= sd_journal_add_disjunction(j
)) ||
1289 (r
= sd_journal_add_match(j
, m4
, 0)) ||
1290 (r
= sd_journal_add_match(j
, muid
, 0)) ||
1291 (r
= sd_journal_add_match(j
, "_UID=0", 0))
1294 if (r
== 0 && endswith(unit
, ".slice")) {
1297 m5
= strjoina("_SYSTEMD_SLICE=", unit
);
1299 /* Show all messages belonging to a slice */
1301 (r
= sd_journal_add_disjunction(j
)) ||
1302 (r
= sd_journal_add_match(j
, m5
, 0)) ||
1303 (r
= sd_journal_add_match(j
, muid
, 0))
1310 static int get_boot_id_for_machine(const char *machine
, sd_id128_t
*boot_id
) {
1311 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1312 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
1321 if (!machine_name_is_valid(machine
))
1324 r
= container_get_leader(machine
, &pid
);
1328 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, NULL
, &rootfd
);
1332 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1335 r
= namespace_fork("(sd-bootidns)", "(sd-bootid)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1336 pidnsfd
, mntnsfd
, -1, -1, rootfd
, &child
);
1342 pair
[0] = safe_close(pair
[0]);
1344 fd
= open("/proc/sys/kernel/random/boot_id", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1346 _exit(EXIT_FAILURE
);
1348 r
= loop_read_exact(fd
, buf
, 36, false);
1351 _exit(EXIT_FAILURE
);
1353 k
= send(pair
[1], buf
, 36, MSG_NOSIGNAL
);
1355 _exit(EXIT_FAILURE
);
1357 _exit(EXIT_SUCCESS
);
1360 pair
[1] = safe_close(pair
[1]);
1362 r
= wait_for_terminate_and_check("(sd-bootidns)", child
, 0);
1365 if (r
!= EXIT_SUCCESS
)
1368 k
= recv(pair
[0], buf
, 36, 0);
1373 r
= sd_id128_from_string(buf
, boot_id
);
1380 int add_match_this_boot(sd_journal
*j
, const char *machine
) {
1381 char match
[9+32+1] = "_BOOT_ID=";
1388 r
= get_boot_id_for_machine(machine
, &boot_id
);
1390 return log_error_errno(r
, "Failed to get boot id of container %s: %m", machine
);
1392 r
= sd_id128_get_boot(&boot_id
);
1394 return log_error_errno(r
, "Failed to get boot id: %m");
1397 sd_id128_to_string(boot_id
, match
+ 9);
1398 r
= sd_journal_add_match(j
, match
, strlen(match
));
1400 return log_error_errno(r
, "Failed to add match: %m");
1402 r
= sd_journal_add_conjunction(j
);
1404 return log_error_errno(r
, "Failed to add conjunction: %m");
1409 int show_journal_by_unit(
1418 int journal_open_flags
,
1422 _cleanup_(sd_journal_closep
) sd_journal
*j
= NULL
;
1426 assert(mode
< _OUTPUT_MODE_MAX
);
1432 r
= sd_journal_open(&j
, journal_open_flags
);
1434 return log_error_errno(r
, "Failed to open journal: %m");
1436 r
= add_match_this_boot(j
, NULL
);
1441 r
= add_matches_for_unit(j
, unit
);
1443 r
= add_matches_for_user_unit(j
, unit
, uid
);
1445 return log_error_errno(r
, "Failed to add unit matches: %m");
1447 if (DEBUG_LOGGING
) {
1448 _cleanup_free_
char *filter
;
1450 filter
= journal_make_match_string(j
);
1454 log_debug("Journal filter: %s", filter
);
1457 return show_journal(f
, j
, mode
, n_columns
, not_before
, how_many
, flags
, ellipsized
);