Skip to content

Commit c5522f8

Browse files
pfmooneyarekinath
authored andcommitted
Omit bunyan timestamps when logging to journald
1 parent 819edc9 commit c5522f8

File tree

1 file changed

+57
-3
lines changed

1 file changed

+57
-3
lines changed

bunyan.c

+57-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ static const char *bunyan_name = NULL;
2727
static char *bunyan_buf = NULL;
2828
static size_t bunyan_buf_sz = 0;
2929
static enum bunyan_log_level bunyan_min_level = WARN;
30+
static boolean_t bunyan_omit_timestamp = B_FALSE;
3031

3132
struct bunyan_var {
3233
struct bunyan_var *bv_next;
@@ -260,9 +261,59 @@ bny_timer_print(struct bunyan_timers *tms)
260261
return (0);
261262
}
262263

264+
#if defined(__linux__)
265+
static boolean_t
266+
bunyan_detect_journald(void)
267+
{
268+
char *envp;
269+
270+
/*
271+
* If journald is providing logging for this process, it will set
272+
* JOURNAL_STREAM to <dev>:<inode>, corresponding to the device and
273+
* inode of the socket attached to stderr and stdout.
274+
*/
275+
if ((envp = getenv("JOURNAL_STREAM")) != NULL) {
276+
char *devp, *inop;
277+
unsigned long device = ULONG_MAX, inode = ULONG_MAX;
278+
279+
if ((devp = strdup(envp)) != NULL) {
280+
inop = strstr(devp, ":");
281+
if (inop != NULL) {
282+
*inop = '\0';
283+
inop++;
284+
device = strtoul(devp, NULL, 10);
285+
inode = strtoul(inop, NULL, 10);
286+
}
287+
free(devp);
288+
}
289+
290+
if (device != ULONG_MAX && inode != ULONG_MAX) {
291+
struct stat info;
292+
293+
if (fstat(STDERR_FILENO, &info) == 0) {
294+
if (info.st_dev == device &&
295+
info.st_ino == inode) {
296+
return (B_TRUE);
297+
}
298+
}
299+
}
300+
}
301+
return (B_FALSE);
302+
}
303+
#endif /* defined (__linux__) */
304+
263305
void
264306
bunyan_init(void)
265307
{
308+
#if defined(__linux__)
309+
/*
310+
* When logging to journald, generating our own timestamps is
311+
* unecessary as the journal has its own native ones.
312+
*/
313+
if (bunyan_detect_journald()) {
314+
bunyan_omit_timestamp = B_TRUE;
315+
}
316+
#endif
266317
}
267318

268319
void
@@ -469,7 +520,6 @@ print_frame(struct bunyan_frame *frame, uint *pn, struct bunyan_var **evars)
469520
void
470521
bunyan_log(enum bunyan_log_level level, const char *msg, ...)
471522
{
472-
char time[128];
473523
va_list ap;
474524
const char *propname;
475525
errf_t *err = NULL;
@@ -480,8 +530,12 @@ bunyan_log(enum bunyan_log_level level, const char *msg, ...)
480530

481531
reset_buf();
482532

483-
bunyan_timestamp(time, sizeof (time));
484-
printf_buf("[%s] ", time);
533+
if (!bunyan_omit_timestamp) {
534+
char time[128];
535+
536+
bunyan_timestamp(time, sizeof (time));
537+
printf_buf("[%s] ", time);
538+
}
485539

486540
switch (level) {
487541
case TRACE:

0 commit comments

Comments
 (0)